@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.js CHANGED
@@ -40,6 +40,530 @@ function renderTemplate(container, items, optionTemplate) {
40
40
  container.replaceChildren(frag);
41
41
  }
42
42
 
43
+ const objectKeyCache = new WeakMap();
44
+ let generatedObjectKeyId = 0;
45
+ function isObjectRecord(value) {
46
+ return value !== null && (typeof value === 'object' || typeof value === 'function');
47
+ }
48
+ function readField(item, field) {
49
+ if (!field || !isObjectRecord(item))
50
+ return undefined;
51
+ return item[field];
52
+ }
53
+ function toSelectKey(value) {
54
+ if (typeof value === 'string' || typeof value === 'number') {
55
+ return value;
56
+ }
57
+ if (typeof value === 'boolean' || typeof value === 'bigint' || typeof value === 'symbol') {
58
+ return String(value);
59
+ }
60
+ return null;
61
+ }
62
+ function objectIdentityKey(item) {
63
+ const cached = objectKeyCache.get(item);
64
+ if (cached)
65
+ return cached;
66
+ generatedObjectKeyId += 1;
67
+ const key = `__smilodon-object-${generatedObjectKeyId}`;
68
+ objectKeyCache.set(item, key);
69
+ return key;
70
+ }
71
+ function indexFallbackKey(index, warn) {
72
+ const env = globalThis.process?.env?.NODE_ENV;
73
+ if (env !== 'production') {
74
+ const message = '[Smilodon Phase2] Using index as key is unstable under filtering/sorting. Provide getKey/valueField for stable selection.';
75
+ if (warn) {
76
+ warn(message);
77
+ }
78
+ else {
79
+ console.warn(message);
80
+ }
81
+ }
82
+ return `__smilodon-index-${index}`;
83
+ }
84
+ /** Generated reference keys survive reorder, but not replacement with new objects. */
85
+ function createDefaultItemAdapter(options = {}) {
86
+ return {
87
+ getKey(item, index) {
88
+ if (options.getKey) {
89
+ return options.getKey(item, index);
90
+ }
91
+ if (isObjectRecord(item)) {
92
+ const directKey = toSelectKey(item.id)
93
+ ?? toSelectKey(item.key)
94
+ ?? toSelectKey(item.value)
95
+ ?? toSelectKey(readField(item, options.valueField));
96
+ if (directKey !== null) {
97
+ return directKey;
98
+ }
99
+ if (options.getValue) {
100
+ const configuredValueKey = toSelectKey(options.getValue(item, index));
101
+ if (configuredValueKey !== null) {
102
+ return configuredValueKey;
103
+ }
104
+ }
105
+ return options.keyFallback === 'index'
106
+ ? indexFallbackKey(index, options.onIndexFallback)
107
+ : objectIdentityKey(item);
108
+ }
109
+ return String(item);
110
+ },
111
+ getValue(item, index) {
112
+ if (options.getValue) {
113
+ return options.getValue(item, index);
114
+ }
115
+ const fieldValue = readField(item, options.valueField);
116
+ if (fieldValue !== undefined) {
117
+ return fieldValue;
118
+ }
119
+ return isObjectRecord(item) && item.value !== undefined ? item.value : item;
120
+ },
121
+ getLabel(item, index) {
122
+ if (options.getLabel) {
123
+ return options.getLabel(item, index);
124
+ }
125
+ const fieldLabel = readField(item, options.labelField);
126
+ if (fieldLabel !== undefined) {
127
+ return String(fieldLabel);
128
+ }
129
+ if (isObjectRecord(item) && item.label !== undefined) {
130
+ return String(item.label);
131
+ }
132
+ if (isObjectRecord(item) && item.text !== undefined) {
133
+ return String(item.text);
134
+ }
135
+ return String(item);
136
+ },
137
+ isDisabled(item, index) {
138
+ if (options.isDisabled) {
139
+ return options.isDisabled(item, index);
140
+ }
141
+ return Boolean(isObjectRecord(item) && item.disabled);
142
+ },
143
+ getGroupKey(item, index) {
144
+ if (options.getGroupKey) {
145
+ return options.getGroupKey(item, index);
146
+ }
147
+ if (!isObjectRecord(item) || item.group === undefined) {
148
+ return null;
149
+ }
150
+ return item.group == null ? null : String(item.group);
151
+ },
152
+ };
153
+ }
154
+
155
+ function getDefaultDuplicateKeyPolicy() {
156
+ const env = globalThis.process?.env?.NODE_ENV;
157
+ return env === 'production' ? 'warn' : 'throw';
158
+ }
159
+ function createItemRegistry(items, adapter, options = {}) {
160
+ const duplicateKeyPolicy = options.duplicateKeyPolicy ?? getDefaultDuplicateKeyPolicy();
161
+ const records = [];
162
+ const keyToRecord = new Map();
163
+ const indexToKey = new Map();
164
+ const keyToIndex = new Map();
165
+ const firstIndexByKey = new Map();
166
+ const duplicateKeys = [];
167
+ items.forEach((item, index) => {
168
+ const key = adapter.getKey(item, index);
169
+ const firstIndex = firstIndexByKey.get(key);
170
+ const record = {
171
+ key,
172
+ item,
173
+ index,
174
+ label: adapter.getLabel(item, index),
175
+ value: adapter.getValue(item, index),
176
+ disabled: adapter.isDisabled?.(item, index) === true,
177
+ groupKey: adapter.getGroupKey?.(item, index) ?? null,
178
+ };
179
+ records.push(record);
180
+ indexToKey.set(index, key);
181
+ if (firstIndex !== undefined) {
182
+ const diagnostic = {
183
+ key,
184
+ firstIndex,
185
+ duplicateIndex: index,
186
+ };
187
+ duplicateKeys.push(diagnostic);
188
+ if (duplicateKeyPolicy === 'throw') {
189
+ throw new Error(duplicateKeyMessage(diagnostic));
190
+ }
191
+ if (duplicateKeyPolicy === 'warn') {
192
+ if (options.onDuplicateKey) {
193
+ options.onDuplicateKey(diagnostic);
194
+ }
195
+ else {
196
+ console.warn(duplicateKeyMessage(diagnostic));
197
+ }
198
+ return;
199
+ }
200
+ if (duplicateKeyPolicy === 'first-wins') {
201
+ return;
202
+ }
203
+ }
204
+ else {
205
+ firstIndexByKey.set(key, index);
206
+ }
207
+ keyToRecord.set(key, record);
208
+ keyToIndex.set(key, index);
209
+ });
210
+ return {
211
+ records,
212
+ keyToRecord,
213
+ indexToKey,
214
+ keyToIndex,
215
+ duplicateKeys,
216
+ };
217
+ }
218
+ function duplicateKeyMessage(diagnostic) {
219
+ return `[Smilodon Phase2] Duplicate item key "${String(diagnostic.key)}" at indexes ${diagnostic.firstIndex} and ${diagnostic.duplicateIndex}. Provide stable unique keys for selection.`;
220
+ }
221
+
222
+ /** Pure key policy. Visibility does not constrain selection; disabled keys do. */
223
+ function applySelectionRequest(selectedKeys, request, config) {
224
+ let next;
225
+ switch (request.type) {
226
+ case 'select':
227
+ next = selectKey(selectedKeys, request.key, config);
228
+ break;
229
+ case 'deselect':
230
+ next = deselectKey(selectedKeys, request.key, config);
231
+ break;
232
+ case 'toggle':
233
+ if (!selectedKeys.has(request.key)) {
234
+ next = selectKey(selectedKeys, request.key, config);
235
+ }
236
+ else if (config.multiple || config.allowDeselect) {
237
+ next = deselectKey(selectedKeys, request.key, config);
238
+ }
239
+ else {
240
+ next = selectedKeys;
241
+ }
242
+ break;
243
+ case 'clear':
244
+ next = config.required && selectedKeys.size > 0
245
+ ? selectedKeys
246
+ : new Set();
247
+ break;
248
+ case 'replace':
249
+ next = replaceKeys(selectedKeys, request.keys, config);
250
+ break;
251
+ }
252
+ // Set membership is authoritative. Reordering the same keys is not a change.
253
+ return next.size === selectedKeys.size && [...next].every((key) => selectedKeys.has(key))
254
+ ? selectedKeys
255
+ : next;
256
+ }
257
+ function selectKey(selectedKeys, key, config) {
258
+ if (config.disabledKeys.has(key)) {
259
+ return selectedKeys;
260
+ }
261
+ if (!config.multiple) {
262
+ return new Set([key]);
263
+ }
264
+ if (selectedKeys.has(key)) {
265
+ return selectedKeys;
266
+ }
267
+ const maxSelections = config.maxSelections ?? 0;
268
+ if (maxSelections > 0 && selectedKeys.size >= maxSelections) {
269
+ return selectedKeys;
270
+ }
271
+ return new Set([...selectedKeys, key]);
272
+ }
273
+ function deselectKey(selectedKeys, key, config) {
274
+ if (!selectedKeys.has(key) || config.disabledKeys.has(key)) {
275
+ return selectedKeys;
276
+ }
277
+ if (config.required && selectedKeys.size <= 1) {
278
+ return selectedKeys;
279
+ }
280
+ const next = new Set(selectedKeys);
281
+ next.delete(key);
282
+ return next;
283
+ }
284
+ function replaceKeys(selectedKeys, keys, config) {
285
+ const next = normalizeKeys(keys, config);
286
+ if (config.required && next.size === 0 && selectedKeys.size > 0) {
287
+ // Required preserves a valid selection, but cannot keep newly disabled keys.
288
+ return normalizeKeys(selectedKeys, config);
289
+ }
290
+ return next;
291
+ }
292
+ function normalizeKeys(keys, config) {
293
+ const seen = new Set();
294
+ const maxSelections = config.maxSelections ?? 0;
295
+ for (const key of keys) {
296
+ if (config.disabledKeys.has(key) || seen.has(key)) {
297
+ continue;
298
+ }
299
+ seen.add(key);
300
+ if (!config.multiple || (maxSelections > 0 && seen.size >= maxSelections)) {
301
+ break;
302
+ }
303
+ }
304
+ return seen;
305
+ }
306
+
307
+ function transition(state, event) {
308
+ switch (event.type) {
309
+ case 'CONNECT':
310
+ return { state: { ...state, lifecycle: 'connected' }, effects: [] };
311
+ case 'DISCONNECT': {
312
+ const effects = state.popup === 'open'
313
+ ? [{ type: 'POPUP_CLOSED', reason: 'disconnect' }, { type: 'SYNC_ARIA' }]
314
+ : [];
315
+ return {
316
+ state: { ...state, lifecycle: 'disconnected', popup: 'closed', focused: false },
317
+ effects,
318
+ };
319
+ }
320
+ case 'OPEN_REQUEST':
321
+ if (state.lifecycle !== 'connected' || state.disabled || state.popup === 'open') {
322
+ return { state: enforceInvariants(state), effects: [] };
323
+ }
324
+ return {
325
+ state: { ...state, popup: 'open' },
326
+ effects: [{ type: 'POPUP_OPENED' }, { type: 'FOCUS_TRIGGER' }, { type: 'SYNC_ARIA' }],
327
+ };
328
+ case 'CLOSE_REQUEST':
329
+ if (state.popup === 'closed') {
330
+ return { state, effects: [] };
331
+ }
332
+ return {
333
+ state: { ...state, popup: 'closed' },
334
+ effects: [{ type: 'POPUP_CLOSED', reason: event.reason }, { type: 'SYNC_ARIA' }],
335
+ };
336
+ case 'TOGGLE_REQUEST':
337
+ return transition(state, state.popup === 'open'
338
+ ? { type: 'CLOSE_REQUEST', reason: 'programmatic' }
339
+ : { type: 'OPEN_REQUEST' });
340
+ case 'FOCUS_GAINED':
341
+ return state.focused
342
+ ? { state, effects: [] }
343
+ : { state: { ...state, focused: true }, effects: [{ type: 'SYNC_ARIA' }] };
344
+ case 'FOCUS_LOST':
345
+ return state.focused
346
+ ? { state: { ...state, focused: false }, effects: [{ type: 'SYNC_ARIA' }] }
347
+ : { state, effects: [] };
348
+ case 'DISABLED_CHANGED': {
349
+ if (state.disabled === event.disabled) {
350
+ return { state: enforceInvariants(state), effects: [] };
351
+ }
352
+ const nextState = enforceInvariants({ ...state, disabled: event.disabled });
353
+ const effects = [];
354
+ if (event.disabled && state.popup === 'open') {
355
+ effects.push({ type: 'POPUP_CLOSED', reason: 'disabled' });
356
+ }
357
+ effects.push({ type: 'SYNC_ARIA' });
358
+ return {
359
+ state: nextState,
360
+ effects,
361
+ };
362
+ }
363
+ case 'ITEMS_REGISTERED': {
364
+ const registeredKeys = new Set(event.keys);
365
+ const disabledKeys = new Set(event.disabledKeys ?? []);
366
+ const selection = { ...state.selection, disabledKeys };
367
+ const activeKey = resolveActiveKey(state.activeKey, registeredKeys, disabledKeys);
368
+ const selectedKeys = applySelectionRequest(state.selectedKeys, { type: 'replace', keys: Array.from(state.selectedKeys)}, selection);
369
+ const nextState = {
370
+ ...state,
371
+ activeKey,
372
+ selectedKeys,
373
+ registeredKeys,
374
+ selection,
375
+ };
376
+ const effects = [];
377
+ if (!keysEqual(activeKey, state.activeKey)) {
378
+ effects.push({ type: 'ACTIVE_KEY_CHANGED', activeKey, reason: 'programmatic' });
379
+ }
380
+ if (!setsEqual(selectedKeys, state.selectedKeys)) {
381
+ effects.push({ type: 'SELECTION_CHANGED', selectedKeys: Array.from(selectedKeys), reason: 'programmatic' });
382
+ }
383
+ if (effects.length > 0) {
384
+ effects.push({ type: 'SYNC_ARIA' });
385
+ }
386
+ return { state: nextState, effects };
387
+ }
388
+ case 'SELECTION_CONFIG_CHANGED': {
389
+ const selection = {
390
+ ...state.selection,
391
+ multiple: event.multiple ?? state.selection.multiple,
392
+ required: event.required ?? state.selection.required,
393
+ allowDeselect: event.allowDeselect ?? state.selection.allowDeselect,
394
+ maxSelections: event.maxSelections ?? state.selection.maxSelections,
395
+ disabledKeys: event.disabledKeys ? new Set(event.disabledKeys) : state.selection.disabledKeys,
396
+ };
397
+ const selectedKeys = applySelectionRequest(state.selectedKeys, { type: 'replace', keys: Array.from(state.selectedKeys)}, selection);
398
+ const activeKey = resolveActiveKey(state.activeKey, state.registeredKeys, selection.disabledKeys);
399
+ const nextState = { ...state, selection, selectedKeys, activeKey };
400
+ const effects = [];
401
+ if (!keysEqual(activeKey, state.activeKey)) {
402
+ effects.push({ type: 'ACTIVE_KEY_CHANGED', activeKey, reason: 'programmatic' });
403
+ }
404
+ if (!setsEqual(selectedKeys, state.selectedKeys)) {
405
+ effects.push({ type: 'SELECTION_CHANGED', selectedKeys: Array.from(selectedKeys), reason: 'programmatic' });
406
+ }
407
+ if (effects.length > 0) {
408
+ effects.push({ type: 'SYNC_ARIA' });
409
+ }
410
+ return { state: nextState, effects };
411
+ }
412
+ case 'ACTIVE_KEY_CHANGED': {
413
+ if (event.key !== null
414
+ && (!state.registeredKeys.has(event.key) || state.selection.disabledKeys.has(event.key))) {
415
+ return { state, effects: [] };
416
+ }
417
+ if (keysEqual(state.activeKey, event.key)) {
418
+ return { state, effects: [] };
419
+ }
420
+ return {
421
+ state: { ...state, activeKey: event.key },
422
+ effects: [
423
+ { type: 'ACTIVE_KEY_CHANGED', activeKey: event.key, reason: event.reason },
424
+ { type: 'SYNC_ARIA' },
425
+ ],
426
+ };
427
+ }
428
+ case 'SELECT_KEY_REQUEST':
429
+ case 'DESELECT_KEY_REQUEST':
430
+ case 'TOGGLE_KEY_REQUEST':
431
+ case 'CLEAR_SELECTION_REQUEST':
432
+ case 'REPLACE_SELECTION_REQUEST': {
433
+ const selectedKeys = applySelectionRequest(state.selectedKeys, selectionRequestFromEvent(event), state.selection);
434
+ if (setsEqual(selectedKeys, state.selectedKeys)) {
435
+ return { state, effects: [] };
436
+ }
437
+ return {
438
+ state: { ...state, selectedKeys },
439
+ effects: [
440
+ { type: 'SELECTION_CHANGED', selectedKeys: Array.from(selectedKeys), reason: event.reason },
441
+ { type: 'SYNC_ARIA' },
442
+ ],
443
+ };
444
+ }
445
+ default:
446
+ return { state, effects: [] };
447
+ }
448
+ }
449
+ function selectionRequestFromEvent(event) {
450
+ switch (event.type) {
451
+ case 'SELECT_KEY_REQUEST':
452
+ return { type: 'select', key: event.key, reason: event.reason };
453
+ case 'DESELECT_KEY_REQUEST':
454
+ return { type: 'deselect', key: event.key, reason: event.reason };
455
+ case 'TOGGLE_KEY_REQUEST':
456
+ return { type: 'toggle', key: event.key, reason: event.reason };
457
+ case 'CLEAR_SELECTION_REQUEST':
458
+ return { type: 'clear', reason: event.reason };
459
+ case 'REPLACE_SELECTION_REQUEST':
460
+ return { type: 'replace', keys: event.keys, reason: event.reason };
461
+ }
462
+ }
463
+ function enforceInvariants(state) {
464
+ if (state.lifecycle === 'disconnected' || state.disabled) {
465
+ return state.popup === 'closed' ? state : { ...state, popup: 'closed' };
466
+ }
467
+ return state;
468
+ }
469
+ function resolveActiveKey(key, registeredKeys, disabledKeys) {
470
+ return key !== null && registeredKeys.has(key) && !disabledKeys.has(key) ? key : null;
471
+ }
472
+ function setsEqual(left, right) {
473
+ if (left.size !== right.size)
474
+ return false;
475
+ for (const value of left) {
476
+ if (!right.has(value))
477
+ return false;
478
+ }
479
+ return true;
480
+ }
481
+ /** Match Map/Set identity, including NaN and signed zero. */
482
+ function keysEqual(left, right) {
483
+ return left === right || Object.is(left, right);
484
+ }
485
+
486
+ function createInitialSelectState() {
487
+ return {
488
+ lifecycle: 'disconnected',
489
+ popup: 'closed',
490
+ disabled: false,
491
+ focused: false,
492
+ query: '',
493
+ activeKey: null,
494
+ selectedKeys: new Set(),
495
+ registeredKeys: new Set(),
496
+ selection: {
497
+ multiple: false,
498
+ required: false,
499
+ allowDeselect: false,
500
+ disabledKeys: new Set(),
501
+ maxSelections: 0,
502
+ },
503
+ dataStatus: 'idle',
504
+ };
505
+ }
506
+
507
+ function isOpen(state) {
508
+ return state.popup === 'open';
509
+ }
510
+ function isDisabled(state) {
511
+ return state.disabled;
512
+ }
513
+ function isFocused(state) {
514
+ return state.focused;
515
+ }
516
+ function hasSelection(state) {
517
+ return state.selectedKeys.size > 0;
518
+ }
519
+ function isSelected(state, key) {
520
+ return state.selectedKeys.has(key);
521
+ }
522
+ function getSelectedKeys(state) {
523
+ return Array.from(state.selectedKeys);
524
+ }
525
+ function getActiveKey(state) {
526
+ return state.activeKey;
527
+ }
528
+ function isRegisteredKey(state, key) {
529
+ return state.registeredKeys.has(key);
530
+ }
531
+
532
+ class SelectEngineBridge {
533
+ constructor(initialState = createInitialSelectState()) {
534
+ this._state = initialState;
535
+ }
536
+ get state() {
537
+ return this._state;
538
+ }
539
+ dispatch(event) {
540
+ const result = transition(this._state, event);
541
+ this._state = result.state;
542
+ return result.effects;
543
+ }
544
+ }
545
+
546
+ class DefaultSelectEffectRunner {
547
+ run(effects, context) {
548
+ for (const effect of effects) {
549
+ switch (effect.type) {
550
+ case 'FOCUS_TRIGGER':
551
+ context.focusTrigger?.();
552
+ break;
553
+ case 'SYNC_ARIA':
554
+ context.syncAria?.();
555
+ break;
556
+ case 'POPUP_OPENED':
557
+ context.onPopupOpened?.();
558
+ break;
559
+ case 'POPUP_CLOSED':
560
+ context.onPopupClosed?.(effect.reason);
561
+ break;
562
+ }
563
+ }
564
+ }
565
+ }
566
+
43
567
  /**
44
568
  * Fenwick Tree (Binary Indexed Tree) for O(log n) prefix sum queries and updates.
45
569
  * Used for cumulative height calculations in variable-height virtualization.
@@ -365,13 +889,17 @@ class DOMPool {
365
889
  class Virtualizer {
366
890
  constructor(container, itemsLength, itemGetter, options) {
367
891
  this.measuredHeights = new Map();
892
+ this.measuredHeightTotal = 0;
368
893
  this.activeNodes = new Map(); // index -> node mapping
369
894
  this.destroyed = false;
370
895
  this.recycleRafId = 0;
896
+ this.intendedScrollTop = 0;
897
+ this.currentWindow = null;
371
898
  this.container = container;
372
899
  this.itemsLength = itemsLength;
373
900
  this.itemGetter = itemGetter;
374
901
  this.options = options;
902
+ this.estimatedItemHeight = options.estimatedItemHeight;
375
903
  this.averageHeight = options.estimatedItemHeight;
376
904
  // Initialize DOM pool with LRU eviction
377
905
  const maxPoolSize = Math.ceil((options.buffer * 2 + 10) * 1.5) + (options.maxPoolExtra ?? 32);
@@ -392,39 +920,121 @@ class Virtualizer {
392
920
  },
393
921
  telemetry: options.enableTelemetry || false,
394
922
  });
395
- // Use Fenwick tree for large lists (>5000 items)
396
- if (itemsLength > 5000) {
397
- this.fenwick = new FenwickTree(itemsLength);
398
- // Initialize with estimated heights
399
- for (let i = 0; i < itemsLength; i++) {
400
- this.fenwick.add(i, options.estimatedItemHeight);
401
- }
402
- }
923
+ // One prefix index keeps offset, window, and scroll calculations on the
924
+ // same measured-height policy at every list size.
925
+ this.fenwick = this.createFenwickTree(itemsLength);
403
926
  this.container.style.willChange = 'transform';
404
927
  }
405
928
  computeWindow(scrollTop, viewportHeight) {
406
929
  const { buffer } = this.options;
407
- const startIndex = Math.max(Math.floor(scrollTop / this.averageHeight) - buffer, 0);
408
- const endIndex = Math.min(Math.ceil((scrollTop + viewportHeight) / this.averageHeight) + buffer, this.itemsLength - 1);
930
+ const visibleStartIndex = this.indexAtOffset(scrollTop);
931
+ const calculatedStartIndex = visibleStartIndex - buffer;
932
+ const startIndex = this.itemsLength > 0
933
+ ? Math.max(0, Math.min(this.itemsLength - 1, calculatedStartIndex))
934
+ : 0;
935
+ const viewportEnd = Math.max(0, scrollTop + viewportHeight);
936
+ let visibleEndIndex = this.indexAtOffset(viewportEnd);
937
+ // The item beginning exactly at the viewport's lower edge is not visible.
938
+ // indexAtOffset deliberately advances across exact boundaries for the
939
+ // viewport start, so reverse that choice here when the viewport has height.
940
+ if (viewportHeight > 0
941
+ && visibleEndIndex > visibleStartIndex
942
+ && this.cumulativeOffset(visibleEndIndex) === viewportEnd) {
943
+ visibleEndIndex -= 1;
944
+ }
945
+ const calculatedEndIndex = Math.max(visibleStartIndex, visibleEndIndex) + buffer;
946
+ const endIndex = this.itemsLength > 0
947
+ ? Math.max(0, Math.min(this.itemsLength - 1, calculatedEndIndex))
948
+ : -1;
409
949
  const windowSize = Math.max(0, endIndex - startIndex + 1);
410
950
  // Adjust pool size dynamically based on window
411
951
  const newPoolSize = windowSize + (this.options.maxPoolExtra ?? 32);
412
952
  this.pool.setMaxSize(newPoolSize);
413
953
  return { startIndex, endIndex, windowSize };
414
954
  }
415
- cumulativeOffset(index) {
416
- if (index <= 0)
955
+ /** Computes and records a scroll-derived window without installing listeners. */
956
+ updateWindow(scrollTop, viewportHeight) {
957
+ if (this.destroyed)
958
+ return null;
959
+ const safeScrollTop = Number.isFinite(scrollTop) ? Math.max(0, scrollTop) : 0;
960
+ const safeViewportHeight = Number.isFinite(viewportHeight) && viewportHeight >= 0
961
+ ? viewportHeight
962
+ : 0;
963
+ const nextWindow = this.computeWindow(safeScrollTop, safeViewportHeight);
964
+ const changed = this.currentWindow === null
965
+ || this.currentWindow.startIndex !== nextWindow.startIndex
966
+ || this.currentWindow.endIndex !== nextWindow.endIndex
967
+ || this.currentWindow.windowSize !== nextWindow.windowSize;
968
+ this.currentWindow = { ...nextWindow };
969
+ return {
970
+ window: { ...nextWindow },
971
+ changed,
972
+ scrollTop: safeScrollTop,
973
+ viewportHeight: safeViewportHeight,
974
+ };
975
+ }
976
+ /** Returns a copy of the last recorded window, or null before the first update. */
977
+ getCurrentWindow() {
978
+ return this.currentWindow ? { ...this.currentWindow } : null;
979
+ }
980
+ /** Finds the item containing an offset, advancing past exact item boundaries. */
981
+ indexAtOffset(offset) {
982
+ if (this.itemsLength <= 0)
417
983
  return 0;
418
- // Use Fenwick tree for O(log n) prefix sum
419
- if (this.fenwick) {
420
- return this.fenwick.sum(index - 1);
984
+ const target = Math.max(0, offset);
985
+ let index = Math.max(0, Math.min(this.itemsLength - 1, this.fenwick.lowerBound(target)));
986
+ // FenwickTree.lowerBound returns the preceding item when the target lands
987
+ // exactly on an item boundary. For the viewport start, select the next item.
988
+ while (index < this.itemsLength - 1 && this.cumulativeOffset(index + 1) <= target) {
989
+ index += 1;
421
990
  }
422
- // Fallback: approximate using average height with sparse adjustments
423
- let total = 0;
424
- for (let i = 0; i < index; i++) {
425
- total += this.measuredHeights.get(i) ?? this.averageHeight;
991
+ return index;
992
+ }
993
+ cumulativeOffset(index) {
994
+ if (!Number.isFinite(index)) {
995
+ return index === Number.POSITIVE_INFINITY && this.itemsLength > 0
996
+ ? this.fenwick.sum(this.itemsLength - 1)
997
+ : 0;
426
998
  }
427
- return total;
999
+ const boundedIndex = Math.max(0, Math.min(this.itemsLength, Math.trunc(index)));
1000
+ if (boundedIndex === 0)
1001
+ return 0;
1002
+ return this.fenwick.sum(boundedIndex - 1);
1003
+ }
1004
+ /**
1005
+ * Calculates and records the intended scroll position for an item without
1006
+ * mutating the container. The caller may apply the returned scrollTop.
1007
+ * Returns null after destruction or when there are no items to target.
1008
+ */
1009
+ scrollToIndex(index) {
1010
+ if (this.destroyed || this.itemsLength <= 0)
1011
+ return null;
1012
+ const requestedIndex = Number.isFinite(index) ? Math.trunc(index) : 0;
1013
+ const targetIndex = Math.max(0, Math.min(this.itemsLength - 1, requestedIndex));
1014
+ const offset = this.cumulativeOffset(targetIndex);
1015
+ this.intendedScrollTop = offset;
1016
+ return { index: targetIndex, offset, scrollTop: offset };
1017
+ }
1018
+ /**
1019
+ * Resolves a stable key against the caller's current data identity, then
1020
+ * delegates to scrollToIndex(). Invalid or out-of-range resolutions are
1021
+ * rejected rather than clamped to a different item's position.
1022
+ */
1023
+ scrollToKey(key, resolveIndex) {
1024
+ if (this.destroyed || this.itemsLength <= 0)
1025
+ return null;
1026
+ const index = resolveIndex(key);
1027
+ if (typeof index !== 'number'
1028
+ || !Number.isInteger(index)
1029
+ || index < 0
1030
+ || index >= this.itemsLength) {
1031
+ return null;
1032
+ }
1033
+ return this.scrollToIndex(index);
1034
+ }
1035
+ /** Returns the last scroll position requested through scrollToIndex(). */
1036
+ getIntendedScrollTop() {
1037
+ return this.intendedScrollTop;
428
1038
  }
429
1039
  acquireNode(index) {
430
1040
  // Check if we already have this node active (reuse)
@@ -485,23 +1095,29 @@ class Virtualizer {
485
1095
  });
486
1096
  }
487
1097
  measureOnAppear(node, index) {
488
- if (this.destroyed || index >= this.itemsLength)
489
- return;
490
- const h = node.offsetHeight;
1098
+ this.measureItem(index, node.offsetHeight);
1099
+ }
1100
+ /** Records a validated measured height and updates the virtual offset index. */
1101
+ measureItem(index, height) {
1102
+ if (this.destroyed
1103
+ || !Number.isInteger(index)
1104
+ || index < 0
1105
+ || index >= this.itemsLength
1106
+ || !Number.isFinite(height)
1107
+ || height <= 0)
1108
+ return false;
491
1109
  const prev = this.measuredHeights.get(index);
492
1110
  const threshold = this.options.measurementThreshold ?? 5;
493
- if (prev === undefined || Math.abs(prev - h) > threshold) {
494
- const oldValue = prev ?? this.averageHeight;
495
- this.measuredHeights.set(index, h);
1111
+ if (prev === undefined || Math.abs(prev - height) > threshold) {
1112
+ const oldValue = prev ?? this.estimatedItemHeight;
1113
+ this.measuredHeights.set(index, height);
1114
+ this.measuredHeightTotal += height - (prev ?? 0);
496
1115
  // Update Fenwick tree with new measurement
497
- if (this.fenwick) {
498
- this.fenwick.update(index, oldValue, h);
499
- }
500
- // Update running average (weighted by measured count)
501
- const count = this.measuredHeights.size;
502
- const total = Array.from(this.measuredHeights.values()).reduce((a, b) => a + b, 0);
503
- this.averageHeight = Math.round((total / count) * 100) / 100;
1116
+ this.fenwick.update(index, oldValue, height);
1117
+ this.updateAverageHeight();
1118
+ return true;
504
1119
  }
1120
+ return false;
505
1121
  }
506
1122
  /**
507
1123
  * Get pool statistics (if telemetry enabled)
@@ -513,27 +1129,27 @@ class Virtualizer {
513
1129
  * Update items length and resize Fenwick tree if needed
514
1130
  */
515
1131
  setItemsLength(newLength) {
1132
+ const previousLength = this.itemsLength;
516
1133
  this.itemsLength = newLength;
517
- for (const index of Array.from(this.measuredHeights.keys())) {
1134
+ if (newLength !== previousLength)
1135
+ this.currentWindow = null;
1136
+ let removedMeasurement = false;
1137
+ for (const [index, height] of this.measuredHeights) {
518
1138
  if (index >= newLength) {
1139
+ this.measuredHeightTotal -= height;
519
1140
  this.measuredHeights.delete(index);
1141
+ removedMeasurement = true;
520
1142
  }
521
1143
  }
1144
+ if (removedMeasurement)
1145
+ this.updateAverageHeight();
522
1146
  for (const index of Array.from(this.activeNodes.keys())) {
523
1147
  if (index >= newLength) {
524
1148
  this.releaseNode(index);
525
1149
  }
526
1150
  }
527
- if (this.fenwick) {
528
- this.fenwick.resize(newLength);
529
- }
530
- else if (newLength > 5000 && !this.fenwick) {
531
- // Activate Fenwick tree when crossing threshold
532
- this.fenwick = new FenwickTree(newLength);
533
- // Populate with existing measurements
534
- for (const [index, height] of this.measuredHeights) {
535
- this.fenwick.update(index, this.averageHeight, height);
536
- }
1151
+ if (newLength !== previousLength) {
1152
+ this.fenwick = this.createFenwickTree(newLength);
537
1153
  }
538
1154
  }
539
1155
  /**
@@ -548,9 +1164,28 @@ class Virtualizer {
548
1164
  this.pool.clear();
549
1165
  this.activeNodes.clear();
550
1166
  this.measuredHeights.clear();
551
- if (this.fenwick) {
552
- this.fenwick.reset();
1167
+ this.measuredHeightTotal = 0;
1168
+ this.averageHeight = this.estimatedItemHeight;
1169
+ this.currentWindow = null;
1170
+ this.fenwick.reset();
1171
+ }
1172
+ updateAverageHeight() {
1173
+ const count = this.measuredHeights.size;
1174
+ this.averageHeight = count > 0
1175
+ ? Math.round((this.measuredHeightTotal / count) * 100) / 100
1176
+ : this.estimatedItemHeight;
1177
+ }
1178
+ createFenwickTree(size) {
1179
+ const tree = new FenwickTree(size);
1180
+ for (let index = 0; index < size; index++) {
1181
+ tree.add(index, this.estimatedItemHeight);
1182
+ }
1183
+ for (const [index, height] of this.measuredHeights) {
1184
+ if (index < size) {
1185
+ tree.update(index, this.estimatedItemHeight, height);
1186
+ }
553
1187
  }
1188
+ return tree;
554
1189
  }
555
1190
  }
556
1191
 
@@ -1612,6 +2247,222 @@ function resetSelectConfig() {
1612
2247
  selectConfig.resetConfig();
1613
2248
  }
1614
2249
 
2250
+ /** Returns whether a selected key remains in the filtered result set. */
2251
+ /**
2252
+ * Returns keys in the half-open index range [startIndex, endIndex), clamped to
2253
+ * the source. Bounds are truncated to integers; an end before start is empty.
2254
+ */
2255
+ function computeWindowKeys(filteredKeys, startIndex, endIndex) {
2256
+ const start = Math.max(0, Math.min(filteredKeys.length, Math.trunc(startIndex)));
2257
+ const end = Math.max(start, Math.min(filteredKeys.length, Math.trunc(endIndex)));
2258
+ return filteredKeys.slice(start, end);
2259
+ }
2260
+
2261
+ /** Projects existing engine state into accessibility semantics without DOM data. */
2262
+ function deriveAccessibilityState(state, context = {}) {
2263
+ const required = state.selection.required;
2264
+ const invalid = context.invalid ?? false;
2265
+ return {
2266
+ expanded: state.popup === 'open',
2267
+ disabled: state.disabled,
2268
+ readonly: context.readonly ?? false,
2269
+ searchable: context.searchable ?? false,
2270
+ multiple: state.selection.multiple,
2271
+ required,
2272
+ invalid,
2273
+ busy: state.dataStatus === 'loading',
2274
+ activeKey: state.activeKey,
2275
+ selectedKeys: state.selectedKeys,
2276
+ disabledKeys: state.selection.disabledKeys,
2277
+ popupRole: 'listbox',
2278
+ label: context.label ?? {},
2279
+ validation: {
2280
+ required,
2281
+ invalid,
2282
+ errorMessage: context.errorMessage ?? null,
2283
+ errorDescriptionId: context.errorDescriptionId ?? null,
2284
+ },
2285
+ };
2286
+ }
2287
+ function uniqueIds(ids) {
2288
+ return [...new Set(ids.filter((id) => Boolean(id)))];
2289
+ }
2290
+ function getLabelledBy(label) {
2291
+ return uniqueIds([label.labelId, ...(label.labelledBy ?? [])]);
2292
+ }
2293
+ function getDescribedBy(state) {
2294
+ return uniqueIds([
2295
+ ...(state.label.describedBy ?? []),
2296
+ state.validation.errorDescriptionId,
2297
+ ]);
2298
+ }
2299
+ /** Computes combobox semantics without reading from or writing to the DOM. */
2300
+ function computeComboboxAccessibility(state, controlsId = null) {
2301
+ return {
2302
+ role: 'combobox',
2303
+ expanded: state.expanded,
2304
+ disabled: state.disabled,
2305
+ readonly: state.readonly,
2306
+ autocomplete: state.searchable ? 'list' : 'none',
2307
+ multiple: state.multiple,
2308
+ required: state.required,
2309
+ invalid: state.invalid,
2310
+ activeKey: state.activeKey,
2311
+ controlsId,
2312
+ labelledBy: getLabelledBy(state.label),
2313
+ describedBy: getDescribedBy(state),
2314
+ ariaLabel: state.label.ariaLabel ?? null,
2315
+ ariaDescription: state.label.ariaDescription ?? null,
2316
+ };
2317
+ }
2318
+ /** Computes listbox semantics; the supplied label IDs remain caller-owned data. */
2319
+ function computeListboxAccessibility(state) {
2320
+ return {
2321
+ role: state.popupRole,
2322
+ multiple: state.multiple,
2323
+ busy: state.busy,
2324
+ labelledBy: getLabelledBy(state.label),
2325
+ ariaLabel: state.label.ariaLabel ?? null,
2326
+ };
2327
+ }
2328
+ /** Computes one option's semantic state from stable identity, never its index. */
2329
+ function computeOptionAccessibility(state, key) {
2330
+ const disabled = state.disabled || state.disabledKeys.has(key);
2331
+ return {
2332
+ key,
2333
+ selected: state.selectedKeys.has(key),
2334
+ disabled,
2335
+ active: !disabled && state.activeKey === key,
2336
+ };
2337
+ }
2338
+ /**
2339
+ * Produces semantic accessibility effects. IDs and rendered option keys are
2340
+ * caller inputs; this function does not inspect the DOM or perform side effects.
2341
+ */
2342
+ function computeAccessibilityEffects(state, options) {
2343
+ return [
2344
+ {
2345
+ type: 'SYNC_COMBOBOX_ARIA',
2346
+ ...computeComboboxAccessibility(state, options.controlsId ?? null),
2347
+ },
2348
+ {
2349
+ type: 'SYNC_LISTBOX_ARIA',
2350
+ ...computeListboxAccessibility(state),
2351
+ },
2352
+ ...options.optionKeys.map((key) => ({
2353
+ type: 'SYNC_OPTION_ARIA',
2354
+ ...computeOptionAccessibility(state, key),
2355
+ })),
2356
+ ...(options.announcements ?? []).map((announcement) => ({
2357
+ type: 'ANNOUNCE',
2358
+ ...announcement,
2359
+ })),
2360
+ ...(options.focusIntents ?? []).map((focusIntent) => ({
2361
+ type: 'FOCUS_INTENT',
2362
+ ...focusIntent,
2363
+ })),
2364
+ ];
2365
+ }
2366
+
2367
+ function setBooleanAttribute(element, name, value) {
2368
+ element.setAttribute(name, String(value));
2369
+ }
2370
+ function setOptionalAttribute(element, name, value) {
2371
+ if (value) {
2372
+ element.setAttribute(name, value);
2373
+ }
2374
+ else {
2375
+ element.removeAttribute(name);
2376
+ }
2377
+ }
2378
+ function setIdListAttribute(element, name, ids) {
2379
+ setOptionalAttribute(element, name, ids.length > 0 ? ids.join(' ') : null);
2380
+ }
2381
+ function applyCombobox(effect, targets) {
2382
+ const combobox = targets.combobox;
2383
+ if (!combobox)
2384
+ return;
2385
+ combobox.setAttribute('role', effect.role);
2386
+ setBooleanAttribute(combobox, 'aria-expanded', effect.expanded);
2387
+ setBooleanAttribute(combobox, 'aria-disabled', effect.disabled);
2388
+ setBooleanAttribute(combobox, 'aria-readonly', effect.readonly);
2389
+ setBooleanAttribute(combobox, 'aria-required', effect.required);
2390
+ setBooleanAttribute(combobox, 'aria-invalid', effect.invalid);
2391
+ combobox.setAttribute('aria-autocomplete', effect.autocomplete);
2392
+ setOptionalAttribute(combobox, 'aria-controls', effect.controlsId);
2393
+ setIdListAttribute(combobox, 'aria-labelledby', effect.labelledBy);
2394
+ setIdListAttribute(combobox, 'aria-describedby', effect.describedBy);
2395
+ setOptionalAttribute(combobox, 'aria-label', effect.ariaLabel);
2396
+ setOptionalAttribute(combobox, 'aria-description', effect.ariaDescription);
2397
+ const activeOption = effect.activeKey == null
2398
+ ? null
2399
+ : targets.getOptionByKey?.(effect.activeKey) ?? null;
2400
+ setOptionalAttribute(combobox, 'aria-activedescendant', activeOption?.id || null);
2401
+ }
2402
+ function applyListbox(effect, targets) {
2403
+ const listbox = targets.listbox;
2404
+ if (!listbox)
2405
+ return;
2406
+ listbox.setAttribute('role', effect.role);
2407
+ if (effect.multiple)
2408
+ listbox.setAttribute('aria-multiselectable', 'true');
2409
+ else
2410
+ listbox.removeAttribute('aria-multiselectable');
2411
+ if (effect.busy)
2412
+ listbox.setAttribute('aria-busy', 'true');
2413
+ else
2414
+ listbox.removeAttribute('aria-busy');
2415
+ setIdListAttribute(listbox, 'aria-labelledby', effect.labelledBy);
2416
+ setOptionalAttribute(listbox, 'aria-label', effect.ariaLabel);
2417
+ }
2418
+ function applyOption(effect, targets) {
2419
+ const option = targets.getOptionByKey?.(effect.key);
2420
+ if (!option)
2421
+ return;
2422
+ option.setAttribute('role', 'option');
2423
+ setBooleanAttribute(option, 'aria-selected', effect.selected);
2424
+ if (effect.disabled)
2425
+ option.setAttribute('aria-disabled', 'true');
2426
+ else
2427
+ option.removeAttribute('aria-disabled');
2428
+ }
2429
+ function applyFocusIntent(target, targets, options) {
2430
+ if (!options.applyFocus || target === 'none')
2431
+ return;
2432
+ const focusTarget = target === 'input'
2433
+ ? targets.focusTargets?.input
2434
+ : target === 'clear-button'
2435
+ ? targets.focusTargets?.clearButton
2436
+ : targets.focusTargets?.getActiveOption?.();
2437
+ focusTarget?.focus();
2438
+ }
2439
+ /** Applies engine accessibility effects to caller-owned web DOM targets. */
2440
+ function applyAccessibilityEffects(effects, targets, options = {}) {
2441
+ for (const effect of effects) {
2442
+ switch (effect.type) {
2443
+ case 'SYNC_COMBOBOX_ARIA':
2444
+ applyCombobox(effect, targets);
2445
+ break;
2446
+ case 'SYNC_LISTBOX_ARIA':
2447
+ applyListbox(effect, targets);
2448
+ break;
2449
+ case 'SYNC_OPTION_ARIA':
2450
+ applyOption(effect, targets);
2451
+ break;
2452
+ case 'ANNOUNCE':
2453
+ if (targets.liveRegion) {
2454
+ targets.liveRegion.setAttribute('aria-live', effect.politeness);
2455
+ targets.liveRegion.setAttribute('aria-atomic', 'true');
2456
+ targets.liveRegion.textContent = effect.message;
2457
+ }
2458
+ break;
2459
+ case 'FOCUS_INTENT':
2460
+ applyFocusIntent(effect.target, targets, options);
2461
+ break;
2462
+ }
2463
+ }
2464
+ }
2465
+
1615
2466
  /**
1616
2467
  * Independent Option Component
1617
2468
  * High cohesion, low coupling - handles its own selection state and events
@@ -2202,15 +3053,19 @@ function arraysEqualByValue(a, b) {
2202
3053
  * Implements all advanced features: infinite scroll, load more, busy state,
2203
3054
  * server-side selection, and full customization
2204
3055
  *
2205
- * ✨ Redesigned with formal elegance, refined microinteractions, and polished UX
3056
+ * Redesigned with formal elegance, refined microinteractions, and polished UX
2206
3057
  */
2207
3058
  class EnhancedSelect extends HTMLElement {
3059
+ static get observedAttributes() {
3060
+ return ['aria-label', 'aria-description'];
3061
+ }
2208
3062
  get classMap() {
2209
3063
  return this._classMap;
2210
3064
  }
2211
3065
  set classMap(map) {
2212
3066
  if (this._areClassMapsEqual(this._classMap, map))
2213
3067
  return;
3068
+ this._invalidateGuardedMeasurements();
2214
3069
  this._classMap = map;
2215
3070
  this._setGlobalStylesMirroring(Boolean(this._optionRenderer || map || this._groupHeaderRenderer));
2216
3071
  this._track('style', 'classMapChanged', {
@@ -2241,6 +3096,48 @@ class EnhancedSelect extends HTMLElement {
2241
3096
  }
2242
3097
  constructor() {
2243
3098
  super();
3099
+ this._engine = new SelectEngineBridge();
3100
+ this._virtualizationScope = {
3101
+ dataKeys: [],
3102
+ filteredKeys: [],
3103
+ registeredKeys: [],
3104
+ windowKeys: [],
3105
+ mountedKeys: [],
3106
+ selectedKeys: new Set(),
3107
+ activeKey: null,
3108
+ };
3109
+ this._renderPlan = {
3110
+ mode: 'legacy-full',
3111
+ filteredIndices: [],
3112
+ filteredKeys: [],
3113
+ intendedRenderKeys: [],
3114
+ filteredIndexByKey: new Map(),
3115
+ };
3116
+ // Null keeps the public/default renderer on its legacy full path. This
3117
+ // private state is only used by guarded virtualization integration.
3118
+ this._guardedVirtualWindow = null;
3119
+ this._guardedVirtualizer = null;
3120
+ this._guardedVirtualizationRequested = false;
3121
+ this._guardedVirtualizerKeys = [];
3122
+ this._guardedMeasurementQuery = null;
3123
+ this._guardedOptionResizeObserver = null;
3124
+ this._guardedObservedOptions = new Set();
3125
+ this._guardedObserverSeenOptions = new WeakSet();
3126
+ this._guardedOptionMeasurements = new WeakMap();
3127
+ this._guardedMeasurementGeneration = 0;
3128
+ this._guardedVirtualScrollTop = 0;
3129
+ this._guardedVirtualViewportHeight = 0;
3130
+ this._guardedVirtualOverscan = 0;
3131
+ this._guardedVirtualWindowRafId = null;
3132
+ this._guardedScrollListenerAttached = false;
3133
+ this._onGuardedVirtualScroll = () => this._scheduleGuardedVirtualWindowUpdate();
3134
+ this._effectRunner = new DefaultSelectEffectRunner();
3135
+ this._itemAdapter = this._createEngineItemAdapter();
3136
+ this._itemRegistry = createItemRegistry([], this._itemAdapter);
3137
+ // Engine selectedKeys owns identity. The registry resolves current records;
3138
+ // this cache keeps the last known record available while a selected key is detached.
3139
+ this._selectedRecordsByKey = new Map();
3140
+ this._registryItemsRef = [];
2244
3141
  this._pageCache = {};
2245
3142
  this._typeBuffer = '';
2246
3143
  this._hasError = false;
@@ -2250,6 +3147,8 @@ class EnhancedSelect extends HTMLElement {
2250
3147
  this._pendingSearchRenderMark = false;
2251
3148
  this._rangeAnchorIndex = null;
2252
3149
  this._customOptionBoundElements = new WeakSet();
3150
+ this._customOptionNormalizedIds = new WeakMap();
3151
+ this._customOptionNormalizedLabels = new WeakMap();
2253
3152
  this._mirrorGlobalStylesForCustomOptions = false;
2254
3153
  this._globalStylesObserver = null;
2255
3154
  this._globalStylesContainer = null;
@@ -2258,6 +3157,7 @@ class EnhancedSelect extends HTMLElement {
2258
3157
  this._asyncGeneration = 0;
2259
3158
  this._lifecycleTimers = new Set();
2260
3159
  this._lifecycleRafs = new Set();
3160
+ this._keyboardActiveChangeGeneration = 0;
2261
3161
  this._tracking = { events: [], styles: [], limitations: [] };
2262
3162
  this._suppressBlurClose = false;
2263
3163
  this._renderCycleId = 0;
@@ -2303,7 +3203,7 @@ class EnhancedSelect extends HTMLElement {
2303
3203
  }
2304
3204
  }
2305
3205
  if (!clickedInside) {
2306
- this._handleClose();
3206
+ this._handleClose('outside-pointer');
2307
3207
  }
2308
3208
  };
2309
3209
  this._shadow = this.attachShadow({ mode: 'open' });
@@ -2311,9 +3211,14 @@ class EnhancedSelect extends HTMLElement {
2311
3211
  this._rendererHelpers = this._buildRendererHelpers();
2312
3212
  // Merge global config with component-level config
2313
3213
  this._config = selectConfig.getConfig();
3214
+ this._engine.dispatch({ type: 'DISABLED_CHANGED', disabled: !this._config.enabled });
3215
+ this._syncEngineSelectionConfig();
2314
3216
  // Initialize state
3217
+ const host = this;
2315
3218
  this._state = {
2316
- isOpen: false,
3219
+ get isOpen() {
3220
+ return host._engine.state.popup === 'open';
3221
+ },
2317
3222
  isBusy: false,
2318
3223
  isSearching: false,
2319
3224
  currentPage: this._config.infiniteScroll.initialPage || 1,
@@ -2340,6 +3245,7 @@ class EnhancedSelect extends HTMLElement {
2340
3245
  this._dropdown = this._createDropdown();
2341
3246
  this._optionsContainer = this._createOptionsContainer();
2342
3247
  this._liveRegion = this._createLiveRegion();
3248
+ this._errorDescription = this._createErrorDescription();
2343
3249
  // Initialize styles BEFORE assembling DOM (order matters in shadow DOM)
2344
3250
  this._initializeStyles();
2345
3251
  this._syncStyleConfigVariables();
@@ -2348,10 +3254,14 @@ class EnhancedSelect extends HTMLElement {
2348
3254
  this._assembleDOM();
2349
3255
  this._attachEventListeners();
2350
3256
  this._initializeObservers();
3257
+ this._syncComboboxAccessibility();
3258
+ this._syncListboxAccessibility();
2351
3259
  }
2352
3260
  connectedCallback() {
2353
3261
  // register instance
2354
3262
  EnhancedSelect._instances.add(this);
3263
+ this._runEngineEffects(this._engine.dispatch({ type: 'CONNECT' }));
3264
+ this._runEngineEffects(this._engine.dispatch({ type: 'DISABLED_CHANGED', disabled: !this._config.enabled }));
2355
3265
  this._connectionController?.abort();
2356
3266
  this._connectionController = new AbortController();
2357
3267
  document.addEventListener('pointerdown', this._onDocumentPointerDown, {
@@ -2363,6 +3273,7 @@ class EnhancedSelect extends HTMLElement {
2363
3273
  this.style.display = 'block';
2364
3274
  // Sync direction attribute (must be in connectedCallback, not constructor)
2365
3275
  this._syncDirectionConfig();
3276
+ this._syncComboboxAccessibility();
2366
3277
  if (this._optionRenderer || this._classMap || this._groupHeaderRenderer) {
2367
3278
  this._setGlobalStylesMirroring(true);
2368
3279
  }
@@ -2381,13 +3292,33 @@ class EnhancedSelect extends HTMLElement {
2381
3292
  this._config.callbacks.onOpen();
2382
3293
  }
2383
3294
  }
3295
+ attributeChangedCallback(name, oldValue, newValue) {
3296
+ if (oldValue === newValue || (name !== 'aria-label' && name !== 'aria-description'))
3297
+ return;
3298
+ this._syncComboboxAccessibility();
3299
+ if (name === 'aria-label')
3300
+ this._syncListboxAccessibility();
3301
+ }
2384
3302
  disconnectedCallback() {
2385
3303
  // unregister instance
2386
3304
  EnhancedSelect._instances.delete(this);
3305
+ if (this._state.isOpen) {
3306
+ this._handleClose('disconnect');
3307
+ }
3308
+ this._runEngineEffects(this._engine.dispatch({ type: 'DISCONNECT' }));
2387
3309
  this._connectionController?.abort();
2388
3310
  this._connectionController = undefined;
2389
3311
  this._asyncGeneration += 1;
3312
+ this._cancelGuardedVirtualWindowUpdate();
2390
3313
  this._clearLifecycleTasks();
3314
+ this._destroyGuardedVirtualizer(true);
3315
+ this._virtualizationScope = {
3316
+ ...this._virtualizationScope,
3317
+ mountedKeys: [],
3318
+ };
3319
+ Array.from(this._optionsContainer.children)
3320
+ .filter((element) => element.hasAttribute('data-index') || element.hasAttribute('data-virtual-spacer'))
3321
+ .forEach((element) => element.remove());
2391
3322
  // Cleanup observers
2392
3323
  this._resizeObserver?.disconnect();
2393
3324
  this._intersectionObserver?.disconnect();
@@ -2764,8 +3695,16 @@ class EnhancedSelect extends HTMLElement {
2764
3695
  return scopedSelector;
2765
3696
  }
2766
3697
  _normalizeCustomOptionAccessibility(optionEl, meta) {
2767
- if (!optionEl.hasAttribute('aria-label') && !optionEl.hasAttribute('aria-labelledby')) {
3698
+ const previousNormalizedLabel = this._customOptionNormalizedLabels.get(optionEl);
3699
+ const currentAriaLabel = optionEl.getAttribute('aria-label');
3700
+ const canRefreshNormalizedLabel = previousNormalizedLabel !== undefined
3701
+ && currentAriaLabel === previousNormalizedLabel;
3702
+ if (!optionEl.hasAttribute('aria-labelledby') && (!currentAriaLabel || canRefreshNormalizedLabel)) {
2768
3703
  optionEl.setAttribute('aria-label', meta.label);
3704
+ this._customOptionNormalizedLabels.set(optionEl, meta.label);
3705
+ }
3706
+ else {
3707
+ this._customOptionNormalizedLabels.delete(optionEl);
2769
3708
  }
2770
3709
  const nestedFocusableSelectors = [
2771
3710
  'a[href]',
@@ -2867,6 +3806,237 @@ class EnhancedSelect extends HTMLElement {
2867
3806
  _isOptionSelectionBlocked(item) {
2868
3807
  return Boolean(item?.disabled) && !this._isDisabledOptionSelectable(item);
2869
3808
  }
3809
+ _isPhase2DevRuntime() {
3810
+ const env = globalThis.process?.env?.NODE_ENV;
3811
+ return env !== 'production';
3812
+ }
3813
+ _getDuplicateKeyPolicy() {
3814
+ return this._isPhase2DevRuntime() ? 'throw' : 'warn';
3815
+ }
3816
+ _warnPhase2(message) {
3817
+ if (this._isPhase2DevRuntime() && typeof console !== 'undefined') {
3818
+ console.warn(message);
3819
+ }
3820
+ }
3821
+ _getItemValue(item) {
3822
+ return this._config.serverSide.getValueFromItem?.(item) ?? item?.value ?? item;
3823
+ }
3824
+ _getItemLabel(item) {
3825
+ return this._config.serverSide.getLabelFromItem?.(item) ?? item?.label ?? String(item);
3826
+ }
3827
+ _createEngineItemAdapter() {
3828
+ return createDefaultItemAdapter({
3829
+ getValue: (item) => this._getItemValue(item),
3830
+ getLabel: (item) => this._getItemLabel(item),
3831
+ isDisabled: (item) => Boolean(item?.disabled),
3832
+ getGroupKey: (item) => {
3833
+ const group = item?.group;
3834
+ return group == null ? null : String(group);
3835
+ },
3836
+ onIndexFallback: (message) => this._warnPhase2(message),
3837
+ });
3838
+ }
3839
+ _getBlockedDisabledKeys() {
3840
+ const keys = this._itemRegistry.records
3841
+ .filter((record) => record.disabled && this._isOptionSelectionBlocked(record.item))
3842
+ .map((record) => record.key);
3843
+ for (const entry of this._getSelectedEntries()) {
3844
+ if (this._isOptionSelectionBlocked(entry.item))
3845
+ keys.push(entry.key);
3846
+ }
3847
+ return keys;
3848
+ }
3849
+ _syncEngineSelectionConfig() {
3850
+ const required = Boolean(this._input?.hasAttribute('required'));
3851
+ const disabledKeys = this._getBlockedDisabledKeys();
3852
+ this._engine.dispatch({
3853
+ type: 'SELECTION_CONFIG_CHANGED',
3854
+ multiple: this._config.selection.mode === 'multi',
3855
+ required,
3856
+ allowDeselect: this._config.selection.allowDeselect === true,
3857
+ maxSelections: this._config.selection.maxSelections ?? 0,
3858
+ disabledKeys,
3859
+ });
3860
+ if (this._state) {
3861
+ this._syncLegacySelectionFromEngine();
3862
+ this._syncLegacyActiveFromEngine();
3863
+ this._assertSelectionProjection('selection config');
3864
+ this._assertActiveProjection('selection config');
3865
+ }
3866
+ }
3867
+ _rebuildItemRegistry(items = this._state.loadedItems) {
3868
+ // Build first so duplicate-key rejection leaves the previous runtime intact.
3869
+ const registry = createItemRegistry(items, this._itemAdapter, {
3870
+ duplicateKeyPolicy: this._getDuplicateKeyPolicy(),
3871
+ });
3872
+ const activeKey = this._engine.state.activeKey;
3873
+ const anchorKey = this._rangeAnchorIndex === null ? undefined : this._itemRegistry.indexToKey.get(this._rangeAnchorIndex);
3874
+ this._itemRegistry = registry;
3875
+ this._state.loadedItems = items;
3876
+ this._registryItemsRef = items;
3877
+ const disabledKeys = this._getBlockedDisabledKeys();
3878
+ this._rangeAnchorIndex = anchorKey === undefined ? null : registry.keyToIndex.get(anchorKey) ?? null;
3879
+ this._engine.dispatch({
3880
+ type: 'ITEMS_REGISTERED',
3881
+ keys: registry.records.map((record) => record.key),
3882
+ disabledKeys,
3883
+ });
3884
+ if (activeKey !== null && registry.keyToRecord.get(activeKey)?.disabled) {
3885
+ this._dispatchActiveKey(null, 'programmatic', 'items registered with disabled active key');
3886
+ }
3887
+ else {
3888
+ this._syncLegacyActiveFromEngine();
3889
+ }
3890
+ this._syncLegacySelectionFromEngine();
3891
+ this._syncEngineSelectionConfig();
3892
+ this._assertSelectionProjection('items registered');
3893
+ }
3894
+ _ensureRegistryCurrent() {
3895
+ if (this._registryItemsRef !== this._state.loadedItems
3896
+ || this._itemRegistry.records.length !== this._state.loadedItems.length
3897
+ || this._itemRegistry.records.some((record, index) => record.item !== this._state.loadedItems[index])) {
3898
+ this._rebuildItemRegistry();
3899
+ return;
3900
+ }
3901
+ this._syncLegacySelectionFromEngine();
3902
+ this._syncLegacyActiveFromEngine();
3903
+ this._assertSelectionProjection('registry read');
3904
+ this._assertActiveProjection('registry read');
3905
+ }
3906
+ _getRecordByIndex(index) {
3907
+ const key = this._itemRegistry.indexToKey.get(index);
3908
+ return key === undefined ? null : this._itemRegistry.keyToRecord.get(key) ?? null;
3909
+ }
3910
+ _getSelectedEntries() {
3911
+ const entries = [];
3912
+ if (!this._state)
3913
+ return entries;
3914
+ for (const key of this._engine.state.selectedKeys) {
3915
+ const record = this._itemRegistry.keyToRecord.get(key) ?? this._selectedRecordsByKey.get(key);
3916
+ if (record)
3917
+ entries.push({ key, index: record.index, item: record.item });
3918
+ }
3919
+ return entries;
3920
+ }
3921
+ _syncLegacySelectionFromEngine() {
3922
+ const selectedIndices = new Set();
3923
+ const selectedItems = new Map();
3924
+ const selectedKeys = this._engine.state.selectedKeys;
3925
+ for (const key of [...this._selectedRecordsByKey.keys()]) {
3926
+ if (!selectedKeys.has(key))
3927
+ this._selectedRecordsByKey.delete(key);
3928
+ }
3929
+ for (const key of selectedKeys) {
3930
+ const record = this._itemRegistry.keyToRecord.get(key);
3931
+ if (record)
3932
+ this._selectedRecordsByKey.set(key, record);
3933
+ if (!record)
3934
+ continue;
3935
+ selectedIndices.add(record.index);
3936
+ selectedItems.set(record.index, record.item);
3937
+ }
3938
+ this._state.selectedIndices = selectedIndices;
3939
+ this._state.selectedItems = selectedItems;
3940
+ }
3941
+ _projectedSelectedKeysSnapshot() {
3942
+ return new Set([...this._state.selectedIndices]
3943
+ .map((index) => this._itemRegistry.indexToKey.get(index))
3944
+ .filter((key) => key !== undefined));
3945
+ }
3946
+ _assertSelectionProjection(context) {
3947
+ if (!this._isPhase2DevRuntime())
3948
+ return;
3949
+ const legacyKeys = this._projectedSelectedKeysSnapshot();
3950
+ const engineKeys = this._engine.state.selectedKeys;
3951
+ if (this._state.selectedItems.size !== this._state.selectedIndices.size
3952
+ || [...this._state.selectedIndices].some((index) => !this._state.selectedItems.has(index))
3953
+ || [...engineKeys].some((key) => this._itemRegistry.keyToRecord.has(key) && !legacyKeys.has(key))
3954
+ || [...legacyKeys].some((key) => !engineKeys.has(key))) {
3955
+ throw new Error(`[Smilodon Phase2] Selection projection failed in ${context}: compatibility=${JSON.stringify([...legacyKeys])}, engine=${JSON.stringify([...engineKeys])}`);
3956
+ }
3957
+ }
3958
+ _projectedActiveKeySnapshot() {
3959
+ return this._state.activeIndex < 0
3960
+ ? null
3961
+ : this._itemRegistry.indexToKey.get(this._state.activeIndex) ?? null;
3962
+ }
3963
+ _syncLegacyActiveFromEngine() {
3964
+ const activeKey = this._engine.state.activeKey;
3965
+ this._state.activeIndex = activeKey === null
3966
+ ? -1
3967
+ : this._itemRegistry.keyToIndex.get(activeKey) ?? -1;
3968
+ this._syncLegacyActiveAria();
3969
+ }
3970
+ _assertActiveProjection(context) {
3971
+ if (!this._isPhase2DevRuntime())
3972
+ return;
3973
+ const legacyKey = this._projectedActiveKeySnapshot();
3974
+ const engineKey = this._engine.state.activeKey;
3975
+ if (legacyKey !== engineKey && !Object.is(legacyKey, engineKey)) {
3976
+ throw new Error(`[Smilodon Phase2] Active projection failed in ${context}: compatibility=${String(legacyKey)}, engine=${String(engineKey)}`);
3977
+ }
3978
+ }
3979
+ _dispatchActiveKey(key, reason, context) {
3980
+ const effects = this._engine.dispatch({ type: 'ACTIVE_KEY_CHANGED', key, reason });
3981
+ this._runEngineEffects(effects);
3982
+ this._syncLegacyActiveFromEngine();
3983
+ this._assertActiveProjection(context);
3984
+ }
3985
+ _clearDisabledEngineActive(context) {
3986
+ const activeKey = this._engine.state.activeKey;
3987
+ if (activeKey !== null && this._itemRegistry.keyToRecord.get(activeKey)?.disabled) {
3988
+ this._dispatchActiveKey(null, 'programmatic', context);
3989
+ }
3990
+ else {
3991
+ this._syncLegacyActiveFromEngine();
3992
+ this._assertActiveProjection(context);
3993
+ }
3994
+ }
3995
+ /**
3996
+ * @deprecated Test/backward-compatibility shim. Production active-state authority is engine.activeKey.
3997
+ * Kept for existing renderer tests; component mutation paths dispatch by key.
3998
+ */
3999
+ _mirrorLegacyActive(reason, context) {
4000
+ this._dispatchActiveKey(this._projectedActiveKeySnapshot(), reason, context);
4001
+ }
4002
+ _dispatchSelection(event, context) {
4003
+ this._engine.dispatch(event);
4004
+ this._syncLegacySelectionFromEngine();
4005
+ this._assertSelectionProjection(context);
4006
+ }
4007
+ /**
4008
+ * @deprecated Test/backward-compatibility shim. Production selection authority is engine.selectedKeys.
4009
+ * Kept for existing styling tests; dispatches to engine authority.
4010
+ */
4011
+ _mirrorLegacySelection(event, context) {
4012
+ this._dispatchSelection(event, context);
4013
+ }
4014
+ _requestSelectionReplacement(entries, reason, context) {
4015
+ for (const entry of entries) {
4016
+ const record = this._itemRegistry.keyToRecord.get(entry.key) ?? this._selectedRecordsByKey.get(entry.key);
4017
+ this._selectedRecordsByKey.set(entry.key, record ?? {
4018
+ key: entry.key,
4019
+ item: entry.item,
4020
+ index: entry.index,
4021
+ label: this._getItemLabel(entry.item),
4022
+ value: this._getItemValue(entry.item),
4023
+ disabled: Boolean(entry.item?.disabled),
4024
+ groupKey: entry.item?.group == null
4025
+ ? null
4026
+ : String(entry.item.group),
4027
+ });
4028
+ }
4029
+ this._dispatchSelection({ type: 'REPLACE_SELECTION_REQUEST', keys: entries.map(({ key }) => key), reason }, context);
4030
+ }
4031
+ _registerShadowItems(indices) {
4032
+ const keys = indices.map((index) => this._itemRegistry.indexToKey.get(index)).filter((key) => key !== undefined);
4033
+ this._engine.dispatch({ type: 'ITEMS_REGISTERED', keys, disabledKeys: this._getBlockedDisabledKeys() });
4034
+ this._clearDisabledEngineActive('visible items');
4035
+ this._assertSelectionProjection('visible items');
4036
+ }
4037
+ _syncLegacyActiveAria() {
4038
+ this._syncComboboxAccessibility();
4039
+ }
2870
4040
  _syncStyleConfigVariables() {
2871
4041
  const styles = this._config.styles;
2872
4042
  if (!styles)
@@ -3285,10 +4455,7 @@ class EnhancedSelect extends HTMLElement {
3285
4455
  delete inputStyles.maxHeight;
3286
4456
  Object.assign(input.style, inputStyles);
3287
4457
  }
3288
- input.setAttribute('role', 'combobox');
3289
- input.setAttribute('aria-expanded', 'false');
3290
4458
  input.setAttribute('aria-haspopup', 'listbox');
3291
- input.setAttribute('aria-autocomplete', this._config.searchable ? 'list' : 'none');
3292
4459
  return input;
3293
4460
  }
3294
4461
  _createDropdown() {
@@ -3302,11 +4469,6 @@ class EnhancedSelect extends HTMLElement {
3302
4469
  if (this._config.styles.dropdown) {
3303
4470
  Object.assign(dropdown.style, this._config.styles.dropdown);
3304
4471
  }
3305
- dropdown.setAttribute('role', 'listbox');
3306
- dropdown.setAttribute('aria-labelledby', `${this._uniqueId}-input`);
3307
- if (this._config.selection.mode === 'multi') {
3308
- dropdown.setAttribute('aria-multiselectable', 'true');
3309
- }
3310
4472
  return dropdown;
3311
4473
  }
3312
4474
  _createOptionsContainer() {
@@ -3322,6 +4484,12 @@ class EnhancedSelect extends HTMLElement {
3322
4484
  liveRegion.style.cssText = 'position:absolute;left:-9999px;width:1px;height:1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border-width:0;';
3323
4485
  return liveRegion;
3324
4486
  }
4487
+ _createErrorDescription() {
4488
+ const description = document.createElement('div');
4489
+ description.id = `${this._uniqueId}-error`;
4490
+ description.style.cssText = 'position:absolute;left:-9999px;width:1px;height:1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border-width:0;';
4491
+ return description;
4492
+ }
3325
4493
  _createArrowContainer() {
3326
4494
  const container = document.createElement('div');
3327
4495
  container.className = 'dropdown-arrow-container';
@@ -3368,10 +4536,12 @@ class EnhancedSelect extends HTMLElement {
3368
4536
  if (this._liveRegion) {
3369
4537
  this._shadow.appendChild(this._liveRegion);
3370
4538
  }
4539
+ if (this._errorDescription) {
4540
+ this._shadow.appendChild(this._errorDescription);
4541
+ }
3371
4542
  // Set ARIA relationships
3372
4543
  const listboxId = `${this._uniqueId}-listbox`;
3373
4544
  this._dropdown.id = listboxId;
3374
- this._input.setAttribute('aria-controls', listboxId);
3375
4545
  this._input.setAttribute('aria-owns', listboxId);
3376
4546
  this._syncInputContainerMode();
3377
4547
  this._syncClearControlState();
@@ -4221,7 +5391,7 @@ class EnhancedSelect extends HTMLElement {
4221
5391
  margin: var(--select-group-header-margin, 0 calc(var(--select-options-padding, 6px) * -1));
4222
5392
  font-weight: var(--select-group-header-weight, 600);
4223
5393
  color: var(--select-group-header-color, var(--select-text-muted));
4224
- background: var(--select-group-header-bg, #ffffff);
5394
+ background: var(--select-group-header-bg, #f3f4f6);
4225
5395
  text-align: var(--select-group-header-text-align, left);
4226
5396
  font-size: var(--select-group-header-font-size, 0.7333em);
4227
5397
  text-transform: var(--select-group-header-text-transform, uppercase);
@@ -4728,6 +5898,25 @@ class EnhancedSelect extends HTMLElement {
4728
5898
  box-shadow: var(--select-group-header-shadow, 0 1px 2px rgba(0, 0, 0, 0.3));
4729
5899
  }
4730
5900
 
5901
+ :host(.dark-mode) .group-header,
5902
+ :host([dark-mode]) .group-header,
5903
+ :host([darkmode]) .group-header,
5904
+ :host([data-theme="dark"]) .group-header,
5905
+ :host([theme="dark"]) .group-header {
5906
+ color: var(--select-dark-group-header-color, var(--select-group-header-dark-color, #9ca3af));
5907
+ background: var(--select-dark-group-header-bg, var(--select-group-header-dark-bg, #1a1a2e));
5908
+ border-bottom: var(--select-group-header-border-bottom, 1px solid rgba(255, 255, 255, 0.08));
5909
+ box-shadow: var(--select-group-header-shadow, 0 1px 2px rgba(0, 0, 0, 0.3));
5910
+ }
5911
+
5912
+ :host(.dark-mode) .group-header:not(:first-child),
5913
+ :host([dark-mode]) .group-header:not(:first-child),
5914
+ :host([darkmode]) .group-header:not(:first-child),
5915
+ :host([data-theme="dark"]) .group-header:not(:first-child),
5916
+ :host([theme="dark"]) .group-header:not(:first-child) {
5917
+ border-top-color: var(--select-border);
5918
+ }
5919
+
4731
5920
  :host(.dark-mode) .option.selected::before,
4732
5921
  :host([dark-mode]) .option.selected::before,
4733
5922
  :host([darkmode]) .option.selected::before,
@@ -4825,7 +6014,7 @@ class EnhancedSelect extends HTMLElement {
4825
6014
  this._handleOpen();
4826
6015
  }
4827
6016
  // Focus the input (do not prevent default behavior for input itself)
4828
- this._input.focus();
6017
+ this._applyFocusIntent('input', 'input-container-trigger');
4829
6018
  // If we just opened the dropdown, transfer pointer capture to the
4830
6019
  // options container so the subsequent pointerup lands there instead of
4831
6020
  // staying with the input container (which would swallow the event).
@@ -4862,7 +6051,7 @@ class EnhancedSelect extends HTMLElement {
4862
6051
  if (!this._state.isOpen) {
4863
6052
  this._handleOpen();
4864
6053
  }
4865
- this._input.focus();
6054
+ this._applyFocusIntent('input', 'input-container-activation');
4866
6055
  });
4867
6056
  this._inputContent.addEventListener('pointermove', (e) => {
4868
6057
  this._updateMultiScrollDrag(e);
@@ -4888,7 +6077,10 @@ class EnhancedSelect extends HTMLElement {
4888
6077
  e.stopPropagation();
4889
6078
  });
4890
6079
  // Input focus/blur
4891
- this._input.addEventListener('focus', () => this._handleOpen());
6080
+ this._input.addEventListener('focus', () => {
6081
+ this._runEngineEffects(this._engine.dispatch({ type: 'FOCUS_GAINED' }));
6082
+ this._handleOpen();
6083
+ });
4892
6084
  // When the input loses focus we normally close the dropdown, but
4893
6085
  // clicking an option will blur the input before the option's click
4894
6086
  // handler executes. To avoid the blur timer closing the dropdown
@@ -4896,6 +6088,7 @@ class EnhancedSelect extends HTMLElement {
4896
6088
  // interacting with the options container. The close callback checks this
4897
6089
  // flag and skips closing if the user is about to click an option.
4898
6090
  this._input.addEventListener('blur', (e) => {
6091
+ this._runEngineEffects(this._engine.dispatch({ type: 'FOCUS_LOST' }));
4899
6092
  const related = e.relatedTarget;
4900
6093
  if (related && (this._shadow.contains(related) || this._container.contains(related))) {
4901
6094
  return;
@@ -4910,7 +6103,7 @@ class EnhancedSelect extends HTMLElement {
4910
6103
  if (active && (this._shadow.contains(active) || this._container.contains(active))) {
4911
6104
  return;
4912
6105
  }
4913
- this._handleClose();
6106
+ this._handleClose('blur');
4914
6107
  }, 150);
4915
6108
  });
4916
6109
  // Input search
@@ -4991,11 +6184,10 @@ class EnhancedSelect extends HTMLElement {
4991
6184
  const items = await this._config.serverSide.fetchSelectedItems(this._config.serverSide.initialSelectedValues);
4992
6185
  if (generation !== this._asyncGeneration || !this.isConnected)
4993
6186
  return;
4994
- // Add to state
4995
- items.forEach((item, index) => {
4996
- this._state.selectedItems.set(index, item);
4997
- this._state.selectedIndices.add(index);
6187
+ const fetchedRegistry = createItemRegistry(items, this._itemAdapter, {
6188
+ duplicateKeyPolicy: this._getDuplicateKeyPolicy(),
4998
6189
  });
6190
+ this._requestSelectionReplacement(fetchedRegistry.records, 'external-value-sync', 'initial selected items');
4999
6191
  this._updateInputDisplay();
5000
6192
  }
5001
6193
  catch (error) {
@@ -5009,25 +6201,121 @@ class EnhancedSelect extends HTMLElement {
5009
6201
  }
5010
6202
  }
5011
6203
  }
6204
+ _runEngineEffects(effects) {
6205
+ this._effectRunner.run(effects, {
6206
+ focusTrigger: () => {
6207
+ this._applyFocusIntent('input', 'engine-focus-trigger');
6208
+ },
6209
+ syncAria: () => {
6210
+ this._syncPopupAria();
6211
+ },
6212
+ });
6213
+ }
6214
+ _syncPopupAria() {
6215
+ if (!this._input)
6216
+ return;
6217
+ this._syncComboboxAccessibility();
6218
+ }
6219
+ _syncComboboxAccessibility() {
6220
+ if (!this._input || !this._engine || !this._state)
6221
+ return;
6222
+ const accessibilityState = deriveAccessibilityState(this._engine.state, {
6223
+ searchable: this._config.searchable,
6224
+ readonly: !this._config.searchable,
6225
+ invalid: this._hasError,
6226
+ label: {
6227
+ ariaLabel: this.getAttribute('aria-label')?.trim() || null,
6228
+ ariaDescription: this.getAttribute('aria-description')?.trim() || null,
6229
+ },
6230
+ errorMessage: this._errorMessage,
6231
+ errorDescriptionId: this._hasError && this._errorMessage ? this._errorDescription?.id ?? null : null,
6232
+ });
6233
+ const effects = computeAccessibilityEffects(accessibilityState, {
6234
+ controlsId: this._dropdown?.id || null,
6235
+ optionKeys: [],
6236
+ }).filter((effect) => effect.type === 'SYNC_COMBOBOX_ARIA');
6237
+ applyAccessibilityEffects(effects, {
6238
+ combobox: this._input,
6239
+ getOptionByKey: (key) => {
6240
+ if (!this._state.isOpen)
6241
+ return null;
6242
+ const index = this._itemRegistry.keyToIndex.get(key);
6243
+ return index === undefined ? null : this._getOptionElementByIndex(index);
6244
+ },
6245
+ });
6246
+ }
6247
+ _syncListboxAccessibility() {
6248
+ if (!this._dropdown || !this._engine || !this._state)
6249
+ return;
6250
+ const derivedState = deriveAccessibilityState(this._engine.state, {
6251
+ label: { ariaLabel: this.getAttribute('aria-label')?.trim() || null },
6252
+ });
6253
+ const accessibilityState = {
6254
+ ...derivedState,
6255
+ // The component's existing busy lifecycle is not yet mirrored to engine dataStatus.
6256
+ busy: this._state.isBusy,
6257
+ };
6258
+ const effects = computeAccessibilityEffects(accessibilityState, {
6259
+ controlsId: this._dropdown.id || null,
6260
+ optionKeys: [],
6261
+ }).filter((effect) => effect.type === 'SYNC_LISTBOX_ARIA');
6262
+ applyAccessibilityEffects(effects, { listbox: this._dropdown });
6263
+ }
6264
+ _syncRenderedOptionAccessibility() {
6265
+ if (!this._optionsContainer || !this._engine || !this._state)
6266
+ return;
6267
+ const optionTargets = new Map();
6268
+ this._optionsContainer.querySelectorAll('[data-index]').forEach((option) => {
6269
+ const index = Number(option.getAttribute('data-index'));
6270
+ if (!Number.isFinite(index))
6271
+ return;
6272
+ const key = this._itemRegistry.indexToKey.get(index);
6273
+ if (key !== undefined)
6274
+ optionTargets.set(key, option);
6275
+ });
6276
+ if (optionTargets.size === 0)
6277
+ return;
6278
+ const effects = computeAccessibilityEffects(deriveAccessibilityState(this._engine.state), {
6279
+ controlsId: this._dropdown?.id || null,
6280
+ optionKeys: [...optionTargets.keys()],
6281
+ }).filter((effect) => effect.type === 'SYNC_OPTION_ARIA');
6282
+ applyAccessibilityEffects(effects, {
6283
+ getOptionByKey: (key) => optionTargets.get(key) ?? null,
6284
+ });
6285
+ }
6286
+ _applyFocusIntent(target, reason, focusTarget) {
6287
+ const effects = computeAccessibilityEffects(deriveAccessibilityState(this._engine.state), {
6288
+ optionKeys: [],
6289
+ focusIntents: [{ target, reason }],
6290
+ }).filter((effect) => effect.type === 'FOCUS_INTENT');
6291
+ applyAccessibilityEffects(effects, {
6292
+ focusTargets: {
6293
+ input: target === 'input' ? this._input : null,
6294
+ clearButton: target === 'clear-button' ? this._clearControl : null,
6295
+ getActiveOption: () => target === 'active-option' ? focusTarget ?? null : null,
6296
+ },
6297
+ }, { applyFocus: true });
6298
+ }
5012
6299
  _handleOpen() {
5013
- if (!this._config.enabled || this._state.isOpen)
6300
+ if (!this._config.enabled) {
6301
+ this._runEngineEffects(this._engine.dispatch({ type: 'DISABLED_CHANGED', disabled: true }));
6302
+ return;
6303
+ }
6304
+ if (this._state.isOpen)
5014
6305
  return;
5015
6306
  // close any other open selects before proceeding
5016
6307
  EnhancedSelect._instances.forEach(inst => {
5017
6308
  if (inst !== this)
5018
6309
  inst._handleClose();
5019
6310
  });
5020
- // Always focus the input when opening so callers (arrow click,
5021
- // programmatic `open()`, etc.) get the keyboard cursor. This was a
5022
- // frequent source of confusion in #14 where people opened the dropdown
5023
- // but the text field never received focus.
5024
- this._input.focus();
6311
+ const effects = this._engine.dispatch({ type: 'OPEN_REQUEST' });
6312
+ if (!effects.some((effect) => effect.type === 'POPUP_OPENED'))
6313
+ return;
6314
+ this._runEngineEffects(effects);
5025
6315
  this._markOpenStart();
5026
- this._state.isOpen = true;
5027
6316
  this.setAttribute('data-open', 'true');
5028
6317
  this._liftStackingAncestors();
5029
6318
  this._dropdown.style.display = 'block';
5030
- this._input.setAttribute('aria-expanded', 'true');
5031
6319
  this._updateArrowRotation();
5032
6320
  // Render options when opening
5033
6321
  this._renderOptions();
@@ -5038,26 +6326,32 @@ class EnhancedSelect extends HTMLElement {
5038
6326
  this._announce('Options expanded');
5039
6327
  // Scroll to selected if configured
5040
6328
  if (this._config.scrollToSelected.enabled) {
6329
+ const keyboardActiveChangeGeneration = this._keyboardActiveChangeGeneration;
6330
+ const canRestoreOpenSelection = () => this._state.isOpen
6331
+ && this._keyboardActiveChangeGeneration === keyboardActiveChangeGeneration;
5041
6332
  // Use requestAnimationFrame for better timing after render
5042
6333
  this._requestLifecycleFrame(() => {
6334
+ if (!canRestoreOpenSelection())
6335
+ return;
5043
6336
  // Double RAF to ensure layout is complete
5044
6337
  this._requestLifecycleFrame(() => {
6338
+ if (!canRestoreOpenSelection())
6339
+ return;
5045
6340
  this._scrollToSelected();
5046
6341
  });
5047
6342
  });
5048
6343
  }
5049
6344
  }
5050
- _handleClose() {
5051
- if (!this._state.isOpen)
6345
+ _handleClose(reason = 'programmatic') {
6346
+ const effects = this._engine.dispatch({ type: 'CLOSE_REQUEST', reason });
6347
+ if (!effects.some((effect) => effect.type === 'POPUP_CLOSED'))
5052
6348
  return;
5053
- this._state.isOpen = false;
5054
6349
  this.removeAttribute('data-open');
5055
6350
  this._restoreLiftedAncestors();
5056
6351
  this._dropdown.style.display = 'none';
5057
6352
  this._dropdown.setAttribute('data-placement', this._resolvedDropdownPlacement);
5058
- this._input.setAttribute('aria-expanded', 'false');
5059
- this._input.removeAttribute('aria-activedescendant');
5060
6353
  this._updateArrowRotation();
6354
+ this._runEngineEffects(effects);
5061
6355
  this._emit('close', {});
5062
6356
  this._config.callbacks.onClose?.();
5063
6357
  this._announce('Options collapsed');
@@ -5068,14 +6362,13 @@ class EnhancedSelect extends HTMLElement {
5068
6362
  this._liftStackingAncestors();
5069
6363
  this._dropdown.style.display = 'block';
5070
6364
  this._syncDropdownPlacement();
5071
- this._input.setAttribute('aria-expanded', 'true');
5072
6365
  }
5073
6366
  else {
5074
6367
  this.removeAttribute('data-open');
5075
6368
  this._restoreLiftedAncestors();
5076
6369
  this._dropdown.style.display = 'none';
5077
- this._input.setAttribute('aria-expanded', 'false');
5078
6370
  }
6371
+ this._syncComboboxAccessibility();
5079
6372
  }
5080
6373
  _liftStackingAncestors() {
5081
6374
  this._restoreLiftedAncestors();
@@ -5335,13 +6628,17 @@ class EnhancedSelect extends HTMLElement {
5335
6628
  if (!this._state.isOpen) {
5336
6629
  this._handleOpen();
5337
6630
  }
5338
- else if (this._state.activeIndex >= 0) {
5339
- this._selectOption(this._state.activeIndex, { shiftKey: e.shiftKey, toggleKey: e.ctrlKey || e.metaKey });
6631
+ else {
6632
+ const activeKey = this._engine.state.activeKey;
6633
+ const currentIndex = activeKey === null ? -1 : this._itemRegistry.keyToIndex.get(activeKey) ?? -1;
6634
+ if (currentIndex >= 0) {
6635
+ this._selectOption(currentIndex, { shiftKey: e.shiftKey, toggleKey: e.ctrlKey || e.metaKey, reason: 'keyboard' });
6636
+ }
5340
6637
  }
5341
6638
  break;
5342
6639
  case 'Escape':
5343
6640
  e.preventDefault();
5344
- this._handleClose();
6641
+ this._handleClose('escape');
5345
6642
  break;
5346
6643
  case 'Tab':
5347
6644
  if (this._state.isOpen) {
@@ -5367,7 +6664,9 @@ class EnhancedSelect extends HTMLElement {
5367
6664
  const selectableIndices = this._getSelectableOptionIndices();
5368
6665
  if (selectableIndices.length === 0)
5369
6666
  return;
5370
- const currentPosition = selectableIndices.indexOf(this._state.activeIndex);
6667
+ const activeKey = this._engine.state.activeKey;
6668
+ const currentIndex = activeKey === null ? -1 : this._itemRegistry.keyToIndex.get(activeKey) ?? -1;
6669
+ const currentPosition = selectableIndices.indexOf(currentIndex);
5371
6670
  const basePosition = currentPosition >= 0
5372
6671
  ? currentPosition
5373
6672
  : delta >= 0
@@ -5377,7 +6676,7 @@ class EnhancedSelect extends HTMLElement {
5377
6676
  const next = selectableIndices[nextPosition];
5378
6677
  this._setActive(next);
5379
6678
  if (this._config.selection.mode === 'multi' && opts?.shiftKey) {
5380
- const anchor = this._rangeAnchorIndex ?? this._state.activeIndex;
6679
+ const anchor = this._rangeAnchorIndex ?? currentIndex;
5381
6680
  const anchorIndex = anchor >= 0 ? anchor : next;
5382
6681
  if (this._rangeAnchorIndex === null) {
5383
6682
  this._rangeAnchorIndex = anchorIndex;
@@ -5385,14 +6684,26 @@ class EnhancedSelect extends HTMLElement {
5385
6684
  this._selectRange(anchorIndex, next, { clear: !opts?.toggleKey });
5386
6685
  }
5387
6686
  }
5388
- _setActive(index) {
5389
- const option = this._getOptionElementByIndex(index);
5390
- if (!option || (option.getAttribute('aria-disabled') === 'true' && !option.classList.contains('smilodon-option--disabled-focusable'))) {
6687
+ _setActive(index, reason = 'keyboard') {
6688
+ this._ensureRegistryCurrent();
6689
+ const record = this._getRecordByIndex(index);
6690
+ let option = this._getOptionElementByIndex(index);
6691
+ if (!option && record && this._guardedVirtualizer) {
6692
+ this._materializeGuardedVirtualKey(record.key);
6693
+ option = this._getOptionElementByIndex(index);
6694
+ }
6695
+ if (!record || record.disabled || !option || option.getAttribute('aria-disabled') === 'true') {
5391
6696
  return;
5392
6697
  }
6698
+ if (reason === 'keyboard')
6699
+ this._keyboardActiveChangeGeneration += 1;
6700
+ const previousIndex = this._state.activeIndex;
6701
+ this._dispatchActiveKey(record.key, reason, 'set active');
6702
+ if (this._state.activeIndex !== index)
6703
+ return;
5393
6704
  // Clear previous active state
5394
- if (this._state.activeIndex >= 0) {
5395
- const prevOption = this._getOptionElementByIndex(this._state.activeIndex);
6705
+ if (previousIndex >= 0 && previousIndex !== index) {
6706
+ const prevOption = this._getOptionElementByIndex(previousIndex);
5396
6707
  if (prevOption) {
5397
6708
  // Check if it's a custom SelectOption or a lightweight DOM element
5398
6709
  if ('setActive' in prevOption && typeof prevOption.setActive === 'function') {
@@ -5400,11 +6711,10 @@ class EnhancedSelect extends HTMLElement {
5400
6711
  }
5401
6712
  else {
5402
6713
  // Lightweight option - remove active class
5403
- prevOption.classList.remove('smilodon-option--active');
6714
+ prevOption.classList.remove('active', 'smilodon-option--active');
5404
6715
  }
5405
6716
  }
5406
6717
  }
5407
- this._state.activeIndex = index;
5408
6718
  // Set new active state
5409
6719
  if (option) {
5410
6720
  // Check if it's a custom SelectOption or a lightweight DOM element
@@ -5413,7 +6723,7 @@ class EnhancedSelect extends HTMLElement {
5413
6723
  }
5414
6724
  else {
5415
6725
  // Lightweight option - add active class
5416
- option.classList.add('smilodon-option--active');
6726
+ option.classList.add('active', 'smilodon-option--active');
5417
6727
  }
5418
6728
  if (typeof option.scrollIntoView === 'function') {
5419
6729
  // Don't scroll wildly when just opening with pre-selections
@@ -5423,8 +6733,7 @@ class EnhancedSelect extends HTMLElement {
5423
6733
  const total = this._state.loadedItems.length;
5424
6734
  this._announce(`Item ${index + 1} of ${total}`);
5425
6735
  // Update aria-activedescendant using the actual option id when available
5426
- const optionId = option.id || `${this._uniqueId}-option-${index}`;
5427
- this._input.setAttribute('aria-activedescendant', optionId);
6736
+ this._syncLegacyActiveAria();
5428
6737
  }
5429
6738
  }
5430
6739
  _getOptionElementByIndex(index) {
@@ -5435,10 +6744,16 @@ class EnhancedSelect extends HTMLElement {
5435
6744
  // Only return elements with data-index or data-sm-selectable attributes
5436
6745
  return Array.from(this._optionsContainer.children).filter((child) => {
5437
6746
  return (child.hasAttribute('data-index') || child.hasAttribute('data-sm-selectable'))
5438
- && (child.getAttribute('aria-disabled') !== 'true' || child.classList.contains('smilodon-option--disabled-focusable'));
6747
+ && child.getAttribute('aria-disabled') !== 'true';
5439
6748
  });
5440
6749
  }
5441
6750
  _getSelectableOptionIndices() {
6751
+ if (this._guardedVirtualizer) {
6752
+ return this._renderPlan.filteredKeys.flatMap((key) => {
6753
+ const record = this._itemRegistry.keyToRecord.get(key);
6754
+ return record && !record.disabled ? [record.index] : [];
6755
+ });
6756
+ }
5442
6757
  return this._getSelectableOptions()
5443
6758
  .map((option) => Number(option.getAttribute('data-sm-index') ?? option.getAttribute('data-index')))
5444
6759
  .filter((index) => Number.isFinite(index));
@@ -5456,7 +6771,7 @@ class EnhancedSelect extends HTMLElement {
5456
6771
  keyboardFocus: (index) => {
5457
6772
  this._setActive(index);
5458
6773
  const el = this._getOptionElementByIndex(index);
5459
- el?.focus?.();
6774
+ this._applyFocusIntent('active-option', 'renderer-keyboard-focus', el);
5460
6775
  },
5461
6776
  };
5462
6777
  }
@@ -5471,43 +6786,25 @@ class EnhancedSelect extends HTMLElement {
5471
6786
  const getValue = this._config.serverSide.getLabelFromItem || ((item) => item?.label ?? String(item));
5472
6787
  const matchIndex = this._state.loadedItems.findIndex((item) => getValue(item).toLowerCase().startsWith(this._typeBuffer));
5473
6788
  if (matchIndex >= 0) {
5474
- this._setActive(matchIndex);
6789
+ this._setActive(matchIndex, 'search');
5475
6790
  }
5476
6791
  }
5477
6792
  _selectAll() {
5478
6793
  if (this._config.selection.mode !== 'multi')
5479
6794
  return;
6795
+ this._ensureRegistryCurrent();
5480
6796
  const options = this._getSelectableOptions();
5481
- const maxSelections = this._config.selection.maxSelections || 0;
6797
+ const entries = this._getSelectedEntries();
5482
6798
  options.forEach((option) => {
5483
6799
  const optionIndex = Number(option.getAttribute('data-sm-index') ?? option.getAttribute('data-index'));
5484
6800
  if (!Number.isFinite(optionIndex))
5485
6801
  return;
5486
- if (maxSelections > 0 && this._state.selectedIndices.size >= maxSelections) {
5487
- return;
5488
- }
5489
- if (!this._state.selectedIndices.has(optionIndex)) {
5490
- // Check if it's a custom SelectOption or a lightweight DOM element
5491
- if ('getConfig' in option && typeof option.getConfig === 'function') {
5492
- const config = option.getConfig();
5493
- if (this._isOptionSelectionBlocked(config.item))
5494
- return;
5495
- this._state.selectedIndices.add(optionIndex);
5496
- this._state.selectedItems.set(optionIndex, config.item);
5497
- option.setSelected(true);
5498
- }
5499
- else {
5500
- // Lightweight option - get item from data attribute or state
5501
- const item = this._state.loadedItems[optionIndex];
5502
- if (item && !this._isOptionSelectionBlocked(item)) {
5503
- this._state.selectedIndices.add(optionIndex);
5504
- this._state.selectedItems.set(optionIndex, item);
5505
- option.classList.add('smilodon-option--selected');
5506
- option.setAttribute('aria-selected', 'true');
5507
- }
5508
- }
5509
- }
6802
+ const record = this._getRecordByIndex(optionIndex);
6803
+ if (record && !this._isOptionSelectionBlocked(record.item))
6804
+ entries.push(record);
5510
6805
  });
6806
+ this._requestSelectionReplacement(entries, 'keyboard', 'select all');
6807
+ this._renderOptions();
5511
6808
  this._updateInputDisplay();
5512
6809
  this._emitChange();
5513
6810
  this._announce(`Selected all ${options.length} items`);
@@ -5515,82 +6812,101 @@ class EnhancedSelect extends HTMLElement {
5515
6812
  _selectRange(start, end, opts) {
5516
6813
  if (this._config.selection.mode !== 'multi')
5517
6814
  return;
5518
- const maxSelections = this._config.selection.maxSelections || 0;
6815
+ this._ensureRegistryCurrent();
5519
6816
  const [min, max] = start < end ? [start, end] : [end, start];
5520
- if (opts?.clear) {
5521
- this._state.selectedIndices.clear();
5522
- this._state.selectedItems.clear();
5523
- }
6817
+ const selectedEntries = this._getSelectedEntries();
6818
+ const entries = opts?.clear
6819
+ ? selectedEntries.filter((entry) => !this._itemRegistry.keyToRecord.has(entry.key))
6820
+ : selectedEntries;
5524
6821
  for (let i = min; i <= max; i += 1) {
5525
- if (maxSelections > 0 && this._state.selectedIndices.size >= maxSelections)
5526
- break;
5527
- const item = this._state.loadedItems[i];
6822
+ const record = this._getRecordByIndex(i);
5528
6823
  const optionEl = this._getOptionElementByIndex(i);
5529
6824
  if (optionEl?.getAttribute('aria-disabled') === 'true' && !optionEl.classList.contains('smilodon-option--disabled-selectable'))
5530
6825
  continue;
5531
- if (!item)
5532
- continue;
5533
- if (this._isOptionSelectionBlocked(item))
6826
+ if (!record || this._isOptionSelectionBlocked(record.item))
5534
6827
  continue;
5535
- this._state.selectedIndices.add(i);
5536
- this._state.selectedItems.set(i, item);
6828
+ entries.push(record);
5537
6829
  }
6830
+ this._requestSelectionReplacement(entries, opts?.reason ?? 'keyboard', 'select range');
5538
6831
  this._renderOptions();
5539
6832
  this._updateInputDisplay();
6833
+ const target = this._getRecordByIndex(end);
6834
+ const selectDetail = target ? this._getSelectEventDetail(target) : null;
6835
+ if (selectDetail)
6836
+ this._emit('select', selectDetail);
5540
6837
  this._emitChange();
5541
6838
  this._announce(`${this._state.selectedIndices.size} items selected`);
6839
+ if (selectDetail)
6840
+ this._config.callbacks.onSelect?.(selectDetail);
6841
+ }
6842
+ _getSelectEventDetail(record) {
6843
+ const getValue = this._config.serverSide.getValueFromItem || ((item) => item?.value ?? item);
6844
+ const getLabel = this._config.serverSide.getLabelFromItem || ((item) => item?.label ?? String(item));
6845
+ return {
6846
+ item: record.item,
6847
+ index: record.index,
6848
+ value: getValue(record.item),
6849
+ label: getLabel(record.item),
6850
+ selected: this._engine.state.selectedKeys.has(record.key),
6851
+ multi: this._config.selection.mode === 'multi',
6852
+ };
5542
6853
  }
5543
6854
  _setInitialActiveOption() {
5544
6855
  const selectableIndices = this._getSelectableOptionIndices();
5545
- if (selectableIndices.length === 0)
5546
- return;
5547
6856
  const selected = Array.from(this._state.selectedIndices).sort((a, b) => a - b);
5548
- if (this._config.selection.mode === 'multi' && selected.length === 0) {
5549
- this._state.activeIndex = -1;
5550
- this._input.removeAttribute('aria-activedescendant');
6857
+ if (selectableIndices.length === 0 || (this._config.selection.mode === 'multi' && selected.length === 0)) {
6858
+ this._dispatchActiveKey(null, 'open', 'initial active option');
5551
6859
  return;
5552
6860
  }
5553
6861
  const target = selected.find((index) => selectableIndices.includes(index)) ?? selectableIndices[0];
5554
- this._setActive(target);
6862
+ this._setActive(target, 'open');
5555
6863
  }
5556
6864
  _announce(message) {
5557
- if (this._liveRegion) {
5558
- this._liveRegion.textContent = message;
5559
- this._setLifecycleTimeout(() => {
5560
- if (this._liveRegion)
5561
- this._liveRegion.textContent = '';
5562
- }, 1000);
5563
- }
6865
+ const effects = computeAccessibilityEffects(deriveAccessibilityState(this._engine.state), {
6866
+ optionKeys: [],
6867
+ announcements: [{ politeness: 'polite', message }],
6868
+ }).filter((effect) => effect.type === 'ANNOUNCE');
6869
+ applyAccessibilityEffects(effects, { liveRegion: this._liveRegion });
6870
+ if (!this._liveRegion)
6871
+ return;
6872
+ this._setLifecycleTimeout(() => {
6873
+ const clearEffects = computeAccessibilityEffects(deriveAccessibilityState(this._engine.state), {
6874
+ optionKeys: [],
6875
+ announcements: [{ politeness: 'polite', message: '' }],
6876
+ }).filter((effect) => effect.type === 'ANNOUNCE');
6877
+ applyAccessibilityEffects(clearEffects, { liveRegion: this._liveRegion });
6878
+ }, 1000);
5564
6879
  }
5565
6880
  _selectOption(index, opts) {
5566
6881
  // FIX: Do not rely on this._optionsContainer.children[index] because filtering changes the children
5567
6882
  // Instead, use the index to update state directly
5568
- const item = this._state.loadedItems[index];
5569
- if (!item) {
6883
+ this._ensureRegistryCurrent();
6884
+ const record = this._getRecordByIndex(index);
6885
+ if (!record)
5570
6886
  return;
5571
- }
6887
+ index = record.index;
6888
+ const item = record.item;
5572
6889
  if (this._isOptionSelectionBlocked(item)) {
5573
6890
  return;
5574
6891
  }
5575
- const isCurrentlySelected = this._state.selectedIndices.has(index);
6892
+ const isCurrentlySelected = this._engine.state.selectedKeys.has(record.key);
6893
+ const reason = opts?.reason ?? 'pointer';
5576
6894
  // Keep active/focus styling aligned with the most recently interacted option.
5577
6895
  // Without this, a previously selected item may retain active classes/styles
5578
6896
  // after selecting a different option.
5579
- this._state.activeIndex = index;
6897
+ if (!record.disabled) {
6898
+ this._dispatchActiveKey(record.key, reason === 'keyboard' ? 'keyboard' : 'pointer', 'option selection');
6899
+ }
5580
6900
  if (this._config.selection.mode === 'single') {
5581
- // Single select: clear previous and select new
5582
- const wasSelected = this._state.selectedIndices.has(index);
5583
- this._state.selectedIndices.clear();
5584
- this._state.selectedItems.clear();
5585
- if (!wasSelected || !this._config.selection.allowDeselect) {
5586
- // Select this option
5587
- this._state.selectedIndices.add(index);
5588
- this._state.selectedItems.set(index, item);
5589
- }
6901
+ this._dispatchSelection({
6902
+ type: isCurrentlySelected && this._config.selection.allowDeselect ? 'TOGGLE_KEY_REQUEST' : 'SELECT_KEY_REQUEST',
6903
+ key: record.key,
6904
+ reason,
6905
+ }, 'single option selection');
5590
6906
  // Re-render to update all option styles
5591
6907
  this._renderOptions();
5592
6908
  if (this._config.selection.closeOnSelect) {
5593
- this._handleClose();
6909
+ this._handleClose('selection');
5594
6910
  }
5595
6911
  }
5596
6912
  else {
@@ -5598,35 +6914,27 @@ class EnhancedSelect extends HTMLElement {
5598
6914
  const shiftKey = Boolean(opts?.shiftKey);
5599
6915
  if (shiftKey) {
5600
6916
  const anchor = this._rangeAnchorIndex ?? index;
5601
- this._selectRange(anchor, index, { clear: !toggleKey });
6917
+ this._selectRange(anchor, index, { clear: !toggleKey, reason });
5602
6918
  this._rangeAnchorIndex = anchor;
5603
6919
  return;
5604
6920
  }
5605
6921
  // Multi select with toggle
5606
6922
  const maxSelections = this._config.selection.maxSelections || 0;
5607
- if (isCurrentlySelected) {
5608
- // Deselect (toggle off)
5609
- this._state.selectedIndices.delete(index);
5610
- this._state.selectedItems.delete(index);
5611
- }
5612
- else {
5613
- // Select (toggle on)
5614
- if (maxSelections > 0 && this._state.selectedIndices.size >= maxSelections) {
5615
- this._announce(`Maximum ${maxSelections} selections allowed`);
5616
- return; // Max selections reached
5617
- }
5618
- this._state.selectedIndices.add(index);
5619
- this._state.selectedItems.set(index, item);
6923
+ if (!isCurrentlySelected && maxSelections > 0 && this._engine.state.selectedKeys.size >= maxSelections) {
6924
+ this._announce(`Maximum ${maxSelections} selections allowed`);
6925
+ this._renderOptions();
6926
+ return;
5620
6927
  }
6928
+ this._dispatchSelection({ type: 'TOGGLE_KEY_REQUEST', key: record.key, reason }, 'multi option selection');
5621
6929
  // Re-render to update styles (safer than trying to find the element in filtered list)
5622
6930
  this._renderOptions();
5623
6931
  }
5624
6932
  this._rangeAnchorIndex = index;
5625
6933
  this._updateInputDisplay();
6934
+ const selectDetail = this._getSelectEventDetail(record);
6935
+ this._emit('select', selectDetail);
5626
6936
  this._emitChange();
5627
- const getValue = this._config.serverSide.getValueFromItem || ((item) => item?.value ?? item);
5628
- const getLabel = this._config.serverSide.getLabelFromItem || ((item) => item?.label ?? String(item));
5629
- const label = getLabel(item);
6937
+ const label = selectDetail.label;
5630
6938
  if (this._config.selection.mode === 'single') {
5631
6939
  this._announce(`Selected ${label}`);
5632
6940
  }
@@ -5635,25 +6943,34 @@ class EnhancedSelect extends HTMLElement {
5635
6943
  const action = isCurrentlySelected ? 'Deselected' : 'Selected';
5636
6944
  this._announce(`${action} ${label}. ${selectedCount} selected`);
5637
6945
  }
5638
- this._config.callbacks.onSelect?.({
5639
- item: item,
5640
- index,
5641
- value: getValue(item),
5642
- label: getLabel(item),
5643
- selected: this._state.selectedIndices.has(index),
5644
- });
6946
+ this._config.callbacks.onSelect?.(selectDetail);
5645
6947
  }
5646
- _handleOptionRemove(index) {
5647
- const item = this._state.selectedItems.get(index);
5648
- const option = this._getOptionElementByIndex(index);
5649
- this._state.selectedIndices.delete(index);
5650
- this._state.selectedItems.delete(index);
6948
+ _handleOptionRemove(index, key) {
6949
+ this._ensureRegistryCurrent();
6950
+ const entry = this._getSelectedEntries().find((selected) => key === undefined
6951
+ ? selected.index === index
6952
+ : selected.key === key);
6953
+ if (!entry)
6954
+ return;
6955
+ const item = entry.item;
6956
+ const activeElement = this._shadow.activeElement;
6957
+ const focusedBadge = activeElement instanceof HTMLButtonElement
6958
+ && activeElement.getAttribute('part') === 'chip-remove'
6959
+ ? activeElement.closest('.selection-badge')
6960
+ : null;
6961
+ const hadFocusedChipRemove = focusedBadge !== null;
6962
+ const focusedBadgeIndex = focusedBadge
6963
+ ? Array.from(this._inputContent.querySelectorAll('.selection-badge')).indexOf(focusedBadge)
6964
+ : -1;
6965
+ const option = this._itemRegistry.keyToRecord.has(entry.key)
6966
+ ? this._getOptionElementByIndex(entry.index)
6967
+ : null;
6968
+ this._dispatchSelection({ type: 'DESELECT_KEY_REQUEST', key: entry.key, reason: 'pointer' }, 'remove selected item');
5651
6969
  if (option && 'setSelected' in option && typeof option.setSelected === 'function') {
5652
6970
  option.setSelected(false);
5653
6971
  }
5654
6972
  else if (option) {
5655
6973
  option.classList.remove('selected', 'sm-selected', 'smilodon-option--selected');
5656
- option.setAttribute('aria-selected', 'false');
5657
6974
  const stateTokens = (option.dataset.smState || '')
5658
6975
  .split(' ')
5659
6976
  .map(token => token.trim())
@@ -5668,13 +6985,24 @@ class EnhancedSelect extends HTMLElement {
5668
6985
  this._updateInputDisplay();
5669
6986
  this._renderOptions();
5670
6987
  this._emitChange();
6988
+ if (hadFocusedChipRemove && this.isConnected) {
6989
+ const removeButtons = this._inputContent.querySelectorAll('[part="chip-remove"]');
6990
+ if (removeButtons.length > 0) {
6991
+ const nextFocusIndex = Math.min(Math.max(focusedBadgeIndex, 0), removeButtons.length - 1);
6992
+ removeButtons[nextFocusIndex].focus();
6993
+ }
6994
+ else {
6995
+ this._applyFocusIntent('input', 'selected-chip-removed');
6996
+ }
6997
+ }
5671
6998
  const config = option && 'getConfig' in option && typeof option.getConfig === 'function'
5672
6999
  ? option.getConfig()
5673
7000
  : undefined;
5674
- this._emit('remove', { item: config?.item ?? item, index });
7001
+ this._emit('remove', { item: config?.item ?? item, index: entry.index });
5675
7002
  }
5676
7003
  _updateInputDisplay() {
5677
- const selectedItems = Array.from(this._state.selectedItems.values());
7004
+ const selectedEntries = this._getSelectedEntries();
7005
+ const selectedItems = selectedEntries.map(({ item }) => item);
5678
7006
  const getLabel = this._config.serverSide.getLabelFromItem || ((item) => item?.label ?? String(item));
5679
7007
  if (selectedItems.length === 0) {
5680
7008
  this._input.value = '';
@@ -5694,8 +7022,7 @@ class EnhancedSelect extends HTMLElement {
5694
7022
  const existingBadges = this._inputContent.querySelectorAll('.selection-badge');
5695
7023
  existingBadges.forEach(badge => badge.remove());
5696
7024
  // Create badges for each selected item
5697
- const selectedEntries = Array.from(this._state.selectedItems.entries());
5698
- selectedEntries.forEach(([index, item]) => {
7025
+ selectedEntries.forEach(({ key, index, item }) => {
5699
7026
  const badge = document.createElement('span');
5700
7027
  badge.className = 'selection-badge';
5701
7028
  if (this._config.styles.classNames?.badge) {
@@ -5738,7 +7065,7 @@ class EnhancedSelect extends HTMLElement {
5738
7065
  removeBtn.addEventListener('click', (e) => {
5739
7066
  e.stopPropagation();
5740
7067
  e.preventDefault();
5741
- this._handleOptionRemove(index);
7068
+ this._handleOptionRemove(index, key);
5742
7069
  });
5743
7070
  badge.appendChild(removeBtn);
5744
7071
  }
@@ -5762,7 +7089,9 @@ class EnhancedSelect extends HTMLElement {
5762
7089
  if (this._state.selectedIndices.size === 0)
5763
7090
  return;
5764
7091
  const target = this._config.scrollToSelected.multiSelectTarget;
5765
- const indices = Array.from(this._state.selectedIndices).sort((a, b) => a - b);
7092
+ const indices = Array.from(this._state.selectedIndices).filter((index) => index >= 0).sort((a, b) => a - b);
7093
+ if (indices.length === 0)
7094
+ return;
5766
7095
  // For multi-select, find the closest selected item to the current scroll position
5767
7096
  let targetIndex;
5768
7097
  if (this._config.selection.mode === 'multi' && indices.length > 1) {
@@ -5790,7 +7119,14 @@ class EnhancedSelect extends HTMLElement {
5790
7119
  targetIndex = target === 'first' ? indices[0] : indices[indices.length - 1];
5791
7120
  }
5792
7121
  // Find and scroll to the target option
5793
- const option = this._getOptionElementByIndex(targetIndex);
7122
+ let option = this._getOptionElementByIndex(targetIndex);
7123
+ if (!option && this._guardedVirtualizer) {
7124
+ const targetKey = this._itemRegistry.indexToKey.get(targetIndex);
7125
+ if (targetKey !== undefined) {
7126
+ this._materializeGuardedVirtualKey(targetKey);
7127
+ option = this._getOptionElementByIndex(targetIndex);
7128
+ }
7129
+ }
5794
7130
  if (option) {
5795
7131
  // Use smooth scrolling with center alignment for better UX
5796
7132
  if (typeof option.scrollIntoView === 'function') {
@@ -5800,7 +7136,7 @@ class EnhancedSelect extends HTMLElement {
5800
7136
  });
5801
7137
  }
5802
7138
  // Also set it as active for keyboard navigation
5803
- this._setActive(targetIndex);
7139
+ this._setActive(targetIndex, 'programmatic');
5804
7140
  }
5805
7141
  }
5806
7142
  async _loadMoreItems() {
@@ -5832,12 +7168,7 @@ class EnhancedSelect extends HTMLElement {
5832
7168
  }
5833
7169
  _setBusy(busy) {
5834
7170
  this._state.isBusy = busy;
5835
- if (busy) {
5836
- this._dropdown.setAttribute('aria-busy', 'true');
5837
- }
5838
- else {
5839
- this._dropdown.removeAttribute('aria-busy');
5840
- }
7171
+ this._syncListboxAccessibility();
5841
7172
  // Trigger re-render to show/hide busy indicator
5842
7173
  // We use _renderOptions to handle the UI update
5843
7174
  this._renderOptions();
@@ -6006,10 +7337,11 @@ class EnhancedSelect extends HTMLElement {
6006
7337
  };
6007
7338
  }
6008
7339
  _emitChange() {
6009
- const selectedItems = Array.from(this._state.selectedItems.values());
7340
+ const selectedEntries = this._getSelectedEntries();
7341
+ const selectedItems = selectedEntries.map(({ item }) => item);
6010
7342
  const getValue = this._config.serverSide.getValueFromItem || ((item) => item?.value ?? item);
6011
7343
  const selectedValues = selectedItems.map(getValue);
6012
- const selectedIndices = Array.from(this._state.selectedIndices);
7344
+ const selectedIndices = selectedEntries.map(({ index }) => index).filter((index) => index >= 0);
6013
7345
  this._emit('change', { selectedItems, selectedValues, selectedIndices });
6014
7346
  this._config.callbacks.onChange?.(selectedItems, selectedValues);
6015
7347
  }
@@ -6020,6 +7352,7 @@ class EnhancedSelect extends HTMLElement {
6020
7352
  set optionRenderer(renderer) {
6021
7353
  if (this._optionRenderer === renderer)
6022
7354
  return;
7355
+ this._invalidateGuardedMeasurements();
6023
7356
  this._optionRenderer = renderer;
6024
7357
  this._setGlobalStylesMirroring(Boolean(renderer || this._classMap || this._groupHeaderRenderer));
6025
7358
  this._track('style', 'optionRendererChanged', { enabled: Boolean(renderer) });
@@ -6029,12 +7362,12 @@ class EnhancedSelect extends HTMLElement {
6029
7362
  * Set items to display in the select
6030
7363
  */
6031
7364
  setItems(items) {
7365
+ this._invalidateGuardedMeasurements();
6032
7366
  const previousLength = this._state.loadedItems.length;
6033
- this._state.loadedItems = items;
6034
- // If grouped items exist, flatten them to items
6035
- if (this._state.groupedItems.length > 0) {
6036
- this._state.loadedItems = this._state.groupedItems.flatMap(group => group.options);
6037
- }
7367
+ this._rebuildItemRegistry(items);
7368
+ this._state.groupedItems = this._groupItemsByProperty(items);
7369
+ if (!this._state.searchQuery)
7370
+ this._updateInputDisplay();
6038
7371
  const newLength = this._state.loadedItems.length;
6039
7372
  // When infinite scroll is active (preserveScrollPosition = true),
6040
7373
  // we need to maintain scroll position during the update
@@ -6066,19 +7399,42 @@ class EnhancedSelect extends HTMLElement {
6066
7399
  this._renderOptions();
6067
7400
  }
6068
7401
  }
7402
+ _groupItemsByProperty(items) {
7403
+ const hasGroupData = items.some((item, index) => this._itemAdapter.getGroupKey?.(item, index) !== null);
7404
+ if (!hasGroupData) {
7405
+ return [];
7406
+ }
7407
+ const groups = new Map();
7408
+ items.forEach((item, index) => {
7409
+ const rawGroup = this._itemAdapter.getGroupKey?.(item, index);
7410
+ const label = rawGroup == null ? 'Ungrouped' : String(rawGroup);
7411
+ const options = groups.get(label);
7412
+ if (options) {
7413
+ options.push(item);
7414
+ }
7415
+ else {
7416
+ groups.set(label, [item]);
7417
+ }
7418
+ });
7419
+ return Array.from(groups.entries()).map(([label, options]) => ({ label, options }));
7420
+ }
6069
7421
  /**
6070
7422
  * Set grouped items
6071
7423
  */
6072
7424
  setGroupedItems(groupedItems) {
7425
+ this._destroyGuardedVirtualizer();
7426
+ this._rebuildItemRegistry(groupedItems.flatMap(group => group.options));
6073
7427
  this._state.groupedItems = groupedItems;
6074
- this._state.loadedItems = groupedItems.flatMap(group => group.options);
6075
7428
  this._renderOptions();
7429
+ if (!this._state.searchQuery)
7430
+ this._updateInputDisplay();
6076
7431
  }
6077
7432
  /**
6078
7433
  * Get currently selected items
6079
7434
  */
6080
7435
  getSelectedItems() {
6081
- return Array.from(this._state.selectedItems.values());
7436
+ this._ensureRegistryCurrent();
7437
+ return this._getSelectedEntries().map((entry) => entry.item);
6082
7438
  }
6083
7439
  /**
6084
7440
  * Get all loaded items
@@ -6090,8 +7446,7 @@ class EnhancedSelect extends HTMLElement {
6090
7446
  * Get currently selected values
6091
7447
  */
6092
7448
  getSelectedValues() {
6093
- const getValue = this._config.serverSide.getValueFromItem || ((item) => item?.value ?? item);
6094
- return this.getSelectedItems().map(getValue);
7449
+ return this.getSelectedItems().map((item) => this._getItemValue(item));
6095
7450
  }
6096
7451
  /**
6097
7452
  * Set selected items by value
@@ -6101,16 +7456,10 @@ class EnhancedSelect extends HTMLElement {
6101
7456
  await this._loadSelectedItemsByValues(values);
6102
7457
  }
6103
7458
  else {
6104
- // Select from loaded items
6105
- const getValue = this._config.serverSide.getValueFromItem || ((item) => item?.value ?? item);
6106
- this._state.selectedIndices.clear();
6107
- this._state.selectedItems.clear();
6108
- this._state.loadedItems.forEach((item, index) => {
6109
- if (arrayIncludesValue(values, getValue(item)) && !this._isOptionSelectionBlocked(item)) {
6110
- this._state.selectedIndices.add(index);
6111
- this._state.selectedItems.set(index, item);
6112
- }
6113
- });
7459
+ this._ensureRegistryCurrent();
7460
+ const selected = this._itemRegistry.records
7461
+ .filter((record) => arrayIncludesValue(values, record.value) && !this._isOptionSelectionBlocked(record.item));
7462
+ this._requestSelectionReplacement(selected, 'external-value-sync', 'setSelectedValues');
6114
7463
  this._renderOptions();
6115
7464
  this._updateInputDisplay();
6116
7465
  this._emitChange();
@@ -6128,14 +7477,10 @@ class EnhancedSelect extends HTMLElement {
6128
7477
  const items = await this._config.serverSide.fetchSelectedItems(values);
6129
7478
  if (generation !== this._asyncGeneration || !this.isConnected)
6130
7479
  return;
6131
- this._state.selectedIndices.clear();
6132
- this._state.selectedItems.clear();
6133
- items.forEach((item, index) => {
6134
- if (this._isOptionSelectionBlocked(item))
6135
- return;
6136
- this._state.selectedIndices.add(index);
6137
- this._state.selectedItems.set(index, item);
7480
+ const fetchedRegistry = createItemRegistry(items, this._itemAdapter, {
7481
+ duplicateKeyPolicy: this._getDuplicateKeyPolicy(),
6138
7482
  });
7483
+ this._requestSelectionReplacement(fetchedRegistry.records, 'external-value-sync', 'fetched selected items');
6139
7484
  this._renderOptions();
6140
7485
  this._updateInputDisplay();
6141
7486
  this._emitChange();
@@ -6159,8 +7504,8 @@ class EnhancedSelect extends HTMLElement {
6159
7504
  * Clear all selections
6160
7505
  */
6161
7506
  clear() {
6162
- this._state.selectedIndices.clear();
6163
- this._state.selectedItems.clear();
7507
+ this._ensureRegistryCurrent();
7508
+ this._dispatchSelection({ type: 'CLEAR_SELECTION_REQUEST', reason: 'programmatic' }, 'clear');
6164
7509
  this._renderOptions();
6165
7510
  this._updateInputDisplay();
6166
7511
  this._emitChange();
@@ -6196,8 +7541,17 @@ class EnhancedSelect extends HTMLElement {
6196
7541
  * Update component configuration
6197
7542
  */
6198
7543
  updateConfig(config) {
7544
+ this._invalidateGuardedMeasurements();
6199
7545
  const previousMode = this._config.selection.mode;
7546
+ const previousEnabled = this._config.enabled;
6200
7547
  this._config = this._mergeConfig(this._config, config);
7548
+ this._rebuildItemRegistry();
7549
+ if (previousEnabled !== this._config.enabled) {
7550
+ if (!this._config.enabled && this._state.isOpen) {
7551
+ this._handleClose('disabled');
7552
+ }
7553
+ this._runEngineEffects(this._engine.dispatch({ type: 'DISABLED_CHANGED', disabled: !this._config.enabled }));
7554
+ }
6201
7555
  if (previousMode !== this._config.selection.mode &&
6202
7556
  this._config.limitations?.autoMitigateRuntimeModeSwitch) {
6203
7557
  this.clear();
@@ -6215,7 +7569,7 @@ class EnhancedSelect extends HTMLElement {
6215
7569
  // Update input state based on new config
6216
7570
  if (this._input) {
6217
7571
  this._input.readOnly = !this._config.searchable;
6218
- this._input.setAttribute('aria-autocomplete', this._config.searchable ? 'list' : 'none');
7572
+ this._syncComboboxAccessibility();
6219
7573
  if (this._state.selectedIndices.size === 0) {
6220
7574
  this._input.placeholder = this._config.placeholder || 'Select an option...';
6221
7575
  }
@@ -6233,14 +7587,7 @@ class EnhancedSelect extends HTMLElement {
6233
7587
  }
6234
7588
  }
6235
7589
  this._syncStyleConfigVariables();
6236
- if (this._dropdown) {
6237
- if (this._config.selection.mode === 'multi') {
6238
- this._dropdown.setAttribute('aria-multiselectable', 'true');
6239
- }
6240
- else {
6241
- this._dropdown.removeAttribute('aria-multiselectable');
6242
- }
6243
- }
7590
+ this._syncListboxAccessibility();
6244
7591
  if (this.isConnected) {
6245
7592
  this._syncDirectionConfig();
6246
7593
  this._syncInputContainerMode();
@@ -6303,7 +7650,7 @@ class EnhancedSelect extends HTMLElement {
6303
7650
  clearedSelection: shouldClearSelection && hadSelection,
6304
7651
  clearedSearch: shouldClearSearch && hadSearch,
6305
7652
  });
6306
- this._input.focus();
7653
+ this._applyFocusIntent('input', 'clear-control-complete');
6307
7654
  }
6308
7655
  _syncClearControlState() {
6309
7656
  if (!this._clearControl || !this._inputContainer || !this._arrowContainer)
@@ -6329,7 +7676,9 @@ class EnhancedSelect extends HTMLElement {
6329
7676
  setError(message) {
6330
7677
  this._hasError = true;
6331
7678
  this._errorMessage = message;
6332
- this._input.setAttribute('aria-invalid', 'true');
7679
+ if (this._errorDescription)
7680
+ this._errorDescription.textContent = message;
7681
+ this._syncComboboxAccessibility();
6333
7682
  this._announce(`Error: ${message}`);
6334
7683
  }
6335
7684
  /**
@@ -6338,20 +7687,22 @@ class EnhancedSelect extends HTMLElement {
6338
7687
  clearError() {
6339
7688
  this._hasError = false;
6340
7689
  this._errorMessage = '';
6341
- this._input.removeAttribute('aria-invalid');
7690
+ if (this._errorDescription)
7691
+ this._errorDescription.textContent = '';
7692
+ this._syncComboboxAccessibility();
6342
7693
  }
6343
7694
  /**
6344
7695
  * Set required state
6345
7696
  */
6346
7697
  setRequired(required) {
6347
7698
  if (required) {
6348
- this._input.setAttribute('aria-required', 'true');
6349
7699
  this._input.setAttribute('required', '');
6350
7700
  }
6351
7701
  else {
6352
- this._input.removeAttribute('aria-required');
6353
7702
  this._input.removeAttribute('required');
6354
7703
  }
7704
+ this._syncEngineSelectionConfig();
7705
+ this._syncComboboxAccessibility();
6355
7706
  }
6356
7707
  /**
6357
7708
  * Validate selection (for required fields)
@@ -6368,15 +7719,414 @@ class EnhancedSelect extends HTMLElement {
6368
7719
  /**
6369
7720
  * Render options based on current state
6370
7721
  */
7722
+ _deriveVirtualizationScope(filteredIndices) {
7723
+ const keyForIndex = (index) => this._itemRegistry.indexToKey.get(index);
7724
+ const filteredKeys = filteredIndices
7725
+ .map(keyForIndex)
7726
+ .filter((key) => key !== undefined);
7727
+ return {
7728
+ dataKeys: this._itemRegistry.records.map((record) => record.key),
7729
+ filteredKeys,
7730
+ registeredKeys: Array.from(this._engine.state.registeredKeys),
7731
+ // The current chunked path schedules all filtered items for rendering;
7732
+ // this scaffold records that target set until bounded windows are wired.
7733
+ windowKeys: this._renderPlan.intendedRenderKeys.slice(),
7734
+ mountedKeys: this._getMountedVirtualizationKeys(this._optionsContainer.children),
7735
+ selectedKeys: new Set(this._engine.state.selectedKeys),
7736
+ activeKey: this._engine.state.activeKey,
7737
+ };
7738
+ }
7739
+ _getMountedVirtualizationKeys(targets) {
7740
+ const keyForIndex = (index) => this._itemRegistry.indexToKey.get(index);
7741
+ return Array.from(targets)
7742
+ .filter((target) => target instanceof HTMLElement
7743
+ && (target.hasAttribute('data-sm-selectable') || target.hasAttribute('data-selectable')))
7744
+ .map((target) => Number(target.getAttribute('data-sm-index') ?? target.getAttribute('data-index')))
7745
+ .filter(Number.isInteger)
7746
+ .map(keyForIndex)
7747
+ .filter((key) => key !== undefined);
7748
+ }
7749
+ _refreshMountedVirtualizationScope() {
7750
+ this._virtualizationScope = {
7751
+ ...this._virtualizationScope,
7752
+ mountedKeys: this._getMountedVirtualizationKeys(this._optionsContainer.children),
7753
+ registeredKeys: Array.from(this._engine.state.registeredKeys),
7754
+ selectedKeys: new Set(this._engine.state.selectedKeys),
7755
+ activeKey: this._engine.state.activeKey,
7756
+ };
7757
+ }
7758
+ _appendMountedVirtualizationTargets(targets) {
7759
+ const mountedKeys = this._getMountedVirtualizationKeys(targets);
7760
+ this._virtualizationScope = {
7761
+ ...this._virtualizationScope,
7762
+ mountedKeys: [...new Set([...this._virtualizationScope.mountedKeys, ...mountedKeys])],
7763
+ registeredKeys: Array.from(this._engine.state.registeredKeys),
7764
+ selectedKeys: new Set(this._engine.state.selectedKeys),
7765
+ activeKey: this._engine.state.activeKey,
7766
+ };
7767
+ }
7768
+ _createLegacyRenderPlan(filteredIndices) {
7769
+ const indices = [...filteredIndices];
7770
+ const filteredKeys = indices
7771
+ .map((index) => this._itemRegistry.indexToKey.get(index))
7772
+ .filter((key) => key !== undefined);
7773
+ const filteredIndexByKey = new Map();
7774
+ filteredKeys.forEach((key, filteredIndex) => filteredIndexByKey.set(key, filteredIndex));
7775
+ return {
7776
+ mode: 'legacy-full',
7777
+ filteredIndices: indices,
7778
+ filteredKeys,
7779
+ intendedRenderKeys: filteredKeys.slice(),
7780
+ filteredIndexByKey,
7781
+ };
7782
+ }
7783
+ _createVirtualRenderPlan(startIndex, endIndex) {
7784
+ const filteredKeys = this._renderPlan.filteredKeys.slice();
7785
+ const intendedRenderKeys = computeWindowKeys(filteredKeys, startIndex, endIndex);
7786
+ const filteredIndices = intendedRenderKeys
7787
+ .map((key) => this._itemRegistry.keyToIndex.get(key))
7788
+ .filter((index) => index !== undefined);
7789
+ return {
7790
+ mode: 'virtual-window',
7791
+ filteredIndices,
7792
+ filteredKeys,
7793
+ intendedRenderKeys,
7794
+ filteredIndexByKey: new Map(this._renderPlan.filteredIndexByKey),
7795
+ };
7796
+ }
7797
+ _ensureGuardedVirtualizer(filteredKeys) {
7798
+ const keysChanged = this._guardedVirtualizer !== null && (filteredKeys.length !== this._guardedVirtualizerKeys.length
7799
+ || filteredKeys.some((key, index) => !Object.is(key, this._guardedVirtualizerKeys[index])));
7800
+ if (keysChanged)
7801
+ this._destroyGuardedVirtualizer(true);
7802
+ if (!this._guardedVirtualizer) {
7803
+ // The controller only calculates ranges and scroll intents. Give it a
7804
+ // detached container so its internal styling never touches rendered UI.
7805
+ this._guardedVirtualizer = new Virtualizer(document.createElement('div'), filteredKeys.length, (index) => this._renderPlan.filteredKeys[index], {
7806
+ estimatedItemHeight: this._resolveGuardedEstimatedItemHeight(),
7807
+ buffer: 0,
7808
+ measurementThreshold: 0,
7809
+ });
7810
+ this._guardedVirtualScrollTop = this._optionsContainer.scrollTop;
7811
+ this._guardedVirtualViewportHeight = this._resolveGuardedViewportHeight();
7812
+ this._optionsContainer.addEventListener('scroll', this._onGuardedVirtualScroll, { passive: true });
7813
+ this._guardedScrollListenerAttached = true;
7814
+ }
7815
+ this._guardedVirtualizerKeys = [...filteredKeys];
7816
+ return this._guardedVirtualizer;
7817
+ }
7818
+ _resolveGuardedEstimatedItemHeight() {
7819
+ const configuredHeight = this._config.estimatedItemHeight;
7820
+ if (typeof configuredHeight === 'number' && Number.isFinite(configuredHeight) && configuredHeight > 0) {
7821
+ return configuredHeight;
7822
+ }
7823
+ const renderedOption = this._optionsContainer.querySelector('[part="option"]');
7824
+ const measuredHeight = renderedOption?.getBoundingClientRect().height || renderedOption?.offsetHeight;
7825
+ if (typeof measuredHeight === 'number' && Number.isFinite(measuredHeight) && measuredHeight > 0) {
7826
+ return measuredHeight;
7827
+ }
7828
+ return 48;
7829
+ }
7830
+ _resolveGuardedViewportHeight() {
7831
+ const candidates = [
7832
+ this._optionsContainer.clientHeight,
7833
+ this._optionsContainer.getBoundingClientRect().height,
7834
+ ];
7835
+ return candidates.find((height) => Number.isFinite(height) && height > 0) ?? 0;
7836
+ }
7837
+ _clampGuardedScrollPosition(itemCount, viewportHeight) {
7838
+ if (!this._guardedVirtualizer)
7839
+ return 0;
7840
+ const totalHeight = this._guardedVirtualizer.cumulativeOffset(itemCount);
7841
+ const maxScrollTop = Math.max(0, totalHeight - viewportHeight);
7842
+ const scrollTop = Math.min(Math.max(0, this._guardedVirtualScrollTop), maxScrollTop);
7843
+ this._guardedVirtualScrollTop = scrollTop;
7844
+ if (this._optionsContainer.scrollTop !== scrollTop) {
7845
+ this._optionsContainer.scrollTop = scrollTop;
7846
+ }
7847
+ return scrollTop;
7848
+ }
7849
+ _createGuardedSpacer(position, height) {
7850
+ const spacer = document.createElement('div');
7851
+ spacer.setAttribute('data-virtual-spacer', position);
7852
+ spacer.setAttribute('aria-hidden', 'true');
7853
+ spacer.setAttribute('role', 'presentation');
7854
+ spacer.style.height = `${Number.isFinite(height) ? Math.max(0, height) : 0}px`;
7855
+ spacer.style.minHeight = '0';
7856
+ spacer.style.flex = '0 0 auto';
7857
+ spacer.style.pointerEvents = 'none';
7858
+ return spacer;
7859
+ }
7860
+ _appendGuardedTopSpacer() {
7861
+ const virtualizer = this._guardedVirtualizer;
7862
+ const window = this._guardedVirtualWindow;
7863
+ if (!virtualizer || !window)
7864
+ return;
7865
+ this._optionsContainer.appendChild(this._createGuardedSpacer('top', virtualizer.cumulativeOffset(window.startIndex)));
7866
+ }
7867
+ _appendGuardedBottomSpacer() {
7868
+ const virtualizer = this._guardedVirtualizer;
7869
+ const window = this._guardedVirtualWindow;
7870
+ if (!virtualizer || !window)
7871
+ return;
7872
+ const totalHeight = virtualizer.cumulativeOffset(this._renderPlan.filteredKeys.length);
7873
+ const endOffset = virtualizer.cumulativeOffset(window.endIndex);
7874
+ this._optionsContainer.appendChild(this._createGuardedSpacer('bottom', Math.max(0, totalHeight - endOffset)));
7875
+ }
7876
+ _resolveGuardedOverscan() {
7877
+ return 2;
7878
+ }
7879
+ _applyGuardedWindowUpdate(update, overscan = 0) {
7880
+ if (!this._guardedVirtualizer)
7881
+ return false;
7882
+ this._guardedVirtualScrollTop = update.scrollTop;
7883
+ this._guardedVirtualViewportHeight = update.viewportHeight;
7884
+ const itemCount = this._renderPlan.filteredKeys.length;
7885
+ const nextWindow = {
7886
+ startIndex: Math.max(0, update.window.startIndex - overscan),
7887
+ endIndex: Math.min(itemCount, update.window.endIndex + 1 + overscan),
7888
+ };
7889
+ const changed = this._guardedVirtualWindow?.startIndex !== nextWindow.startIndex
7890
+ || this._guardedVirtualWindow?.endIndex !== nextWindow.endIndex;
7891
+ this._guardedVirtualWindow = nextWindow;
7892
+ return changed;
7893
+ }
7894
+ _scheduleGuardedVirtualWindowUpdate() {
7895
+ if (!this._guardedVirtualizer || this._guardedVirtualWindowRafId !== null)
7896
+ return;
7897
+ this._guardedVirtualWindowRafId = this._requestLifecycleFrame(() => {
7898
+ this._guardedVirtualWindowRafId = null;
7899
+ const virtualizer = this._guardedVirtualizer;
7900
+ if (!virtualizer)
7901
+ return;
7902
+ const update = virtualizer.updateWindow(this._optionsContainer.scrollTop, this._resolveGuardedViewportHeight());
7903
+ this._guardedVirtualOverscan = this._resolveGuardedOverscan();
7904
+ if (update && this._applyGuardedWindowUpdate(update, this._guardedVirtualOverscan)) {
7905
+ this._renderOptions();
7906
+ }
7907
+ });
7908
+ }
7909
+ _cancelGuardedVirtualWindowUpdate() {
7910
+ if (this._guardedVirtualWindowRafId === null)
7911
+ return;
7912
+ cancelAnimationFrame(this._guardedVirtualWindowRafId);
7913
+ this._lifecycleRafs.delete(this._guardedVirtualWindowRafId);
7914
+ this._guardedVirtualWindowRafId = null;
7915
+ }
7916
+ _applyGuardedScrollResult(result) {
7917
+ if (!result || !this._guardedVirtualizer)
7918
+ return false;
7919
+ this._guardedVirtualScrollTop = result.scrollTop;
7920
+ this._optionsContainer.scrollTop = result.scrollTop;
7921
+ const update = this._guardedVirtualizer.updateWindow(this._guardedVirtualScrollTop, this._guardedVirtualViewportHeight);
7922
+ if (!update)
7923
+ return false;
7924
+ this._guardedVirtualWindow = {
7925
+ startIndex: update.window.startIndex,
7926
+ endIndex: update.window.endIndex + 1,
7927
+ };
7928
+ this._guardedVirtualOverscan = 0;
7929
+ return true;
7930
+ }
7931
+ _updateGuardedVirtualWindow(scrollTop, viewportHeight) {
7932
+ this._guardedVirtualizationRequested = true;
7933
+ const virtualizer = this._ensureGuardedVirtualizer(this._renderPlan.filteredKeys);
7934
+ this._guardedVirtualScrollTop = scrollTop;
7935
+ this._guardedVirtualViewportHeight = viewportHeight;
7936
+ const update = virtualizer.updateWindow(scrollTop, viewportHeight);
7937
+ if (!update)
7938
+ return false;
7939
+ this._guardedVirtualOverscan = 0;
7940
+ this._applyGuardedWindowUpdate(update, this._guardedVirtualOverscan);
7941
+ this._optionsContainer.scrollTop = update.scrollTop;
7942
+ return true;
7943
+ }
7944
+ _destroyGuardedVirtualizer(preserveRequestedMode = false) {
7945
+ this._cancelGuardedVirtualWindowUpdate();
7946
+ this._guardedMeasurementGeneration += 1;
7947
+ if (this._guardedScrollListenerAttached) {
7948
+ this._optionsContainer.removeEventListener('scroll', this._onGuardedVirtualScroll);
7949
+ this._guardedScrollListenerAttached = false;
7950
+ }
7951
+ this._guardedVirtualizer?.destroy();
7952
+ this._guardedVirtualizer = null;
7953
+ this._teardownGuardedOptionResizeObserver();
7954
+ if (!preserveRequestedMode)
7955
+ this._guardedVirtualizationRequested = false;
7956
+ this._guardedVirtualizerKeys = [];
7957
+ this._guardedVirtualWindow = null;
7958
+ this._guardedVirtualScrollTop = 0;
7959
+ this._guardedVirtualViewportHeight = 0;
7960
+ this._guardedVirtualOverscan = 0;
7961
+ }
7962
+ _invalidateGuardedMeasurements() {
7963
+ if (this._guardedVirtualizer)
7964
+ this._destroyGuardedVirtualizer(true);
7965
+ }
7966
+ _createGuardedOptionResizeObserver(generation) {
7967
+ if (typeof ResizeObserver === 'undefined')
7968
+ return;
7969
+ this._guardedOptionResizeObserver = new ResizeObserver((entries) => {
7970
+ if (generation !== this._guardedMeasurementGeneration
7971
+ || !this._guardedVirtualizer
7972
+ || !this._guardedVirtualizationRequested
7973
+ || !this.isConnected)
7974
+ return;
7975
+ const virtualizer = this._guardedVirtualizer;
7976
+ const scrollTop = this._optionsContainer.scrollTop;
7977
+ const viewportHeight = this._resolveGuardedViewportHeight();
7978
+ const anchor = this._captureGuardedScrollAnchor(virtualizer, scrollTop, viewportHeight);
7979
+ let changed = false;
7980
+ for (const entry of entries) {
7981
+ const option = entry.target;
7982
+ if (!(option instanceof HTMLElement) || !this._guardedObservedOptions.has(option))
7983
+ continue;
7984
+ if (!option.isConnected || !this._optionsContainer.contains(option))
7985
+ continue;
7986
+ const meta = this._guardedOptionMeasurements.get(option);
7987
+ if (!meta || meta.generation !== generation)
7988
+ continue;
7989
+ const dataIndex = Number(option.getAttribute('data-index'));
7990
+ if (!Number.isInteger(dataIndex) || !Object.is(this._itemRegistry.indexToKey.get(dataIndex), meta.key))
7991
+ continue;
7992
+ const currentIndex = this._renderPlan.filteredIndexByKey.get(meta.key);
7993
+ if (currentIndex === undefined || currentIndex !== meta.index)
7994
+ continue;
7995
+ const reportedHeight = entry.borderBoxSize?.[0]?.blockSize;
7996
+ const height = typeof reportedHeight === 'number' ? reportedHeight : entry.contentRect.height;
7997
+ if (!Number.isFinite(height) || height <= 0)
7998
+ continue;
7999
+ changed = virtualizer.measureItem(meta.index, height) || changed;
8000
+ }
8001
+ if (!changed)
8002
+ return;
8003
+ if (anchor) {
8004
+ const currentAnchorIndex = this._renderPlan.filteredIndexByKey.get(anchor.key);
8005
+ if (currentAnchorIndex !== undefined) {
8006
+ const anchoredScrollTop = Math.max(0, virtualizer.cumulativeOffset(currentAnchorIndex) + anchor.offset);
8007
+ this._guardedVirtualScrollTop = anchoredScrollTop;
8008
+ this._optionsContainer.scrollTop = anchoredScrollTop;
8009
+ }
8010
+ }
8011
+ const update = virtualizer.updateWindow(this._optionsContainer.scrollTop, viewportHeight);
8012
+ if (update)
8013
+ this._applyGuardedWindowUpdate(update, this._guardedVirtualOverscan);
8014
+ this._renderOptions();
8015
+ });
8016
+ }
8017
+ _captureGuardedScrollAnchor(virtualizer, scrollTop, viewportHeight) {
8018
+ const viewportTop = this._optionsContainer.getBoundingClientRect().top + this._optionsContainer.clientTop;
8019
+ const viewportBottom = viewportTop + viewportHeight;
8020
+ const visible = Array.from(this._guardedObservedOptions)
8021
+ .map((option) => ({ option, rect: option.getBoundingClientRect() }))
8022
+ .filter(({ rect }) => rect.height > 0 && rect.bottom > viewportTop && rect.top < viewportBottom)
8023
+ .sort((left, right) => left.rect.top - right.rect.top)[0];
8024
+ const visibleMeta = visible ? this._guardedOptionMeasurements.get(visible.option) : undefined;
8025
+ if (visibleMeta && visibleMeta.generation === this._guardedMeasurementGeneration) {
8026
+ return {
8027
+ key: visibleMeta.key,
8028
+ offset: scrollTop - virtualizer.cumulativeOffset(visibleMeta.index),
8029
+ };
8030
+ }
8031
+ if (this._renderPlan.filteredKeys.length === 0)
8032
+ return null;
8033
+ const index = virtualizer.computeWindow(scrollTop, 0).startIndex;
8034
+ const key = this._renderPlan.filteredKeys[index];
8035
+ return key === undefined ? null : {
8036
+ key,
8037
+ offset: scrollTop - virtualizer.cumulativeOffset(index),
8038
+ };
8039
+ }
8040
+ _syncGuardedOptionResizeTargets() {
8041
+ const virtualizer = this._guardedVirtualizer;
8042
+ if (!virtualizer || !this._guardedVirtualizationRequested || !this.isConnected)
8043
+ return;
8044
+ const candidates = [];
8045
+ for (const child of Array.from(this._optionsContainer.children)) {
8046
+ if (!(child instanceof HTMLElement) || !child.hasAttribute('data-index'))
8047
+ continue;
8048
+ const dataIndex = Number(child.getAttribute('data-index'));
8049
+ if (!Number.isInteger(dataIndex))
8050
+ continue;
8051
+ const key = this._itemRegistry.indexToKey.get(dataIndex);
8052
+ const index = key === undefined ? undefined : this._renderPlan.filteredIndexByKey.get(key);
8053
+ if (key === undefined || index === undefined)
8054
+ continue;
8055
+ candidates.push({ option: child, key, index });
8056
+ }
8057
+ const reusedTarget = candidates.some(({ option }) => this._guardedObserverSeenOptions.has(option));
8058
+ if (reusedTarget && this._guardedOptionResizeObserver) {
8059
+ this._guardedMeasurementGeneration += 1;
8060
+ this._teardownGuardedOptionResizeObserver();
8061
+ }
8062
+ if (!this._guardedOptionResizeObserver) {
8063
+ this._createGuardedOptionResizeObserver(this._guardedMeasurementGeneration);
8064
+ }
8065
+ const observer = this._guardedOptionResizeObserver;
8066
+ if (!observer)
8067
+ return;
8068
+ const current = new Set();
8069
+ for (const { option, key, index } of candidates) {
8070
+ current.add(option);
8071
+ this._guardedOptionMeasurements.set(option, {
8072
+ key,
8073
+ index,
8074
+ generation: this._guardedMeasurementGeneration,
8075
+ });
8076
+ if (!this._guardedObservedOptions.has(option)) {
8077
+ observer.observe(option);
8078
+ this._guardedObserverSeenOptions.add(option);
8079
+ }
8080
+ }
8081
+ for (const previous of this._guardedObservedOptions) {
8082
+ if (!current.has(previous))
8083
+ observer.unobserve(previous);
8084
+ }
8085
+ this._guardedObservedOptions = current;
8086
+ }
8087
+ _teardownGuardedOptionResizeObserver() {
8088
+ for (const option of this._guardedObservedOptions) {
8089
+ this._guardedOptionResizeObserver?.unobserve(option);
8090
+ }
8091
+ this._guardedObservedOptions.clear();
8092
+ this._guardedObserverSeenOptions = new WeakSet();
8093
+ this._guardedOptionResizeObserver?.disconnect();
8094
+ this._guardedOptionResizeObserver = null;
8095
+ this._guardedOptionMeasurements = new WeakMap();
8096
+ }
8097
+ _materializeGuardedVirtualKey(key) {
8098
+ if (!this._guardedVirtualizer)
8099
+ return false;
8100
+ const targetIndex = this._renderPlan.filteredIndexByKey.get(key);
8101
+ if (targetIndex === undefined)
8102
+ return false;
8103
+ this._ensureGuardedVirtualizer(this._renderPlan.filteredKeys);
8104
+ const result = this._guardedVirtualizer.scrollToKey(key, (candidate) => this._renderPlan.filteredIndexByKey.get(candidate));
8105
+ if (!this._applyGuardedScrollResult(result))
8106
+ return false;
8107
+ this._renderOptions();
8108
+ return true;
8109
+ }
8110
+ _refreshVirtualizationScope(filteredIndices) {
8111
+ this._virtualizationScope = this._deriveVirtualizationScope(filteredIndices);
8112
+ }
6371
8113
  _renderOptions() {
8114
+ this._ensureRegistryCurrent();
8115
+ const scrollTopBeforeRender = this._optionsContainer.scrollTop;
6372
8116
  this._renderCycleId += 1;
6373
8117
  const renderCycleId = this._renderCycleId;
8118
+ if (this._guardedVirtualizer) {
8119
+ this._guardedVirtualScrollTop = this._optionsContainer.scrollTop;
8120
+ }
6374
8121
  // Cleanup observer
6375
8122
  if (this._loadMoreTrigger && this._intersectionObserver) {
6376
8123
  this._intersectionObserver.unobserve(this._loadMoreTrigger);
6377
8124
  }
8125
+ this._unobserveGuardedOptionResizeTargets();
6378
8126
  // Clear options container
6379
8127
  this._optionsContainer.innerHTML = '';
8128
+ let filteredIndicesForScope = [];
8129
+ let guardedScrollTopToRestore = null;
6380
8130
  // Ensure dropdown only contains options container (cleanup legacy direct children)
6381
8131
  // We need to preserve optionsContainer, so we can't just clear dropdown.innerHTML
6382
8132
  // But we can check if there are other children and remove them
@@ -6391,6 +8141,10 @@ class EnhancedSelect extends HTMLElement {
6391
8141
  }
6392
8142
  // Show searching state (exclusive state)
6393
8143
  if (this._state.isSearching) {
8144
+ this._registerShadowItems([]);
8145
+ this._renderPlan = this._createLegacyRenderPlan([]);
8146
+ this._refreshVirtualizationScope(filteredIndicesForScope);
8147
+ this._syncLegacyActiveAria();
6394
8148
  const searching = document.createElement('div');
6395
8149
  searching.className = 'searching-state';
6396
8150
  searching.setAttribute('part', 'loading');
@@ -6402,8 +8156,17 @@ class EnhancedSelect extends HTMLElement {
6402
8156
  const getLabel = this._config.serverSide.getLabelFromItem || ((item) => item?.label ?? String(item));
6403
8157
  // Filter items by search query
6404
8158
  const query = this._state.searchQuery.toLowerCase();
8159
+ if (this._guardedMeasurementQuery !== null && this._guardedMeasurementQuery !== query) {
8160
+ this._invalidateGuardedMeasurements();
8161
+ }
8162
+ this._guardedMeasurementQuery = query;
6405
8163
  // Handle Grouped Items Rendering (when no search query)
6406
8164
  if (this._state.groupedItems.length > 0 && !query) {
8165
+ this._destroyGuardedVirtualizer();
8166
+ this._renderPlan = this._createLegacyRenderPlan(this._itemRegistry.records.map((record) => record.index));
8167
+ filteredIndicesForScope = this._renderPlan.filteredIndices;
8168
+ this._registerShadowItems(filteredIndicesForScope);
8169
+ this._refreshVirtualizationScope(filteredIndicesForScope);
6407
8170
  this._state.groupedItems.forEach((group, groupIndex) => {
6408
8171
  let header;
6409
8172
  if (this.groupHeaderRenderer) {
@@ -6441,7 +8204,7 @@ class EnhancedSelect extends HTMLElement {
6441
8204
  }
6442
8205
  else {
6443
8206
  // Normal rendering (flat list or filtered)
6444
- const filteredIndices = [];
8207
+ const computedFilteredIndices = [];
6445
8208
  this._state.loadedItems.forEach((item, index) => {
6446
8209
  if (query) {
6447
8210
  try {
@@ -6453,8 +8216,40 @@ class EnhancedSelect extends HTMLElement {
6453
8216
  return;
6454
8217
  }
6455
8218
  }
6456
- filteredIndices.push(index);
8219
+ computedFilteredIndices.push(index);
6457
8220
  });
8221
+ this._renderPlan = this._createLegacyRenderPlan(computedFilteredIndices);
8222
+ filteredIndicesForScope = this._renderPlan.filteredIndices;
8223
+ this._registerShadowItems(filteredIndicesForScope);
8224
+ if (this._guardedVirtualizationRequested && !this._guardedVirtualizer) {
8225
+ this._ensureGuardedVirtualizer(this._renderPlan.filteredKeys);
8226
+ this._guardedVirtualViewportHeight = this._resolveGuardedViewportHeight();
8227
+ // A data reorder/filter may have invalidated the old virtualizer, but
8228
+ // the physical position is still available before the DOM is cleared.
8229
+ this._guardedVirtualScrollTop = scrollTopBeforeRender;
8230
+ }
8231
+ if (this._guardedVirtualizer) {
8232
+ const virtualizer = this._ensureGuardedVirtualizer(this._renderPlan.filteredKeys);
8233
+ const measuredViewportHeight = this._resolveGuardedViewportHeight();
8234
+ if (measuredViewportHeight > 0) {
8235
+ this._guardedVirtualViewportHeight = measuredViewportHeight;
8236
+ }
8237
+ const scrollTop = this._clampGuardedScrollPosition(this._renderPlan.filteredKeys.length, this._guardedVirtualViewportHeight);
8238
+ guardedScrollTopToRestore = scrollTop;
8239
+ const update = virtualizer.updateWindow(scrollTop, this._guardedVirtualViewportHeight);
8240
+ if (update) {
8241
+ this._applyGuardedWindowUpdate(update, this._guardedVirtualOverscan);
8242
+ }
8243
+ else {
8244
+ this._guardedVirtualWindow = null;
8245
+ }
8246
+ }
8247
+ if (this._guardedVirtualWindow) {
8248
+ this._renderPlan = this._createVirtualRenderPlan(this._guardedVirtualWindow.startIndex, this._guardedVirtualWindow.endIndex);
8249
+ }
8250
+ const filteredIndices = this._renderPlan.filteredIndices;
8251
+ this._refreshVirtualizationScope(filteredIndicesForScope);
8252
+ this._appendGuardedTopSpacer();
6458
8253
  if (filteredIndices.length === 0 && !this._state.isBusy) {
6459
8254
  const empty = document.createElement('div');
6460
8255
  empty.setAttribute('part', 'no-results');
@@ -6468,7 +8263,8 @@ class EnhancedSelect extends HTMLElement {
6468
8263
  this._optionsContainer.appendChild(empty);
6469
8264
  }
6470
8265
  else {
6471
- const shouldIncrementalRender = this._config.virtualize !== false
8266
+ const shouldIncrementalRender = !this._guardedVirtualizer
8267
+ && this._config.virtualize !== false
6472
8268
  && this._state.groupedItems.length === 0
6473
8269
  && filteredIndices.length > 300;
6474
8270
  if (shouldIncrementalRender) {
@@ -6476,7 +8272,7 @@ class EnhancedSelect extends HTMLElement {
6476
8272
  let cursor = 0;
6477
8273
  let maxRenderTarget = 0;
6478
8274
  if (this._state.selectedIndices.size > 0 && this._config.scrollToSelected.enabled) {
6479
- const indices = Array.from(this._state.selectedIndices).sort((a, b) => a - b);
8275
+ const indices = Array.from(this._state.selectedIndices).filter((index) => index >= 0).sort((a, b) => a - b);
6480
8276
  const targetIndex = this._config.scrollToSelected.multiSelectTarget === 'first' ? indices[0] : indices[indices.length - 1];
6481
8277
  const filteredPos = filteredIndices.indexOf(targetIndex);
6482
8278
  if (filteredPos !== -1) {
@@ -6494,7 +8290,11 @@ class EnhancedSelect extends HTMLElement {
6494
8290
  const item = this._state.loadedItems[itemIndex];
6495
8291
  this._renderSingleOption(item, itemIndex, getValue, getLabel, fragment);
6496
8292
  }
8293
+ const renderedTargets = Array.from(fragment.children);
6497
8294
  this._optionsContainer.appendChild(fragment);
8295
+ this._appendMountedVirtualizationTargets(renderedTargets);
8296
+ this._syncRenderedOptionAccessibility();
8297
+ this._syncLegacyActiveAria();
6498
8298
  if (cursor < filteredIndices.length) {
6499
8299
  this._requestLifecycleFrame(renderChunk);
6500
8300
  }
@@ -6515,7 +8315,9 @@ class EnhancedSelect extends HTMLElement {
6515
8315
  this._renderSingleOption(item, itemIndex, getValue, getLabel);
6516
8316
  });
6517
8317
  }
8318
+ this._appendGuardedBottomSpacer();
6518
8319
  }
8320
+ this._refreshMountedVirtualizationScope();
6519
8321
  // Append Busy Indicator if busy
6520
8322
  if (this._state.isBusy && this._config.busyBucket.enabled) {
6521
8323
  const busyBucket = document.createElement('div');
@@ -6537,8 +8339,23 @@ class EnhancedSelect extends HTMLElement {
6537
8339
  else if ((this._config.loadMore.enabled || this._config.infiniteScroll.enabled) && this._state.loadedItems.length > 0) {
6538
8340
  this._addLoadMoreTrigger();
6539
8341
  }
8342
+ // Rebuilding the list temporarily removes its spacer geometry. Browsers
8343
+ // clamp scrollTop during that interval, so restore the logical position
8344
+ // only after the new top/bottom spacers and mounted rows are present.
8345
+ if (guardedScrollTopToRestore !== null) {
8346
+ this._optionsContainer.scrollTop = guardedScrollTopToRestore;
8347
+ }
8348
+ this._syncRenderedOptionAccessibility();
8349
+ this._syncLegacyActiveAria();
8350
+ this._syncGuardedOptionResizeTargets();
6540
8351
  this._finalizePerfMarks();
6541
8352
  }
8353
+ _unobserveGuardedOptionResizeTargets() {
8354
+ for (const option of this._guardedObservedOptions) {
8355
+ this._guardedOptionResizeObserver?.unobserve(option);
8356
+ }
8357
+ this._guardedObservedOptions.clear();
8358
+ }
6542
8359
  _renderSingleOption(item, index, getValue, getLabel, targetContainer = this._optionsContainer) {
6543
8360
  const isSelected = this._state.selectedIndices.has(index);
6544
8361
  const isDisabled = Boolean(item?.disabled);
@@ -6713,16 +8530,18 @@ class EnhancedSelect extends HTMLElement {
6713
8530
  if (meta.value != null) {
6714
8531
  optionEl.dataset.smValue = String(meta.value);
6715
8532
  }
6716
- optionEl.id = optionEl.id || meta.id;
6717
- if (!optionEl.getAttribute('role')) {
6718
- optionEl.setAttribute('role', 'option');
8533
+ else {
8534
+ delete optionEl.dataset.smValue;
6719
8535
  }
6720
- optionEl.setAttribute('aria-selected', String(meta.selected));
6721
- if (meta.disabled && !meta.disabledBehavior.selectable) {
6722
- optionEl.setAttribute('aria-disabled', 'true');
8536
+ // Refresh component-generated IDs when a renderer reuses an option node,
8537
+ // while preserving an ID that the renderer supplied itself.
8538
+ const previousNormalizedId = this._customOptionNormalizedIds.get(optionEl);
8539
+ if (!optionEl.id || (previousNormalizedId !== undefined && optionEl.id === previousNormalizedId)) {
8540
+ optionEl.id = meta.id;
8541
+ this._customOptionNormalizedIds.set(optionEl, meta.id);
6723
8542
  }
6724
8543
  else {
6725
- optionEl.removeAttribute('aria-disabled');
8544
+ this._customOptionNormalizedIds.delete(optionEl);
6726
8545
  }
6727
8546
  if (!optionEl.hasAttribute('tabindex')) {
6728
8547
  optionEl.tabIndex = -1;
@@ -7805,5 +9624,5 @@ function warnCSPViolation(feature, fallback) {
7805
9624
  }
7806
9625
  }
7807
9626
 
7808
- export { CSPFeatures, CustomOptionPool, DOMPool, EnhancedSelect, FenwickTree, NativeSelectElement, OptionRenderer, PerformanceTelemetry, SelectOption, Virtualizer, WorkerManager, applyClasses, applyDefaultTheme, arrayIncludesValue, arraysEqualByValue, configureSelect, containsSuspiciousPatterns, createElement, createRendererHelpers, createTextNode, defaultTheme, detectEnvironment, escapeAttribute, escapeHTML, getCustomProperty, getHTMLSanitizer, getTelemetry, getWorkerManager, hasOverflowHiddenAncestor, injectShadowStyles, measureAsync, measureSync, removeCustomProperty, renderTemplate, resetSelectConfig, sanitizeHTML, selectConfig, setCSSProperties, setCustomProperties, setHTMLSanitizer, setTextContent, shadowDOMStyles, toggleClass, validateTemplate, valuesEqual, warnCSPViolation };
9627
+ export { CSPFeatures, CustomOptionPool, DOMPool, DefaultSelectEffectRunner, EnhancedSelect, FenwickTree, NativeSelectElement, OptionRenderer, PerformanceTelemetry, SelectEngineBridge, SelectOption, Virtualizer, WorkerManager, applyClasses, applyDefaultTheme, applySelectionRequest, arrayIncludesValue, arraysEqualByValue, configureSelect, containsSuspiciousPatterns, createDefaultItemAdapter, createElement, createInitialSelectState, createItemRegistry, createRendererHelpers, createTextNode, defaultTheme, detectEnvironment, escapeAttribute, escapeHTML, getActiveKey, getCustomProperty, getDefaultDuplicateKeyPolicy, getHTMLSanitizer, getSelectedKeys, getTelemetry, getWorkerManager, hasOverflowHiddenAncestor, hasSelection, injectShadowStyles, isDisabled, isFocused, isOpen, isRegisteredKey, isSelected, measureAsync, measureSync, removeCustomProperty, renderTemplate, resetSelectConfig, sanitizeHTML, selectConfig, setCSSProperties, setCustomProperties, setHTMLSanitizer, setTextContent, shadowDOMStyles, toggleClass, transition, validateTemplate, valuesEqual, warnCSPViolation };
7809
9628
  //# sourceMappingURL=index.js.map