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