@smilodon/core 1.19.0 → 1.21.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.
package/dist/index.umd.js CHANGED
@@ -2078,6 +2078,123 @@
2078
2078
  customElements.define("smilodon-select", NativeSelectElement);
2079
2079
  }
2080
2080
 
2081
+ const SELECTED_OPTIONS_FIELDS = new Set(['placement', 'groupedPlacement']);
2082
+ const SCROLL_TO_SELECTED_FIELDS = new Set([
2083
+ 'enabled',
2084
+ 'multiSelectTarget',
2085
+ 'onOpen',
2086
+ 'behavior',
2087
+ 'block',
2088
+ ]);
2089
+ const placements = new Set(['original', 'selected-first']);
2090
+ const groupedPlacements = new Set(['within-group']);
2091
+ const scrollTargets = new Set(['first', 'last']);
2092
+ const openPolicies = new Set(['preserve', 'reveal', 'align']);
2093
+ const scrollBehaviors = new Set(['auto', 'instant', 'smooth']);
2094
+ const scrollBlocks = new Set(['start', 'center', 'end', 'nearest']);
2095
+ function asPlainRecord(value) {
2096
+ if (value === null || typeof value !== 'object' || Array.isArray(value))
2097
+ return null;
2098
+ const prototype = Object.getPrototypeOf(value);
2099
+ return prototype === Object.prototype || prototype === null ? value : null;
2100
+ }
2101
+ function unknownFieldIssues(record, allowed) {
2102
+ return Object.keys(record)
2103
+ .filter((key) => !allowed.has(key))
2104
+ .sort()
2105
+ .map((key) => ({
2106
+ path: key,
2107
+ code: 'unknown-field',
2108
+ message: `Unknown configuration field: ${key}.`,
2109
+ }));
2110
+ }
2111
+ function validateEnum(record, field, allowed, issues) {
2112
+ const value = record[field];
2113
+ if (value === undefined)
2114
+ return;
2115
+ if (typeof value !== 'string') {
2116
+ issues.push({ path: field, code: 'invalid-type', message: `${field} must be a string.` });
2117
+ }
2118
+ else if (!allowed.has(value)) {
2119
+ issues.push({ path: field, code: 'invalid-value', message: `${field} has an unsupported value.` });
2120
+ }
2121
+ }
2122
+ /** Validate a partial selected-options configuration update. */
2123
+ function validateSelectedOptionsConfig(candidate) {
2124
+ const record = asPlainRecord(candidate);
2125
+ if (!record) {
2126
+ return {
2127
+ valid: false,
2128
+ issues: [{ path: 'selectedOptions', code: 'invalid-type', message: 'selectedOptions must be a plain object.' }],
2129
+ };
2130
+ }
2131
+ const issues = unknownFieldIssues(record, SELECTED_OPTIONS_FIELDS);
2132
+ validateEnum(record, 'placement', placements, issues);
2133
+ validateEnum(record, 'groupedPlacement', groupedPlacements, issues);
2134
+ if (issues.length > 0)
2135
+ return { valid: false, issues };
2136
+ return {
2137
+ valid: true,
2138
+ value: {
2139
+ ...(record.placement === undefined ? {} : { placement: record.placement }),
2140
+ ...(record.groupedPlacement === undefined
2141
+ ? {}
2142
+ : { groupedPlacement: record.groupedPlacement }),
2143
+ },
2144
+ };
2145
+ }
2146
+ /** Validate a partial scroll-to-selected configuration update. */
2147
+ function validateScrollToSelectedConfig(candidate) {
2148
+ const record = asPlainRecord(candidate);
2149
+ if (!record) {
2150
+ return {
2151
+ valid: false,
2152
+ issues: [{ path: 'scrollToSelected', code: 'invalid-type', message: 'scrollToSelected must be a plain object.' }],
2153
+ };
2154
+ }
2155
+ const issues = unknownFieldIssues(record, SCROLL_TO_SELECTED_FIELDS);
2156
+ if (record.enabled !== undefined && typeof record.enabled !== 'boolean') {
2157
+ issues.push({ path: 'enabled', code: 'invalid-type', message: 'enabled must be a boolean.' });
2158
+ }
2159
+ validateEnum(record, 'multiSelectTarget', scrollTargets, issues);
2160
+ validateEnum(record, 'onOpen', openPolicies, issues);
2161
+ validateEnum(record, 'behavior', scrollBehaviors, issues);
2162
+ validateEnum(record, 'block', scrollBlocks, issues);
2163
+ if (issues.length > 0)
2164
+ return { valid: false, issues };
2165
+ return {
2166
+ valid: true,
2167
+ value: {
2168
+ ...(record.enabled === undefined ? {} : { enabled: record.enabled }),
2169
+ ...(record.multiSelectTarget === undefined
2170
+ ? {}
2171
+ : { multiSelectTarget: record.multiSelectTarget }),
2172
+ ...(record.onOpen === undefined ? {} : { onOpen: record.onOpen }),
2173
+ ...(record.behavior === undefined ? {} : { behavior: record.behavior }),
2174
+ ...(record.block === undefined ? {} : { block: record.block }),
2175
+ },
2176
+ };
2177
+ }
2178
+ /** Validate and copy only the new public configuration sections. */
2179
+ function validateSelectedOptionsConfigUpdate(config) {
2180
+ const result = { ...config };
2181
+ if (config.selectedOptions !== undefined) {
2182
+ const validation = validateSelectedOptionsConfig(config.selectedOptions);
2183
+ if (validation.valid)
2184
+ result.selectedOptions = validation.value;
2185
+ else
2186
+ delete result.selectedOptions;
2187
+ }
2188
+ if (config.scrollToSelected !== undefined) {
2189
+ const validation = validateScrollToSelectedConfig(config.scrollToSelected);
2190
+ if (validation.valid)
2191
+ result.scrollToSelected = validation.value;
2192
+ else
2193
+ delete result.scrollToSelected;
2194
+ }
2195
+ return result;
2196
+ }
2197
+
2081
2198
  /**
2082
2199
  * Global Configuration System for Select Components
2083
2200
  * Allows users to define default behaviors that can be overridden at component level
@@ -2117,9 +2234,14 @@
2117
2234
  scrollToSelected: {
2118
2235
  enabled: true,
2119
2236
  multiSelectTarget: 'first',
2237
+ onOpen: 'reveal',
2120
2238
  behavior: 'smooth',
2121
2239
  block: 'nearest',
2122
2240
  },
2241
+ selectedOptions: {
2242
+ placement: 'original',
2243
+ groupedPlacement: 'within-group',
2244
+ },
2123
2245
  loadMore: {
2124
2246
  enabled: false,
2125
2247
  itemsPerLoad: 3,
@@ -2202,7 +2324,8 @@
2202
2324
  * Update global configuration (deep merge)
2203
2325
  */
2204
2326
  updateConfig(updates) {
2205
- this.config = this.deepMerge(this.config, updates);
2327
+ const acceptedUpdates = validateSelectedOptionsConfigUpdate(updates);
2328
+ this.config = this.deepMerge(this.config, acceptedUpdates);
2206
2329
  }
2207
2330
  /**
2208
2331
  * Reset to default configuration
@@ -3163,6 +3286,94 @@
3163
3286
  return true;
3164
3287
  }
3165
3288
 
3289
+ function createVisualNavigationModel(orderedKeys, isSelectable) {
3290
+ const ordered = [...orderedKeys];
3291
+ const selectableKeys = [];
3292
+ const positionByKey = new Map();
3293
+ const selectablePositionByKey = new Map();
3294
+ ordered.forEach((key, position) => {
3295
+ positionByKey.set(key, position);
3296
+ if (isSelectable(key)) {
3297
+ selectablePositionByKey.set(key, selectableKeys.length);
3298
+ selectableKeys.push(key);
3299
+ }
3300
+ });
3301
+ return { orderedKeys: ordered, selectableKeys, positionByKey, selectablePositionByKey };
3302
+ }
3303
+ /** Resolve a clamped keyboard movement in visual order. */
3304
+ function resolveVisualMovement(model, currentKey, delta) {
3305
+ const { selectableKeys, selectablePositionByKey } = model;
3306
+ if (selectableKeys.length === 0)
3307
+ return null;
3308
+ const currentPosition = currentKey === null ? undefined : selectablePositionByKey.get(currentKey);
3309
+ const basePosition = currentPosition ?? (delta >= 0 ? -1 : selectableKeys.length);
3310
+ const nextPosition = Math.max(0, Math.min(selectableKeys.length - 1, basePosition + delta));
3311
+ return selectableKeys[nextPosition] ?? null;
3312
+ }
3313
+ function resolveVisualBoundary(model, boundary) {
3314
+ return boundary === 'first'
3315
+ ? model.selectableKeys[0] ?? null
3316
+ : model.selectableKeys[model.selectableKeys.length - 1] ?? null;
3317
+ }
3318
+ /** Return selectable keys in the inclusive visual interval between two keys. */
3319
+ function resolveVisualRange(model, startKey, endKey) {
3320
+ const startPosition = model.positionByKey.get(startKey);
3321
+ const endPosition = model.positionByKey.get(endKey);
3322
+ if (startPosition === undefined || endPosition === undefined)
3323
+ return [];
3324
+ const low = Math.min(startPosition, endPosition);
3325
+ const high = Math.max(startPosition, endPosition);
3326
+ const selectable = new Set(model.selectableKeys);
3327
+ return model.orderedKeys.slice(low, high + 1).filter((key) => selectable.has(key));
3328
+ }
3329
+
3330
+ /**
3331
+ * Return a presentation-only ordering for option keys.
3332
+ *
3333
+ * The source array and selection set are never mutated. Callers remain
3334
+ * responsible for retaining the returned order as the displayed ordering for
3335
+ * the relevant render/open transaction.
3336
+ */
3337
+ function projectSelectedOptionKeys(orderedKeys, selectedKeys, placement) {
3338
+ const selected = [];
3339
+ const unselected = [];
3340
+ for (const key of orderedKeys) {
3341
+ (selectedKeys.has(key) ? selected : unselected).push(key);
3342
+ }
3343
+ return [...selected, ...unselected];
3344
+ }
3345
+ /**
3346
+ * Stably partitions selected keys to the front of each group independently.
3347
+ * Group order, identity, membership, and the source arrays are preserved.
3348
+ */
3349
+ function projectSelectedOptionGroups(groups, selectedKeys) {
3350
+ return groups.map(({ groupIdentity, orderedKeys }) => {
3351
+ const selected = [];
3352
+ const unselected = [];
3353
+ for (const key of orderedKeys) {
3354
+ (selectedKeys.has(key) ? selected : unselected).push(key);
3355
+ }
3356
+ return { groupIdentity, orderedKeys: [...selected, ...unselected] };
3357
+ });
3358
+ }
3359
+
3360
+ /** Resolve the selected key at an edge of the displayed eligible ordering. */
3361
+ function resolveSelectedTargetKey(orderedKeys, selectedKeys, target) {
3362
+ if (target === 'first') {
3363
+ for (const key of orderedKeys) {
3364
+ if (selectedKeys.has(key))
3365
+ return key;
3366
+ }
3367
+ return null;
3368
+ }
3369
+ for (let index = orderedKeys.length - 1; index >= 0; index -= 1) {
3370
+ const key = orderedKeys[index];
3371
+ if (selectedKeys.has(key))
3372
+ return key;
3373
+ }
3374
+ return null;
3375
+ }
3376
+
3166
3377
  /**
3167
3378
  * DOM-independent coordinator for the opt-in acknowledged data-loading
3168
3379
  * protocol. This module is intentionally not re-exported from the package
@@ -4238,6 +4449,15 @@
4238
4449
  super();
4239
4450
  this._dataLoadingConfig = { ...LEGACY_DATA_LOADING_CONFIG };
4240
4451
  this._hasLastInvalidDataLoadingCandidate = false;
4452
+ this._selectedLabelTooltipTrigger = null;
4453
+ this._selectedLabelTooltipPointerTrigger = null;
4454
+ this._selectedLabelTooltipFocusTrigger = null;
4455
+ this._selectedLabelTooltipPointerInside = false;
4456
+ this._selectedLabelTooltipDismissedTrigger = null;
4457
+ this._selectedLabelTooltipHideTimer = null;
4458
+ this._selectedLabelTooltipResizeObserver = null;
4459
+ this._selectedLabelTooltipMeasureFrame = null;
4460
+ this._selectedLabelKeys = new WeakMap();
4241
4461
  this._busyPresentationVisible = false;
4242
4462
  this._busyPresentationStartedAt = null;
4243
4463
  this._busyPresentationGeneration = 0;
@@ -4257,8 +4477,27 @@
4257
4477
  filteredIndices: [],
4258
4478
  filteredKeys: [],
4259
4479
  intendedRenderKeys: [],
4480
+ displayIndexByKey: new Map(),
4481
+ sourceIndexByKey: new Map(),
4260
4482
  filteredIndexByKey: new Map(),
4483
+ groupedPresentation: [],
4484
+ };
4485
+ // Presentation policy and membership are snapshotted when the dropdown opens
4486
+ // so selection/config updates cannot reorder an active list.
4487
+ this._selectedOptionsSelectionAtOpen = null;
4488
+ this._selectedOptionsConfigAtOpen = {
4489
+ placement: 'original',
4490
+ groupedPlacement: 'within-group',
4491
+ };
4492
+ this._scrollToSelectedConfigAtOpen = {
4493
+ enabled: true,
4494
+ multiSelectTarget: 'first',
4495
+ onOpen: 'reveal',
4496
+ behavior: 'smooth',
4497
+ block: 'nearest',
4261
4498
  };
4499
+ this._closedOptionsViewportAnchor = null;
4500
+ this._openOptionsViewportAnchor = null;
4262
4501
  this._emptyStateContext = null;
4263
4502
  // Null keeps the public/default renderer on its legacy full path. This
4264
4503
  // private state is only used by guarded virtualization integration.
@@ -4315,9 +4554,12 @@
4315
4554
  this._boundArrowClick = null;
4316
4555
  this._pendingFirstRenderMark = false;
4317
4556
  this._pendingSearchRenderMark = false;
4318
- this._rangeAnchorIndex = null;
4557
+ this._rangeAnchorKey = null;
4319
4558
  /** Chip identity is tracked independently of dropdown option positions. */
4320
4559
  this._lastRenderedChipKeys = null;
4560
+ /** Stable presentation nodes keyed by the engine's selected-item identity. */
4561
+ this._chipElements = new Map();
4562
+ this._chipExitStates = new Map();
4321
4563
  this._latestChipScrollGeneration = 0;
4322
4564
  this._latestChipScrollFrame = null;
4323
4565
  this._customOptionBoundElements = new WeakSet();
@@ -4333,6 +4575,9 @@
4333
4575
  this._lifecycleTimers = new Set();
4334
4576
  this._lifecycleRafs = new Set();
4335
4577
  this._keyboardActiveChangeGeneration = 0;
4578
+ /** Invalidates selected-option positioning scheduled by an earlier opening. */
4579
+ this._openSelectedScrollGeneration = 0;
4580
+ this._openSelectedScrollCleanup = null;
4336
4581
  this._tracking = { events: [], styles: [], limitations: [] };
4337
4582
  this._suppressBlurClose = false;
4338
4583
  this._renderCycleId = 0;
@@ -4400,6 +4645,14 @@
4400
4645
  this._handleClose('outside-pointer');
4401
4646
  }
4402
4647
  };
4648
+ this._scheduleSelectedLabelTooltipMeasure = () => {
4649
+ if (this._selectedLabelTooltipMeasureFrame !== null || !this.isConnected)
4650
+ return;
4651
+ this._selectedLabelTooltipMeasureFrame = this._requestLifecycleFrame(() => {
4652
+ this._selectedLabelTooltipMeasureFrame = null;
4653
+ this._refreshSelectedLabelTooltipMeasurements();
4654
+ });
4655
+ };
4403
4656
  this._shadow = this.attachShadow({ mode: 'open' });
4404
4657
  this._uniqueId = `enhanced-select-${Math.random().toString(36).substr(2, 9)}`;
4405
4658
  this._rendererHelpers = this._buildRendererHelpers();
@@ -4434,6 +4687,7 @@
4434
4687
  this._inputContainer = this._createInputContainer();
4435
4688
  this._inputContent = this._createInputContent();
4436
4689
  this._input = this._createInput();
4690
+ this._selectedLabelTooltip = this._createSelectedLabelTooltip();
4437
4691
  this._arrowContainer = this._createArrowContainer();
4438
4692
  this._clearControl = this._createClearControl();
4439
4693
  this._dropdown = this._createDropdown();
@@ -4459,9 +4713,19 @@
4459
4713
  this._runEngineEffects(this._engine.dispatch({ type: 'DISABLED_CHANGED', disabled: !this._config.enabled }));
4460
4714
  this._connectionController?.abort();
4461
4715
  this._connectionController = new AbortController();
4716
+ this._observeSelectedLabelTooltipTargets();
4462
4717
  document.addEventListener('pointerdown', this._onDocumentPointerDown, {
4463
4718
  signal: this._connectionController.signal,
4464
4719
  });
4720
+ window.addEventListener('resize', this._scheduleSelectedLabelTooltipMeasure, {
4721
+ signal: this._connectionController.signal,
4722
+ passive: true,
4723
+ });
4724
+ window.addEventListener('scroll', this._scheduleSelectedLabelTooltipMeasure, {
4725
+ signal: this._connectionController.signal,
4726
+ passive: true,
4727
+ capture: true,
4728
+ });
4465
4729
  // WORKAROUND: Force display style on host element for Angular compatibility
4466
4730
  // Angular's rendering seems to not apply :host styles correctly in some cases
4467
4731
  // Must be done in connectedCallback when element is attached to DOM
@@ -4510,7 +4774,9 @@
4510
4774
  this._syncListboxAccessibility();
4511
4775
  }
4512
4776
  disconnectedCallback() {
4777
+ this._cancelOpenSelectedScroll();
4513
4778
  this._cancelLatestChipScroll();
4779
+ this._clearChipPresentation();
4514
4780
  this._cancelBusyPresentation();
4515
4781
  if (this._dataRequestCoordinator) {
4516
4782
  const actions = this._dataRequestCoordinator.disconnect();
@@ -4533,6 +4799,13 @@
4533
4799
  this._runEngineEffects(this._engine.dispatch({ type: 'DISCONNECT' }));
4534
4800
  this._connectionController?.abort();
4535
4801
  this._connectionController = undefined;
4802
+ this._hideSelectedLabelTooltip(true);
4803
+ this._selectedLabelTooltipResizeObserver?.disconnect();
4804
+ this._selectedLabelTooltipResizeObserver = null;
4805
+ if (this._selectedLabelTooltipMeasureFrame !== null) {
4806
+ cancelAnimationFrame(this._selectedLabelTooltipMeasureFrame);
4807
+ this._selectedLabelTooltipMeasureFrame = null;
4808
+ }
4536
4809
  this._asyncGeneration += 1;
4537
4810
  this._cancelGuardedVirtualWindowUpdate();
4538
4811
  this._clearLifecycleTasks();
@@ -5096,12 +5369,12 @@
5096
5369
  duplicateKeyPolicy: this._getDuplicateKeyPolicy(),
5097
5370
  });
5098
5371
  const activeKey = this._engine.state.activeKey;
5099
- const anchorKey = this._rangeAnchorIndex === null ? undefined : this._itemRegistry.indexToKey.get(this._rangeAnchorIndex);
5372
+ const anchorKey = this._rangeAnchorKey;
5100
5373
  this._itemRegistry = registry;
5101
5374
  this._state.loadedItems = items;
5102
5375
  this._registryItemsRef = items;
5103
5376
  const disabledKeys = this._getBlockedDisabledKeys();
5104
- this._rangeAnchorIndex = anchorKey === undefined ? null : registry.keyToIndex.get(anchorKey) ?? null;
5377
+ this._rangeAnchorKey = anchorKey !== null && registry.keyToRecord.has(anchorKey) ? anchorKey : null;
5105
5378
  this._engine.dispatch({
5106
5379
  type: 'ITEMS_REGISTERED',
5107
5380
  keys: registry.records.map((record) => record.key),
@@ -5684,6 +5957,14 @@
5684
5957
  input.setAttribute('aria-haspopup', 'listbox');
5685
5958
  return input;
5686
5959
  }
5960
+ _createSelectedLabelTooltip() {
5961
+ const tooltip = document.createElement('div');
5962
+ tooltip.id = `${this._uniqueId}-selected-label-tooltip`;
5963
+ tooltip.className = 'selected-label-tooltip';
5964
+ tooltip.setAttribute('role', 'tooltip');
5965
+ tooltip.hidden = true;
5966
+ return tooltip;
5967
+ }
5687
5968
  _createDropdown() {
5688
5969
  const dropdown = document.createElement('div');
5689
5970
  dropdown.className = 'select-dropdown';
@@ -5778,6 +6059,7 @@
5778
6059
  if (this._errorDescription) {
5779
6060
  this._shadow.appendChild(this._errorDescription);
5780
6061
  }
6062
+ this._shadow.appendChild(this._selectedLabelTooltip);
5781
6063
  // Set ARIA relationships
5782
6064
  const listboxId = `${this._uniqueId}-listbox`;
5783
6065
  this._dropdown.id = listboxId;
@@ -5792,6 +6074,12 @@
5792
6074
  ELEGANT SELECT COMPONENT — Refined Design System
5793
6075
  Formal aesthetics with sophisticated microinteractions
5794
6076
  ═══════════════════════════════════════════════════════════════════════════ */
6077
+
6078
+ @layer smilodon-input-content-fallback {
6079
+ .input-container.input-container--multi:not([data-multi-scroll-mode="horizontal"]) .input-content {
6080
+ padding-inline-end: var(--select-multi-input-end-gap, 12px);
6081
+ }
6082
+ }
5795
6083
 
5796
6084
  :host {
5797
6085
  --select-primary: #1a1a2e;
@@ -5816,6 +6104,10 @@
5816
6104
  --select-transition-smooth: 250ms cubic-bezier(0.4, 0, 0.2, 1);
5817
6105
  --select-transition-bounce: 350ms cubic-bezier(0.34, 1.56, 0.64, 1);
5818
6106
  --select-badge-animation: badgeEnter 300ms cubic-bezier(0.34, 1.56, 0.64, 1) forwards;
6107
+ --select-badge-exit-from-opacity: 1;
6108
+ --select-badge-exit-from-transform: scale(1) translateY(0);
6109
+ --select-badge-exit-to-opacity: 0;
6110
+ --select-badge-exit-to-transform: scale(0.8) translateY(-4px);
5819
6111
  --select-badge-enter-from-opacity: 0;
5820
6112
  --select-badge-enter-from-transform: scale(0.8) translateY(-4px);
5821
6113
  --select-badge-enter-to-opacity: 1;
@@ -6017,7 +6309,13 @@
6017
6309
  transform var(--select-transition-bounce),
6018
6310
  box-shadow var(--select-transition-fast),
6019
6311
  background var(--select-transition-fast);
6020
- animation: var(--select-badge-animation);
6312
+ animation: var(--select-badge-enter-animation, var(--select-badge-animation));
6313
+ }
6314
+
6315
+ .selection-badge[data-motion="exiting"] {
6316
+ animation: var(--select-badge-exit-animation, none);
6317
+ pointer-events: none;
6318
+ transition: none;
6021
6319
  }
6022
6320
 
6023
6321
  @keyframes badgeEnter {
@@ -6030,6 +6328,17 @@
6030
6328
  transform: var(--select-badge-enter-to-transform);
6031
6329
  }
6032
6330
  }
6331
+
6332
+ @keyframes badgeExit {
6333
+ 0% {
6334
+ opacity: var(--select-badge-exit-from-opacity, 1);
6335
+ transform: var(--select-badge-exit-from-transform, scale(1) translateY(0));
6336
+ }
6337
+ 100% {
6338
+ opacity: var(--select-badge-exit-to-opacity, 0);
6339
+ transform: var(--select-badge-exit-to-transform, scale(0.8) translateY(-4px));
6340
+ }
6341
+ }
6033
6342
 
6034
6343
  .selection-badge:hover {
6035
6344
  background: var(--select-badge-hover-bg, var(--select-badge-bg, linear-gradient(135deg, var(--select-accent) 0%, var(--select-primary-light) 100%)));
@@ -6142,6 +6451,29 @@
6142
6451
  position: relative;
6143
6452
  width: 100%;
6144
6453
  }
6454
+
6455
+ .selected-label-tooltip {
6456
+ position: fixed;
6457
+ z-index: 2147483000;
6458
+ box-sizing: border-box;
6459
+ width: max-content;
6460
+ max-width: min(24rem, calc(100vw - 16px));
6461
+ padding: 8px 10px;
6462
+ border: 1px solid rgba(255, 255, 255, 0.18);
6463
+ border-radius: 6px;
6464
+ background: #18202e;
6465
+ color: #fff;
6466
+ box-shadow: 0 4px 16px rgba(0, 0, 0, 0.24);
6467
+ font: 500 13px/1.45 system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
6468
+ white-space: normal;
6469
+ overflow-wrap: anywhere;
6470
+ pointer-events: auto;
6471
+ direction: inherit;
6472
+ }
6473
+
6474
+ .selected-label-tooltip[hidden] {
6475
+ display: none;
6476
+ }
6145
6477
 
6146
6478
  .input-container {
6147
6479
  position: relative;
@@ -6190,6 +6522,7 @@
6190
6522
  overflow-y: var(--select-input-overflow-y, hidden);
6191
6523
  scrollbar-width: thin;
6192
6524
  box-sizing: border-box;
6525
+ padding: var(--select-input-content-padding, revert-layer);
6193
6526
  }
6194
6527
 
6195
6528
  .input-container:hover {
@@ -6215,7 +6548,6 @@
6215
6548
  align-content: var(--select-multi-input-align-content, var(--select-multi-input-align-content-config, flex-start));
6216
6549
  overflow-x: var(--select-multi-input-overflow-x, var(--select-multi-input-overflow-x-config, hidden));
6217
6550
  overflow-y: var(--select-multi-input-overflow-y, var(--select-multi-input-overflow-y-config, auto));
6218
- padding-inline-end: var(--select-multi-input-end-gap, 12px);
6219
6551
  }
6220
6552
 
6221
6553
  .input-container.input-container--multi .input-content .selection-badge {
@@ -6253,7 +6585,7 @@
6253
6585
  overflow-y: hidden;
6254
6586
  overscroll-behavior-x: contain;
6255
6587
  overscroll-behavior-y: none;
6256
- padding-inline-end: 0;
6588
+ padding: var(--select-input-content-padding, 0);
6257
6589
  scroll-padding-inline-end: var(--select-multi-action-area-width, var(--select-arrow-width, 42px));
6258
6590
  }
6259
6591
 
@@ -6356,6 +6688,7 @@
6356
6688
  bottom: 0;
6357
6689
  width: var(--select-arrow-width, var(--select-arrow-size, 42px));
6358
6690
  height: var(--select-arrow-height, var(--select-arrow-size, auto));
6691
+ padding: var(--select-dropdown-arrow-container-padding, 0);
6359
6692
  display: flex;
6360
6693
  align-items: center;
6361
6694
  justify-content: center;
@@ -7235,7 +7568,25 @@
7235
7568
  this._shadow.appendChild(style);
7236
7569
  }
7237
7570
  }
7571
+ _isArrowOrClearControlEvent(event) {
7572
+ const path = event.composedPath();
7573
+ return ((this._arrowContainer != null && path.includes(this._arrowContainer)) ||
7574
+ (this._clearControl != null && path.includes(this._clearControl)));
7575
+ }
7238
7576
  _attachEventListeners() {
7577
+ this._shadow.addEventListener('pointerover', (event) => this._handleSelectedLabelPointerOver(event));
7578
+ this._shadow.addEventListener('pointerout', (event) => this._handleSelectedLabelPointerOut(event));
7579
+ this._shadow.addEventListener('focusin', (event) => this._handleSelectedLabelFocusIn(event));
7580
+ this._shadow.addEventListener('focusout', (event) => this._handleSelectedLabelFocusOut(event));
7581
+ this._shadow.addEventListener('keydown', (event) => {
7582
+ const keyboardEvent = event;
7583
+ if (keyboardEvent.key !== 'Escape' || this._selectedLabelTooltip.hidden)
7584
+ return;
7585
+ keyboardEvent.preventDefault();
7586
+ keyboardEvent.stopPropagation();
7587
+ this._dismissSelectedLabelTooltip();
7588
+ });
7589
+ this._inputContent.addEventListener('scroll', this._scheduleSelectedLabelTooltipMeasure, { passive: true });
7239
7590
  // Arrow click handler
7240
7591
  if (this._arrowContainer) {
7241
7592
  this._boundArrowClick = (e) => {
@@ -7271,13 +7622,11 @@
7271
7622
  // Prevent propagation to document click listener but do NOT preventDefault.
7272
7623
  // Allow default so browser events (click) on newly opened options still fire.
7273
7624
  // e.stopPropagation(); // BUG: By stopping propagation here, the document click listener doesn't see it, which is fine for not closing it. But be very careful.
7274
- const target = e.target;
7275
7625
  if (!this._config.enabled)
7276
7626
  return;
7277
- if (target && target.closest('.dropdown-arrow-container'))
7278
- return;
7279
- if (target && target.closest('.clear-control-button'))
7627
+ if (this._isArrowOrClearControlEvent(e))
7280
7628
  return;
7629
+ const target = e.target;
7281
7630
  if (this._isPointerOnInputScrollbar(e)) {
7282
7631
  this._suppressNextOpenClick = true;
7283
7632
  return;
@@ -7324,7 +7673,6 @@
7324
7673
  }
7325
7674
  });
7326
7675
  this._inputContainer.addEventListener('click', (e) => {
7327
- const target = e.target;
7328
7676
  const isHorizontalMultiMode = this._config.selection.mode === 'multi'
7329
7677
  && (this._config.multiSelectDisplay?.mode ?? 'wrap') === 'horizontal';
7330
7678
  if (!this._config.enabled || !isHorizontalMultiMode) {
@@ -7332,7 +7680,7 @@
7332
7680
  this._multiScrollDrag.moved = false;
7333
7681
  return;
7334
7682
  }
7335
- if (target && target.closest('.dropdown-arrow-container, .clear-control-button')) {
7683
+ if (this._isArrowOrClearControlEvent(e)) {
7336
7684
  this._suppressNextOpenClick = false;
7337
7685
  this._multiScrollDrag.moved = false;
7338
7686
  return;
@@ -7407,6 +7755,10 @@
7407
7755
  if (!this._config.searchable)
7408
7756
  return;
7409
7757
  const query = e.target.value;
7758
+ if (this._selectedLabelTooltipTrigger === this._input
7759
+ && this._getSelectedLabelForTrigger(this._input) === null) {
7760
+ this._hideSelectedLabelTooltip();
7761
+ }
7410
7762
  this._handleSearch(query);
7411
7763
  });
7412
7764
  // If the user presses down inside the options container we should
@@ -7569,6 +7921,286 @@
7569
7921
  return index === undefined ? null : this._getOptionElementByIndex(index);
7570
7922
  },
7571
7923
  });
7924
+ this._syncSelectedLabelTooltipDescription();
7925
+ }
7926
+ _selectedLabelTriggerFromTarget(target) {
7927
+ if (!(target instanceof HTMLElement))
7928
+ return null;
7929
+ if (target === this._input)
7930
+ return target;
7931
+ const label = target.closest('.selection-badge-label');
7932
+ return label && this._inputContent.contains(label) ? label : null;
7933
+ }
7934
+ _getSelectedLabelForTrigger(trigger) {
7935
+ const entries = this._getSelectedEntries();
7936
+ if (trigger === this._input) {
7937
+ if (this._config.selection.mode !== 'single' || this._state.searchQuery.length > 0)
7938
+ return null;
7939
+ const item = entries[0]?.item;
7940
+ if (item === undefined)
7941
+ return null;
7942
+ const label = this._getItemLabel(item);
7943
+ return this._input.value === label ? label : null;
7944
+ }
7945
+ if (!trigger.classList.contains('selection-badge-label'))
7946
+ return null;
7947
+ const key = this._selectedLabelKeys.get(trigger);
7948
+ if (key === undefined)
7949
+ return null;
7950
+ const entry = entries.find((candidate) => candidate.key === key);
7951
+ if (!entry)
7952
+ return null;
7953
+ const label = this._getItemLabel(entry.item);
7954
+ return trigger.textContent === label ? label : null;
7955
+ }
7956
+ _isSelectedLabelTruncated(trigger) {
7957
+ if (!trigger.isConnected)
7958
+ return false;
7959
+ return trigger.clientWidth > 0 && trigger.scrollWidth > trigger.clientWidth + 1;
7960
+ }
7961
+ _handleSelectedLabelPointerOver(event) {
7962
+ const target = event.target;
7963
+ if (target?.closest('.selected-label-tooltip') === this._selectedLabelTooltip) {
7964
+ this._selectedLabelTooltipPointerInside = true;
7965
+ this._clearSelectedLabelTooltipHideTimer();
7966
+ return;
7967
+ }
7968
+ const trigger = this._selectedLabelTriggerFromTarget(target);
7969
+ if (!trigger || (event.relatedTarget instanceof Node && trigger.contains(event.relatedTarget)))
7970
+ return;
7971
+ this._selectedLabelTooltipPointerTrigger = trigger;
7972
+ this._selectedLabelTooltipDismissedTrigger = null;
7973
+ this._showSelectedLabelTooltip(trigger);
7974
+ }
7975
+ _handleSelectedLabelPointerOut(event) {
7976
+ const target = event.target;
7977
+ if (target === this._selectedLabelTooltip || this._selectedLabelTooltip.contains(target)) {
7978
+ if (event.relatedTarget instanceof Node && this._selectedLabelTooltip.contains(event.relatedTarget))
7979
+ return;
7980
+ this._selectedLabelTooltipPointerInside = false;
7981
+ this._scheduleSelectedLabelTooltipHide();
7982
+ return;
7983
+ }
7984
+ const trigger = this._selectedLabelTriggerFromTarget(target);
7985
+ if (!trigger || (event.relatedTarget instanceof Node && trigger.contains(event.relatedTarget)))
7986
+ return;
7987
+ if (this._selectedLabelTooltipPointerTrigger === trigger) {
7988
+ this._selectedLabelTooltipPointerTrigger = null;
7989
+ if (this._selectedLabelTooltipDismissedTrigger === trigger) {
7990
+ this._selectedLabelTooltipDismissedTrigger = null;
7991
+ }
7992
+ }
7993
+ if (event.relatedTarget === this._selectedLabelTooltip) {
7994
+ this._selectedLabelTooltipPointerInside = true;
7995
+ this._clearSelectedLabelTooltipHideTimer();
7996
+ return;
7997
+ }
7998
+ this._scheduleSelectedLabelTooltipHide();
7999
+ }
8000
+ _handleSelectedLabelFocusIn(event) {
8001
+ const trigger = this._selectedLabelTriggerFromTarget(event.target);
8002
+ if (!trigger)
8003
+ return;
8004
+ this._selectedLabelTooltipFocusTrigger = trigger;
8005
+ this._selectedLabelTooltipDismissedTrigger = null;
8006
+ this._showSelectedLabelTooltip(trigger);
8007
+ }
8008
+ _handleSelectedLabelFocusOut(event) {
8009
+ const trigger = this._selectedLabelTriggerFromTarget(event.target);
8010
+ if (!trigger || this._selectedLabelTooltipFocusTrigger !== trigger)
8011
+ return;
8012
+ this._selectedLabelTooltipFocusTrigger = null;
8013
+ if (this._selectedLabelTooltipDismissedTrigger === trigger) {
8014
+ this._selectedLabelTooltipDismissedTrigger = null;
8015
+ }
8016
+ this._scheduleSelectedLabelTooltipHide();
8017
+ }
8018
+ _showSelectedLabelTooltip(trigger) {
8019
+ if (this._selectedLabelTooltipDismissedTrigger === trigger)
8020
+ return;
8021
+ if (!trigger.isConnected || !this._isSelectedLabelVisibleInViewport(trigger)) {
8022
+ if (this._selectedLabelTooltipTrigger === trigger)
8023
+ this._hideSelectedLabelTooltip();
8024
+ return;
8025
+ }
8026
+ const label = this._getSelectedLabelForTrigger(trigger);
8027
+ if (label === null || !this._isSelectedLabelTruncated(trigger)) {
8028
+ if (trigger.classList.contains('selection-badge-label'))
8029
+ trigger.tabIndex = -1;
8030
+ if (this._selectedLabelTooltipTrigger === trigger)
8031
+ this._hideSelectedLabelTooltip();
8032
+ return;
8033
+ }
8034
+ if (trigger.classList.contains('selection-badge-label'))
8035
+ trigger.tabIndex = 0;
8036
+ if (this._selectedLabelTooltipTrigger !== trigger) {
8037
+ this._removeSelectedLabelTooltipDescription(this._selectedLabelTooltipTrigger);
8038
+ this._selectedLabelTooltipTrigger = trigger;
8039
+ }
8040
+ this._selectedLabelTooltip.textContent = label;
8041
+ this._selectedLabelTooltip.hidden = false;
8042
+ this._positionSelectedLabelTooltip(trigger);
8043
+ this._syncSelectedLabelTooltipDescription();
8044
+ this._clearSelectedLabelTooltipHideTimer();
8045
+ }
8046
+ _positionSelectedLabelTooltip(trigger) {
8047
+ if (this._selectedLabelTooltip.hidden || !trigger.isConnected)
8048
+ return;
8049
+ const triggerRect = trigger.getBoundingClientRect();
8050
+ const tooltip = this._selectedLabelTooltip;
8051
+ tooltip.style.maxWidth = `min(24rem, calc(100vw - 16px))`;
8052
+ tooltip.style.direction = getComputedStyle(trigger).direction;
8053
+ const tooltipRect = tooltip.getBoundingClientRect();
8054
+ const viewportWidth = document.documentElement.clientWidth || window.innerWidth;
8055
+ const viewportHeight = document.documentElement.clientHeight || window.innerHeight;
8056
+ const rtl = getComputedStyle(trigger).direction === 'rtl';
8057
+ const desiredLeft = rtl ? triggerRect.right - tooltipRect.width : triggerRect.left;
8058
+ const left = Math.max(8, Math.min(desiredLeft, viewportWidth - tooltipRect.width - 8));
8059
+ const above = triggerRect.top - tooltipRect.height - 6;
8060
+ const top = above >= 8 ? above : Math.min(triggerRect.bottom + 6, viewportHeight - tooltipRect.height - 8);
8061
+ tooltip.style.left = `${left}px`;
8062
+ tooltip.style.top = `${Math.max(8, top)}px`;
8063
+ }
8064
+ _syncSelectedLabelTooltipDescription() {
8065
+ const trigger = this._selectedLabelTooltipTrigger;
8066
+ this._removeSelectedLabelTooltipDescription(trigger);
8067
+ if (trigger && !this._selectedLabelTooltip.hidden) {
8068
+ const ids = new Set((trigger.getAttribute('aria-describedby') ?? '').split(/\s+/).filter(Boolean));
8069
+ ids.add(this._selectedLabelTooltip.id);
8070
+ trigger.setAttribute('aria-describedby', [...ids].join(' '));
8071
+ }
8072
+ }
8073
+ _removeSelectedLabelTooltipDescription(trigger) {
8074
+ if (!trigger)
8075
+ return;
8076
+ const ids = (trigger.getAttribute('aria-describedby') ?? '').split(/\s+/).filter(Boolean);
8077
+ const remaining = ids.filter((id) => id !== this._selectedLabelTooltip.id);
8078
+ if (remaining.length)
8079
+ trigger.setAttribute('aria-describedby', remaining.join(' '));
8080
+ else
8081
+ trigger.removeAttribute('aria-describedby');
8082
+ }
8083
+ _dismissSelectedLabelTooltip() {
8084
+ this._selectedLabelTooltipDismissedTrigger = this._selectedLabelTooltipFocusTrigger
8085
+ ?? this._selectedLabelTooltipTrigger
8086
+ ?? this._selectedLabelTooltipPointerTrigger;
8087
+ this._hideSelectedLabelTooltip();
8088
+ }
8089
+ _hideSelectedLabelTooltip(clearInteractionState = false) {
8090
+ this._clearSelectedLabelTooltipHideTimer();
8091
+ this._removeSelectedLabelTooltipDescription(this._selectedLabelTooltipTrigger);
8092
+ this._selectedLabelTooltipTrigger = null;
8093
+ this._selectedLabelTooltip.hidden = true;
8094
+ if (clearInteractionState) {
8095
+ this._selectedLabelTooltipPointerTrigger = null;
8096
+ this._selectedLabelTooltipFocusTrigger = null;
8097
+ this._selectedLabelTooltipPointerInside = false;
8098
+ this._selectedLabelTooltipDismissedTrigger = null;
8099
+ }
8100
+ }
8101
+ _clearSelectedLabelTooltipHideTimer() {
8102
+ if (this._selectedLabelTooltipHideTimer === null)
8103
+ return;
8104
+ window.clearTimeout(this._selectedLabelTooltipHideTimer);
8105
+ this._lifecycleTimers.delete(this._selectedLabelTooltipHideTimer);
8106
+ this._selectedLabelTooltipHideTimer = null;
8107
+ }
8108
+ _scheduleSelectedLabelTooltipHide() {
8109
+ this._clearSelectedLabelTooltipHideTimer();
8110
+ this._selectedLabelTooltipHideTimer = this._setLifecycleTimeout(() => {
8111
+ this._selectedLabelTooltipHideTimer = null;
8112
+ if (this._selectedLabelTooltipPointerInside)
8113
+ return;
8114
+ const trigger = this._selectedLabelTooltipTrigger;
8115
+ if (trigger && (this._selectedLabelTooltipFocusTrigger === trigger
8116
+ || this._selectedLabelTooltipPointerTrigger === trigger))
8117
+ return;
8118
+ const focusedTrigger = this._selectedLabelTooltipFocusTrigger;
8119
+ if (focusedTrigger && focusedTrigger !== this._selectedLabelTooltipDismissedTrigger
8120
+ && focusedTrigger.isConnected
8121
+ && this._isSelectedLabelVisibleInViewport(focusedTrigger)) {
8122
+ this._showSelectedLabelTooltip(focusedTrigger);
8123
+ return;
8124
+ }
8125
+ this._hideSelectedLabelTooltip();
8126
+ }, 180);
8127
+ }
8128
+ _isSelectedLabelVisibleInViewport(trigger) {
8129
+ if (!trigger.classList.contains('selection-badge-label'))
8130
+ return true;
8131
+ const viewport = this._inputContent;
8132
+ const triggerRect = trigger.getBoundingClientRect();
8133
+ const viewportRect = viewport.getBoundingClientRect();
8134
+ // DOM-only test environments do not calculate layout rectangles. Leave
8135
+ // visibility indeterminate there; browser measurement handles real layout.
8136
+ if (triggerRect.width === 0 && triggerRect.height === 0
8137
+ && viewportRect.width === 0 && viewportRect.height === 0)
8138
+ return true;
8139
+ const left = viewportRect.left + viewport.clientLeft;
8140
+ const top = viewportRect.top + viewport.clientTop;
8141
+ const right = left + viewport.clientWidth;
8142
+ const bottom = top + viewport.clientHeight;
8143
+ return triggerRect.right > left && triggerRect.left < right
8144
+ && triggerRect.bottom > top && triggerRect.top < bottom;
8145
+ }
8146
+ _observeSelectedLabelTooltipTargets() {
8147
+ if (typeof ResizeObserver === 'undefined')
8148
+ return;
8149
+ const hasSingleSelection = this._config.selection.mode === 'single'
8150
+ && this._getSelectedEntries().length > 0;
8151
+ const chipLabels = this._getActiveChipBadges()
8152
+ .map((badge) => badge.querySelector('.selection-badge-label'))
8153
+ .filter((label) => label !== null);
8154
+ if (!hasSingleSelection && chipLabels.length === 0) {
8155
+ this._selectedLabelTooltipResizeObserver?.disconnect();
8156
+ this._selectedLabelTooltipResizeObserver = null;
8157
+ return;
8158
+ }
8159
+ if (!this._selectedLabelTooltipResizeObserver) {
8160
+ this._selectedLabelTooltipResizeObserver = new ResizeObserver(() => this._scheduleSelectedLabelTooltipMeasure());
8161
+ }
8162
+ this._selectedLabelTooltipResizeObserver.disconnect();
8163
+ if (hasSingleSelection)
8164
+ this._selectedLabelTooltipResizeObserver.observe(this._input);
8165
+ chipLabels.forEach((label) => {
8166
+ this._selectedLabelTooltipResizeObserver?.observe(label);
8167
+ });
8168
+ }
8169
+ _refreshSelectedLabelTooltipMeasurements() {
8170
+ this._getActiveChipBadges().forEach((badge) => {
8171
+ const label = badge.querySelector('.selection-badge-label');
8172
+ if (!label)
8173
+ return;
8174
+ label.tabIndex = this._isSelectedLabelTruncated(label) ? 0 : -1;
8175
+ });
8176
+ const currentTrigger = this._selectedLabelTooltipTrigger;
8177
+ if (currentTrigger?.classList.contains('selection-badge-label')
8178
+ && !this._isSelectedLabelVisibleInViewport(currentTrigger)) {
8179
+ if (this._selectedLabelTooltipPointerTrigger === currentTrigger) {
8180
+ this._selectedLabelTooltipPointerTrigger = null;
8181
+ }
8182
+ this._hideSelectedLabelTooltip();
8183
+ }
8184
+ const trigger = this._selectedLabelTooltipTrigger
8185
+ ?? this._selectedLabelTooltipFocusTrigger
8186
+ ?? this._selectedLabelTooltipPointerTrigger;
8187
+ if (!trigger)
8188
+ return;
8189
+ if (!trigger.isConnected || !this._isSelectedLabelVisibleInViewport(trigger)) {
8190
+ if (this._selectedLabelTooltipPointerTrigger === trigger) {
8191
+ this._selectedLabelTooltipPointerTrigger = null;
8192
+ }
8193
+ if (this._selectedLabelTooltipTrigger === trigger)
8194
+ this._hideSelectedLabelTooltip();
8195
+ return;
8196
+ }
8197
+ const label = this._getSelectedLabelForTrigger(trigger);
8198
+ if (label === null || !this._isSelectedLabelTruncated(trigger)) {
8199
+ if (this._selectedLabelTooltipTrigger === trigger)
8200
+ this._hideSelectedLabelTooltip();
8201
+ return;
8202
+ }
8203
+ this._showSelectedLabelTooltip(trigger);
7572
8204
  }
7573
8205
  _syncListboxAccessibility() {
7574
8206
  if (!this._dropdown || !this._engine || !this._state)
@@ -7646,6 +8278,15 @@
7646
8278
  this._dropdown.removeAttribute('inert');
7647
8279
  this._dropdown.removeAttribute('aria-hidden');
7648
8280
  this._markOpenStart();
8281
+ this._scrollToSelectedConfigAtOpen = { ...this._config.scrollToSelected };
8282
+ this._openOptionsViewportAnchor = this._scrollToSelectedConfigAtOpen.onOpen === 'preserve'
8283
+ ? (this._closedOptionsViewportAnchor ?? this._captureOptionsViewportAnchor())
8284
+ : null;
8285
+ this._closedOptionsViewportAnchor = null;
8286
+ this._selectedOptionsConfigAtOpen = { ...this._config.selectedOptions };
8287
+ this._selectedOptionsSelectionAtOpen = this._config.selectedOptions.placement === 'selected-first'
8288
+ ? new Set(this._engine.state.selectedKeys)
8289
+ : null;
7649
8290
  this.setAttribute('data-open', 'true');
7650
8291
  this._liftStackingAncestors();
7651
8292
  this._dropdown.style.display = 'block';
@@ -7657,28 +8298,17 @@
7657
8298
  this._emit('open', {});
7658
8299
  this._config.callbacks.onOpen?.();
7659
8300
  this._announce('Options expanded');
7660
- // Scroll to selected if configured
7661
- if (this._config.scrollToSelected.enabled) {
7662
- const keyboardActiveChangeGeneration = this._keyboardActiveChangeGeneration;
7663
- const canRestoreOpenSelection = () => this._state.isOpen
7664
- && this._keyboardActiveChangeGeneration === keyboardActiveChangeGeneration;
7665
- // Use requestAnimationFrame for better timing after render
7666
- this._requestLifecycleFrame(() => {
7667
- if (!canRestoreOpenSelection())
7668
- return;
7669
- // Double RAF to ensure layout is complete
7670
- this._requestLifecycleFrame(() => {
7671
- if (!canRestoreOpenSelection())
7672
- return;
7673
- this._scrollToSelected();
7674
- });
7675
- });
7676
- }
8301
+ this._scheduleOpenSelectedScroll();
7677
8302
  }
7678
8303
  _handleClose(reason = 'programmatic') {
8304
+ if (this._state.isOpen) {
8305
+ this._closedOptionsViewportAnchor = this._captureOptionsViewportAnchor();
8306
+ }
7679
8307
  const effects = this._engine.dispatch({ type: 'CLOSE_REQUEST', reason });
7680
8308
  if (!effects.some((effect) => effect.type === 'POPUP_CLOSED'))
7681
8309
  return;
8310
+ this._cancelOpenSelectedScroll();
8311
+ this._selectedOptionsSelectionAtOpen = null;
7682
8312
  this.removeAttribute('data-open');
7683
8313
  this._restoreLiftedAncestors();
7684
8314
  this._dropdown.setAttribute('data-placement', this._resolvedDropdownPlacement);
@@ -7690,6 +8320,257 @@
7690
8320
  this._config.callbacks.onClose?.();
7691
8321
  this._announce('Options collapsed');
7692
8322
  }
8323
+ /**
8324
+ * Defer the one automatic selected-option positioning operation until the
8325
+ * dropdown's own entrance geometry has settled. Logical active/ARIA state
8326
+ * remains synchronous in _setInitialActiveOption().
8327
+ */
8328
+ _scheduleOpenSelectedScroll() {
8329
+ this._cancelOpenSelectedScroll();
8330
+ const openingConfig = this._scrollToSelectedConfigAtOpen;
8331
+ if (!openingConfig.enabled)
8332
+ return;
8333
+ const generation = this._openSelectedScrollGeneration;
8334
+ const keyboardGeneration = this._keyboardActiveChangeGeneration;
8335
+ const initialScrollTop = this._optionsContainer.scrollTop;
8336
+ const animations = [];
8337
+ const frameIds = new Set();
8338
+ let timerId = null;
8339
+ let completed = false;
8340
+ const isCurrent = () => generation === this._openSelectedScrollGeneration
8341
+ && this._state.isOpen
8342
+ && this.isConnected
8343
+ && this._config.scrollToSelected.enabled
8344
+ && keyboardGeneration === this._keyboardActiveChangeGeneration;
8345
+ const removeListeners = () => {
8346
+ this._optionsContainer.removeEventListener('wheel', cancelForUserInput);
8347
+ this._optionsContainer.removeEventListener('touchstart', cancelForUserInput);
8348
+ this._optionsContainer.removeEventListener('pointerdown', cancelForUserInput);
8349
+ this._optionsContainer.removeEventListener('scroll', cancelForUserScroll);
8350
+ for (const animation of animations) {
8351
+ animation.removeEventListener('finish', onAnimationStateChange);
8352
+ animation.removeEventListener('cancel', onAnimationStateChange);
8353
+ }
8354
+ };
8355
+ const cleanup = () => {
8356
+ removeListeners();
8357
+ for (const id of frameIds)
8358
+ cancelAnimationFrame(id);
8359
+ frameIds.clear();
8360
+ if (timerId !== null) {
8361
+ clearTimeout(timerId);
8362
+ this._lifecycleTimers.delete(timerId);
8363
+ timerId = null;
8364
+ }
8365
+ if (this._openSelectedScrollCleanup === cleanup) {
8366
+ this._openSelectedScrollCleanup = null;
8367
+ }
8368
+ };
8369
+ const cancelForUserInput = () => this._cancelOpenSelectedScroll();
8370
+ const cancelForUserScroll = () => {
8371
+ if (Math.abs(this._optionsContainer.scrollTop - initialScrollTop) > 1) {
8372
+ this._cancelOpenSelectedScroll();
8373
+ }
8374
+ };
8375
+ const finish = () => {
8376
+ if (completed)
8377
+ return;
8378
+ completed = true;
8379
+ cleanup();
8380
+ if (!isCurrent())
8381
+ return;
8382
+ const frameId = requestAnimationFrame(() => {
8383
+ frameIds.delete(frameId);
8384
+ cleanup();
8385
+ if (!isCurrent())
8386
+ return;
8387
+ if (openingConfig.onOpen === 'preserve') {
8388
+ this._restorePreservedOptionsViewport();
8389
+ }
8390
+ else {
8391
+ this._scrollToSelected({
8392
+ onlyIfNeeded: openingConfig.onOpen === 'reveal',
8393
+ setActive: false,
8394
+ config: openingConfig,
8395
+ });
8396
+ }
8397
+ });
8398
+ frameIds.add(frameId);
8399
+ this._openSelectedScrollCleanup = cleanup;
8400
+ };
8401
+ const onAnimationStateChange = () => {
8402
+ if (animations.every((animation) => animation.playState === 'finished' || animation.playState === 'idle'))
8403
+ finish();
8404
+ };
8405
+ const begin = () => {
8406
+ if (!isCurrent()) {
8407
+ cleanup();
8408
+ return;
8409
+ }
8410
+ const getAnimations = this._dropdown.getAnimations;
8411
+ const reducedMotion = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches ?? false;
8412
+ if (!reducedMotion && typeof getAnimations === 'function') {
8413
+ for (const animation of getAnimations.call(this._dropdown)) {
8414
+ const timing = animation.effect?.getComputedTiming();
8415
+ if (!timing || timing.iterations === Infinity || animation.playState === 'finished'
8416
+ || animation.playState === 'idle')
8417
+ continue;
8418
+ animations.push(animation);
8419
+ }
8420
+ }
8421
+ if (animations.length === 0) {
8422
+ if (!reducedMotion && typeof getAnimations !== 'function') {
8423
+ const fallbackWait = this._getDropdownEntranceFallbackDurationMs();
8424
+ if (fallbackWait > 0) {
8425
+ timerId = window.setTimeout(finish, fallbackWait + 34);
8426
+ this._lifecycleTimers.add(timerId);
8427
+ return;
8428
+ }
8429
+ }
8430
+ finish();
8431
+ return;
8432
+ }
8433
+ for (const animation of animations) {
8434
+ animation.addEventListener('finish', onAnimationStateChange);
8435
+ animation.addEventListener('cancel', onAnimationStateChange);
8436
+ }
8437
+ const remainingMs = Math.max(...animations.map((animation) => {
8438
+ const timing = animation.effect?.getComputedTiming();
8439
+ const endTime = Number(timing?.endTime);
8440
+ const currentTime = Number(animation.currentTime ?? 0);
8441
+ return Number.isFinite(endTime) ? Math.max(0, endTime - currentTime) : 0;
8442
+ }));
8443
+ const boundedWait = Math.min(10000, remainingMs + 50);
8444
+ timerId = window.setTimeout(finish, boundedWait);
8445
+ this._lifecycleTimers.add(timerId);
8446
+ };
8447
+ this._optionsContainer.addEventListener('wheel', cancelForUserInput, { passive: true });
8448
+ this._optionsContainer.addEventListener('touchstart', cancelForUserInput, { passive: true });
8449
+ this._optionsContainer.addEventListener('pointerdown', cancelForUserInput, { passive: true });
8450
+ this._optionsContainer.addEventListener('scroll', cancelForUserScroll, { passive: true });
8451
+ this._openSelectedScrollCleanup = cleanup;
8452
+ const frameId = requestAnimationFrame(() => {
8453
+ frameIds.delete(frameId);
8454
+ begin();
8455
+ });
8456
+ frameIds.add(frameId);
8457
+ }
8458
+ _cancelOpenSelectedScroll() {
8459
+ this._openSelectedScrollGeneration += 1;
8460
+ this._openSelectedScrollCleanup?.();
8461
+ this._openSelectedScrollCleanup = null;
8462
+ }
8463
+ _captureOptionsViewportAnchor() {
8464
+ const scroller = this._optionsContainer;
8465
+ const scrollTop = scroller.scrollTop;
8466
+ const order = this._renderPlan.filteredKeys.slice();
8467
+ const viewportTop = scroller.getBoundingClientRect().top + scroller.clientTop;
8468
+ const viewportBottom = viewportTop + scroller.clientHeight;
8469
+ const visible = Array.from(scroller.querySelectorAll('[data-sm-selectable], [data-selectable]'))
8470
+ .map((option) => ({ option, rect: option.getBoundingClientRect() }))
8471
+ .filter(({ rect }) => rect.height > 0 && rect.bottom > viewportTop && rect.top < viewportBottom)
8472
+ .sort((left, right) => left.rect.top - right.rect.top)[0];
8473
+ if (visible) {
8474
+ const sourceIndex = Number(visible.option.getAttribute('data-sm-index') ?? visible.option.getAttribute('data-index'));
8475
+ const key = Number.isInteger(sourceIndex) ? this._itemRegistry.indexToKey.get(sourceIndex) ?? null : null;
8476
+ if (key !== null) {
8477
+ return { key, offset: visible.rect.top - viewportTop, scrollTop, order };
8478
+ }
8479
+ }
8480
+ if (this._guardedVirtualizer && order.length > 0
8481
+ && typeof this._guardedVirtualizer.computeWindow === 'function') {
8482
+ const viewportHeight = this._resolveGuardedViewportHeight();
8483
+ const index = this._guardedVirtualizer.computeWindow(scrollTop, viewportHeight).startIndex;
8484
+ const key = order[index] ?? null;
8485
+ if (key !== null) {
8486
+ return {
8487
+ key,
8488
+ offset: this._guardedVirtualizer.cumulativeOffset(index) - scrollTop,
8489
+ scrollTop,
8490
+ order,
8491
+ };
8492
+ }
8493
+ }
8494
+ return { key: null, offset: 0, scrollTop, order };
8495
+ }
8496
+ /** Restore the previous visible option only when this opening changed order. */
8497
+ _restorePreservedOptionsViewport() {
8498
+ const anchor = this._openOptionsViewportAnchor;
8499
+ this._openOptionsViewportAnchor = null;
8500
+ if (!anchor)
8501
+ return;
8502
+ const nextOrder = this._renderPlan.filteredKeys;
8503
+ const nextPositionByKey = new Map(nextOrder.map((key, index) => [key, index]));
8504
+ const orderChanged = anchor.order.some((key, oldIndex) => {
8505
+ const nextIndex = nextPositionByKey.get(key);
8506
+ return nextIndex !== undefined && nextIndex !== oldIndex;
8507
+ });
8508
+ if (!orderChanged)
8509
+ return;
8510
+ const scroller = this._optionsContainer;
8511
+ const viewportHeight = this._resolveGuardedViewportHeight() || scroller.clientHeight;
8512
+ let targetScrollTop = null;
8513
+ if (anchor.key !== null) {
8514
+ const displayIndex = this._renderPlan.displayIndexByKey.get(anchor.key);
8515
+ if (displayIndex !== undefined) {
8516
+ const sourceIndex = this._renderPlan.sourceIndexByKey.get(anchor.key);
8517
+ const option = sourceIndex === undefined ? null : this._getOptionElementByIndex(sourceIndex);
8518
+ const viewportTop = scroller.getBoundingClientRect().top + scroller.clientTop;
8519
+ const optionTop = option?.getBoundingClientRect().top;
8520
+ if (option && option.getBoundingClientRect().height > 0 && Number.isFinite(optionTop)) {
8521
+ targetScrollTop = scroller.scrollTop + optionTop - viewportTop - anchor.offset;
8522
+ }
8523
+ else if (this._guardedVirtualizer) {
8524
+ targetScrollTop = this._guardedVirtualizer.cumulativeOffset(displayIndex) - anchor.offset;
8525
+ }
8526
+ }
8527
+ }
8528
+ if (targetScrollTop === null)
8529
+ targetScrollTop = anchor.scrollTop;
8530
+ let maxScrollTop = Number.POSITIVE_INFINITY;
8531
+ if (this._guardedVirtualizer) {
8532
+ maxScrollTop = Math.max(0, this._guardedVirtualizer.cumulativeOffset(nextOrder.length) - viewportHeight);
8533
+ }
8534
+ else if (scroller.scrollHeight > 0 && scroller.clientHeight > 0) {
8535
+ maxScrollTop = Math.max(0, scroller.scrollHeight - scroller.clientHeight);
8536
+ }
8537
+ targetScrollTop = Math.max(0, Math.min(targetScrollTop, maxScrollTop));
8538
+ if (Math.abs(targetScrollTop - scroller.scrollTop) < 1)
8539
+ return;
8540
+ // The coordinator owns this single restoration write. The virtualizer may
8541
+ // update its mounted window in response, but it must not issue a second
8542
+ // physical positioning correction for this transaction.
8543
+ this._guardedVirtualScrollTop = targetScrollTop;
8544
+ scroller.scrollTop = targetScrollTop;
8545
+ }
8546
+ /** Used only when Element.getAnimations() is unavailable. */
8547
+ _getDropdownEntranceFallbackDurationMs() {
8548
+ if (window.matchMedia?.('(prefers-reduced-motion: reduce)').matches)
8549
+ return 0;
8550
+ const style = getComputedStyle(this._dropdown);
8551
+ const parseTime = (value) => {
8552
+ const trimmed = value.trim();
8553
+ const parsed = Number.parseFloat(trimmed);
8554
+ if (!Number.isFinite(parsed))
8555
+ return 0;
8556
+ return trimmed.endsWith('ms') ? parsed : trimmed.endsWith('s') ? parsed * 1000 : 0;
8557
+ };
8558
+ const animationDurations = style.animationDuration.split(',');
8559
+ const animationDelays = style.animationDelay.split(',');
8560
+ const animationIterations = style.animationIterationCount.split(',');
8561
+ const maxAnimation = Math.max(0, ...animationDurations.map((duration, index) => {
8562
+ const count = Number.parseFloat(animationIterations[index % animationIterations.length] ?? '1');
8563
+ if (!Number.isFinite(count))
8564
+ return 0;
8565
+ return parseTime(duration)
8566
+ * Math.max(0, count)
8567
+ + parseTime(animationDelays[index % animationDelays.length] ?? '0s');
8568
+ }));
8569
+ const transitionDurations = style.transitionDuration.split(',');
8570
+ const transitionDelays = style.transitionDelay.split(',');
8571
+ const maxTransition = Math.max(0, ...transitionDurations.map((duration, index) => parseTime(duration) + parseTime(transitionDelays[index % transitionDelays.length] ?? '0s')));
8572
+ return Math.min(10000, Math.max(maxAnimation, maxTransition));
8573
+ }
7693
8574
  /** Stop an outstanding exit before reopening, disconnecting or starting another one. */
7694
8575
  _cancelDropdownExit() {
7695
8576
  if (this._dropdownExitTimer !== null) {
@@ -7916,6 +8797,10 @@
7916
8797
  return results;
7917
8798
  }
7918
8799
  _handleSearch(query) {
8800
+ if (this._selectedLabelTooltipTrigger === this._input
8801
+ && (query.length > 0 || this._getSelectedLabelForTrigger(this._input) === null)) {
8802
+ this._hideSelectedLabelTooltip();
8803
+ }
7919
8804
  if (this._dataRequestCoordinator
7920
8805
  && (this._acknowledgedProjectionPending || this._acknowledgedProjectionSettling)) {
7921
8806
  // Keep the committed query/generation stable until the accepted snapshot
@@ -8020,6 +8905,12 @@
8020
8905
  }
8021
8906
  }
8022
8907
  _handleKeydown(e) {
8908
+ if (e.key === 'Escape' && !this._selectedLabelTooltip.hidden) {
8909
+ e.preventDefault();
8910
+ e.stopPropagation();
8911
+ this._dismissSelectedLabelTooltip();
8912
+ return;
8913
+ }
8023
8914
  if (!this._config.enabled)
8024
8915
  return;
8025
8916
  switch (e.key) {
@@ -8044,26 +8935,38 @@
8044
8935
  case 'Home':
8045
8936
  e.preventDefault();
8046
8937
  if (this._state.isOpen) {
8938
+ if (this._usesSelectedFirstVisualOrder()) {
8939
+ this._moveToVisualBoundary('first', { shiftKey: e.shiftKey, toggleKey: e.ctrlKey || e.metaKey });
8940
+ break;
8941
+ }
8047
8942
  const selectableIndices = this._getSelectableOptionIndices();
8048
8943
  const firstIndex = selectableIndices[0];
8049
8944
  if (firstIndex === undefined)
8050
8945
  break;
8051
8946
  this._setActive(firstIndex);
8052
8947
  if (this._config.selection.mode === 'multi' && e.shiftKey) {
8053
- this._selectRange(this._rangeAnchorIndex ?? firstIndex, firstIndex, { clear: !(e.ctrlKey || e.metaKey) });
8948
+ const targetKey = this._itemRegistry.indexToKey.get(firstIndex);
8949
+ if (targetKey !== undefined)
8950
+ this._selectKeyboardRange(this._rangeAnchorKey ?? targetKey, targetKey, { clear: !(e.ctrlKey || e.metaKey) });
8054
8951
  }
8055
8952
  }
8056
8953
  break;
8057
8954
  case 'End':
8058
8955
  e.preventDefault();
8059
8956
  if (this._state.isOpen) {
8957
+ if (this._usesSelectedFirstVisualOrder()) {
8958
+ this._moveToVisualBoundary('last', { shiftKey: e.shiftKey, toggleKey: e.ctrlKey || e.metaKey });
8959
+ break;
8960
+ }
8060
8961
  const selectableIndices = this._getSelectableOptionIndices();
8061
8962
  const lastIndex = selectableIndices[selectableIndices.length - 1];
8062
8963
  if (lastIndex === undefined)
8063
8964
  break;
8064
8965
  this._setActive(lastIndex);
8065
8966
  if (this._config.selection.mode === 'multi' && e.shiftKey) {
8066
- this._selectRange(this._rangeAnchorIndex ?? lastIndex, lastIndex, { clear: !(e.ctrlKey || e.metaKey) });
8967
+ const targetKey = this._itemRegistry.indexToKey.get(lastIndex);
8968
+ if (targetKey !== undefined)
8969
+ this._selectKeyboardRange(this._rangeAnchorKey ?? targetKey, targetKey, { clear: !(e.ctrlKey || e.metaKey) });
8067
8970
  }
8068
8971
  }
8069
8972
  break;
@@ -8081,6 +8984,9 @@
8081
8984
  break;
8082
8985
  case 'Enter':
8083
8986
  case ' ':
8987
+ if (e.key === ' ' && this._config.searchable && e.target === this._input) {
8988
+ break;
8989
+ }
8084
8990
  e.preventDefault();
8085
8991
  if (!this._state.isOpen) {
8086
8992
  this._handleOpen();
@@ -8104,7 +9010,8 @@
8104
9010
  break;
8105
9011
  case 'a':
8106
9012
  case 'A':
8107
- if ((e.ctrlKey || e.metaKey) && this._config.selection.mode === 'multi') {
9013
+ if ((e.ctrlKey || e.metaKey) && !e.altKey
9014
+ && this._config.selection.mode === 'multi' && !this._config.searchable) {
8108
9015
  e.preventDefault();
8109
9016
  this._selectAll();
8110
9017
  }
@@ -8118,6 +9025,26 @@
8118
9025
  }
8119
9026
  }
8120
9027
  _moveActive(delta, opts) {
9028
+ if (this._usesSelectedFirstVisualOrder()) {
9029
+ const model = this._getVisualNavigationModel();
9030
+ if (model.selectableKeys.length === 0)
9031
+ return;
9032
+ const activeKey = this._engine.state.activeKey;
9033
+ const currentPosition = activeKey === null ? undefined : model.selectablePositionByKey.get(activeKey);
9034
+ // Load-more is only requested after movement reaches the actual visual end.
9035
+ if (delta === 1 && currentPosition === model.selectableKeys.length - 1 && this._requestKeyboardLoadMore())
9036
+ return;
9037
+ const nextKey = resolveVisualMovement(model, activeKey, delta);
9038
+ if (nextKey === null)
9039
+ return;
9040
+ this._setActiveForVisualKey(nextKey);
9041
+ if (this._config.selection.mode === 'multi' && opts?.shiftKey) {
9042
+ const anchorKey = this._rangeAnchorKey ?? activeKey ?? nextKey;
9043
+ this._rangeAnchorKey = anchorKey;
9044
+ this._selectKeyboardRange(anchorKey, nextKey, { clear: !opts.toggleKey });
9045
+ }
9046
+ return;
9047
+ }
8121
9048
  const selectableIndices = this._getSelectableOptionIndices();
8122
9049
  if (selectableIndices.length === 0)
8123
9050
  return;
@@ -8139,14 +9066,90 @@
8139
9066
  const next = selectableIndices[nextPosition];
8140
9067
  this._setActive(next);
8141
9068
  if (this._config.selection.mode === 'multi' && opts?.shiftKey) {
8142
- const anchor = this._rangeAnchorIndex ?? currentIndex;
8143
- const anchorIndex = anchor >= 0 ? anchor : next;
8144
- if (this._rangeAnchorIndex === null) {
8145
- this._rangeAnchorIndex = anchorIndex;
8146
- }
8147
- this._selectRange(anchorIndex, next, { clear: !opts?.toggleKey });
9069
+ const nextKey = this._itemRegistry.indexToKey.get(next);
9070
+ if (nextKey === undefined)
9071
+ return;
9072
+ const anchorKey = this._rangeAnchorKey ?? (currentIndex >= 0 ? this._itemRegistry.indexToKey.get(currentIndex) : undefined) ?? nextKey;
9073
+ this._rangeAnchorKey = anchorKey;
9074
+ this._selectKeyboardRange(anchorKey, nextKey, { clear: !opts?.toggleKey });
8148
9075
  }
8149
9076
  }
9077
+ _usesSelectedFirstVisualOrder() {
9078
+ return this._selectedOptionsConfigAtOpen.placement === 'selected-first';
9079
+ }
9080
+ _getVisualNavigationModel() {
9081
+ this._ensureRegistryCurrent();
9082
+ return createVisualNavigationModel(this._renderPlan.filteredKeys, (key) => {
9083
+ const record = this._itemRegistry.keyToRecord.get(key);
9084
+ if (!record || record.disabled)
9085
+ return false;
9086
+ const option = this._getOptionElementByIndex(record.index);
9087
+ return option?.getAttribute('aria-disabled') !== 'true';
9088
+ });
9089
+ }
9090
+ _setActiveForVisualKey(key, reason = 'keyboard', options = {}) {
9091
+ const sourceIndex = this._renderPlan.sourceIndexByKey.get(key)
9092
+ ?? this._itemRegistry.keyToIndex.get(key);
9093
+ if (sourceIndex === undefined)
9094
+ return;
9095
+ this._setActive(sourceIndex, reason, options);
9096
+ }
9097
+ _moveToVisualBoundary(boundary, opts) {
9098
+ const model = this._getVisualNavigationModel();
9099
+ const targetKey = resolveVisualBoundary(model, boundary);
9100
+ if (targetKey === null)
9101
+ return;
9102
+ const currentKey = this._engine.state.activeKey;
9103
+ this._setActiveForVisualKey(targetKey);
9104
+ if (this._config.selection.mode === 'multi' && opts?.shiftKey) {
9105
+ const anchorKey = this._rangeAnchorKey ?? currentKey ?? targetKey;
9106
+ this._rangeAnchorKey = anchorKey;
9107
+ this._selectKeyboardRange(anchorKey, targetKey, { clear: !opts.toggleKey });
9108
+ }
9109
+ }
9110
+ _selectKeyboardRange(anchorKey, targetKey, opts) {
9111
+ if (this._usesSelectedFirstVisualOrder()) {
9112
+ const model = this._getVisualNavigationModel();
9113
+ const resolvedAnchor = model.selectablePositionByKey.has(anchorKey) ? anchorKey : targetKey;
9114
+ this._rangeAnchorKey = resolvedAnchor;
9115
+ this._selectVisualRange(resolvedAnchor, targetKey, opts);
9116
+ return;
9117
+ }
9118
+ const start = this._itemRegistry.keyToIndex.get(anchorKey);
9119
+ const end = this._itemRegistry.keyToIndex.get(targetKey);
9120
+ if (start !== undefined && end !== undefined)
9121
+ this._selectRange(start, end, opts);
9122
+ }
9123
+ _selectVisualRange(anchorKey, targetKey, opts) {
9124
+ if (this._config.selection.mode !== 'multi')
9125
+ return;
9126
+ this._ensureRegistryCurrent();
9127
+ const model = this._getVisualNavigationModel();
9128
+ const rangeKeys = resolveVisualRange(model, anchorKey, targetKey);
9129
+ if (rangeKeys.length === 0)
9130
+ return;
9131
+ const selectedEntries = this._getSelectedEntries();
9132
+ const entries = opts?.clear
9133
+ ? selectedEntries.filter((entry) => !this._itemRegistry.keyToRecord.has(entry.key))
9134
+ : selectedEntries;
9135
+ for (const key of rangeKeys) {
9136
+ const record = this._itemRegistry.keyToRecord.get(key);
9137
+ if (!record || this._isOptionSelectionBlocked(record.item))
9138
+ continue;
9139
+ entries.push(record);
9140
+ }
9141
+ this._requestSelectionReplacement(entries, opts?.reason ?? 'keyboard', 'select visual range');
9142
+ this._renderOptions();
9143
+ this._updateInputDisplay();
9144
+ const target = this._itemRegistry.keyToRecord.get(targetKey);
9145
+ const selectDetail = target ? this._getSelectEventDetail(target) : null;
9146
+ if (selectDetail)
9147
+ this._emit('select', selectDetail);
9148
+ this._emitChange();
9149
+ this._announce(`${this._state.selectedIndices.size} items selected`);
9150
+ if (selectDetail)
9151
+ this._config.callbacks.onSelect?.(selectDetail);
9152
+ }
8150
9153
  /** Return true only when boundary navigation is held for an in-flight/new page. */
8151
9154
  _requestKeyboardLoadMore() {
8152
9155
  if (!this._state.isOpen
@@ -8174,7 +9177,7 @@
8174
9177
  this._dispatchAcknowledgedActions(actions);
8175
9178
  return true;
8176
9179
  }
8177
- _setActive(index, reason = 'keyboard') {
9180
+ _setActive(index, reason = 'keyboard', options = {}) {
8178
9181
  this._ensureRegistryCurrent();
8179
9182
  const record = this._getRecordByIndex(index);
8180
9183
  let option = this._getOptionElementByIndex(index);
@@ -8185,8 +9188,10 @@
8185
9188
  if (!record || record.disabled || !option || option.getAttribute('aria-disabled') === 'true') {
8186
9189
  return;
8187
9190
  }
8188
- if (reason === 'keyboard')
9191
+ if (reason === 'keyboard' || reason === 'search') {
8189
9192
  this._keyboardActiveChangeGeneration += 1;
9193
+ this._cancelOpenSelectedScroll();
9194
+ }
8190
9195
  const previousIndex = this._state.activeIndex;
8191
9196
  this._dispatchActiveKey(record.key, reason, 'set active');
8192
9197
  if (this._state.activeIndex !== index)
@@ -8213,8 +9218,7 @@
8213
9218
  else {
8214
9219
  this._syncCustomOptionActiveClasses(option, true);
8215
9220
  }
8216
- if (typeof option.scrollIntoView === 'function') {
8217
- // Don't scroll wildly when just opening with pre-selections
9221
+ if (options.scroll !== false && typeof option.scrollIntoView === 'function') {
8218
9222
  option.scrollIntoView({ block: 'nearest', behavior: 'smooth' });
8219
9223
  }
8220
9224
  // Announce position for screen readers
@@ -8270,8 +9274,22 @@
8270
9274
  this._typeTimeout = window.setTimeout(() => {
8271
9275
  this._typeBuffer = '';
8272
9276
  }, 500);
8273
- // Find first matching option
9277
+ // Type-ahead uses the displayed candidate order when a presentation projection is active.
8274
9278
  const getValue = this._config.serverSide.getLabelFromItem || ((item) => item?.label ?? String(item));
9279
+ if (this._usesSelectedFirstVisualOrder()) {
9280
+ const model = this._getVisualNavigationModel();
9281
+ const matchKey = model.selectableKeys.find((key) => {
9282
+ const record = this._itemRegistry.keyToRecord.get(key);
9283
+ return record !== undefined && getValue(record.item).toLowerCase().startsWith(this._typeBuffer);
9284
+ });
9285
+ if (matchKey !== undefined) {
9286
+ const sourceIndex = this._renderPlan.sourceIndexByKey.get(matchKey)
9287
+ ?? this._itemRegistry.keyToIndex.get(matchKey);
9288
+ if (sourceIndex !== undefined)
9289
+ this._setActive(sourceIndex, 'search');
9290
+ }
9291
+ return;
9292
+ }
8275
9293
  const matchIndex = this._state.loadedItems.findIndex((item) => getValue(item).toLowerCase().startsWith(this._typeBuffer));
8276
9294
  if (matchIndex >= 0) {
8277
9295
  this._setActive(matchIndex, 'search');
@@ -8340,6 +9358,17 @@
8340
9358
  };
8341
9359
  }
8342
9360
  _setInitialActiveOption() {
9361
+ if (this._usesSelectedFirstVisualOrder()) {
9362
+ const model = this._getVisualNavigationModel();
9363
+ const selectedKey = model.selectableKeys.find((key) => this._engine.state.selectedKeys.has(key));
9364
+ if (selectedKey === undefined) {
9365
+ this._dispatchActiveKey(null, 'open', 'initial active option');
9366
+ return;
9367
+ }
9368
+ // Resolve via stable identity so the open-time projection remains authoritative.
9369
+ this._setActiveForVisualKey(selectedKey, 'open', { scroll: false });
9370
+ return;
9371
+ }
8343
9372
  const selectableIndices = this._getSelectableOptionIndices();
8344
9373
  const selected = Array.from(this._state.selectedIndices).sort((a, b) => a - b);
8345
9374
  // Opening an empty select must not implicitly assign an active descendant.
@@ -8349,7 +9378,9 @@
8349
9378
  return;
8350
9379
  }
8351
9380
  const target = selected.find((index) => selectableIndices.includes(index)) ?? selectableIndices[0];
8352
- this._setActive(target, 'open');
9381
+ // Set logical active state and ARIA immediately. The open-time coordinator
9382
+ // owns any physical positioning after the dropdown's entrance settles.
9383
+ this._setActive(target, 'open', { scroll: false });
8353
9384
  }
8354
9385
  _announce(message) {
8355
9386
  const effects = computeAccessibilityEffects(deriveAccessibilityState(this._engine.state), {
@@ -8403,9 +9434,10 @@
8403
9434
  const toggleKey = Boolean(opts?.toggleKey);
8404
9435
  const shiftKey = Boolean(opts?.shiftKey);
8405
9436
  if (shiftKey) {
8406
- const anchor = this._rangeAnchorIndex ?? index;
8407
- this._selectRange(anchor, index, { clear: !toggleKey, reason });
8408
- this._rangeAnchorIndex = anchor;
9437
+ const targetKey = record.key;
9438
+ const anchorKey = this._rangeAnchorKey ?? targetKey;
9439
+ this._selectKeyboardRange(anchorKey, targetKey, { clear: !toggleKey, reason });
9440
+ this._rangeAnchorKey = anchorKey;
8409
9441
  return;
8410
9442
  }
8411
9443
  // Multi select with toggle
@@ -8419,7 +9451,7 @@
8419
9451
  // Re-render to update styles (safer than trying to find the element in filtered list)
8420
9452
  this._renderOptions();
8421
9453
  }
8422
- this._rangeAnchorIndex = index;
9454
+ this._rangeAnchorKey = record.key;
8423
9455
  this._updateInputDisplay();
8424
9456
  const selectDetail = this._getSelectEventDetail(record);
8425
9457
  this._emit('select', selectDetail);
@@ -8450,7 +9482,7 @@
8450
9482
  : null;
8451
9483
  const hadFocusedChipRemove = focusedBadge !== null;
8452
9484
  const focusedBadgeIndex = focusedBadge
8453
- ? Array.from(this._inputContent.querySelectorAll('.selection-badge')).indexOf(focusedBadge)
9485
+ ? this._getActiveChipBadges().indexOf(focusedBadge)
8454
9486
  : -1;
8455
9487
  const option = this._itemRegistry.keyToRecord.has(entry.key)
8456
9488
  ? this._getOptionElementByIndex(entry.index)
@@ -8476,7 +9508,7 @@
8476
9508
  this._renderOptions();
8477
9509
  this._emitChange();
8478
9510
  if (hadFocusedChipRemove && this.isConnected) {
8479
- const removeButtons = this._inputContent.querySelectorAll('[part="chip-remove"]');
9511
+ const removeButtons = this._getActiveChipRemoveButtons();
8480
9512
  if (removeButtons.length > 0) {
8481
9513
  const nextFocusIndex = Math.min(Math.max(focusedBadgeIndex, 0), removeButtons.length - 1);
8482
9514
  removeButtons[nextFocusIndex].focus();
@@ -8490,8 +9522,248 @@
8490
9522
  : undefined;
8491
9523
  this._emit('remove', { item: config?.item ?? item, index: entry.index });
8492
9524
  }
9525
+ _getActiveChipBadges() {
9526
+ return Array.from(this._inputContent.querySelectorAll('.selection-badge'))
9527
+ .filter((badge) => badge.dataset.motion !== 'exiting' && !badge.hasAttribute('inert'));
9528
+ }
9529
+ _getActiveChipRemoveButtons() {
9530
+ return this._getActiveChipBadges()
9531
+ .map((badge) => badge.querySelector('[part="chip-remove"]'))
9532
+ .filter((button) => button !== null && !button.disabled);
9533
+ }
9534
+ _clearChipPresentation() {
9535
+ const badges = new Set(this._chipElements.values());
9536
+ const tooltipTriggers = [
9537
+ this._selectedLabelTooltipTrigger,
9538
+ this._selectedLabelTooltipPointerTrigger,
9539
+ this._selectedLabelTooltipFocusTrigger,
9540
+ this._selectedLabelTooltipDismissedTrigger,
9541
+ ];
9542
+ if (tooltipTriggers.some((trigger) => trigger !== null
9543
+ && Array.from(badges).some((badge) => badge.contains(trigger)))) {
9544
+ this._hideSelectedLabelTooltip(true);
9545
+ }
9546
+ for (const [key, state] of this._chipExitStates) {
9547
+ window.clearTimeout(state.timer);
9548
+ this._chipExitStates.delete(key);
9549
+ state.animations.forEach((animation) => animation.cancel());
9550
+ }
9551
+ for (const badge of this._chipElements.values()) {
9552
+ badge.removeAttribute('inert');
9553
+ badge.remove();
9554
+ }
9555
+ this._chipExitStates.clear();
9556
+ this._chipElements.clear();
9557
+ }
9558
+ _cancelChipExit(key, badge) {
9559
+ const state = this._chipExitStates.get(key);
9560
+ if (!state || state.badge !== badge)
9561
+ return;
9562
+ window.clearTimeout(state.timer);
9563
+ this._chipExitStates.delete(key);
9564
+ state.animations.forEach((animation) => animation.cancel());
9565
+ badge.removeAttribute('data-motion');
9566
+ badge.removeAttribute('aria-hidden');
9567
+ badge.removeAttribute('inert');
9568
+ badge.setAttribute('part', 'chip');
9569
+ const removeButton = badge.querySelector('[part="chip-remove"]');
9570
+ if (removeButton)
9571
+ removeButton.disabled = false;
9572
+ }
9573
+ _finishChipExit(key, expected) {
9574
+ const state = this._chipExitStates.get(key);
9575
+ if (!state || state.badge !== expected)
9576
+ return;
9577
+ window.clearTimeout(state.timer);
9578
+ this._chipExitStates.delete(key);
9579
+ state.animations.forEach((animation) => {
9580
+ if (animation.playState !== 'finished')
9581
+ animation.cancel();
9582
+ });
9583
+ this._chipElements.delete(key);
9584
+ expected.remove();
9585
+ if (this.isConnected) {
9586
+ this._observeSelectedLabelTooltipTargets();
9587
+ this._refreshSelectedLabelTooltipMeasurements();
9588
+ }
9589
+ }
9590
+ _moveFocusOutOfChip(badge) {
9591
+ const activeElement = this._shadow.activeElement;
9592
+ if (!(activeElement instanceof HTMLElement) || !badge.contains(activeElement))
9593
+ return;
9594
+ const badges = this._getActiveChipBadges().filter((candidate) => candidate !== badge);
9595
+ const oldIndex = Array.from(this._inputContent.querySelectorAll('.selection-badge')).indexOf(badge);
9596
+ const buttons = badges
9597
+ .map((candidate) => candidate.querySelector('[part="chip-remove"]'))
9598
+ .filter((button) => button !== null && !button.disabled);
9599
+ const next = buttons[Math.min(Math.max(oldIndex, 0), buttons.length - 1)];
9600
+ if (next)
9601
+ next.focus({ preventScroll: true });
9602
+ else
9603
+ this._input.focus({ preventScroll: true });
9604
+ }
9605
+ _beginChipExit(key, badge) {
9606
+ if (this._chipExitStates.has(key))
9607
+ return;
9608
+ this._moveFocusOutOfChip(badge);
9609
+ const label = badge.querySelector('.selection-badge-label');
9610
+ if (label) {
9611
+ this._removeSelectedLabelTooltipDescription(label);
9612
+ label.tabIndex = -1;
9613
+ if (this._selectedLabelTooltipPointerTrigger === label)
9614
+ this._selectedLabelTooltipPointerTrigger = null;
9615
+ if (this._selectedLabelTooltipFocusTrigger === label)
9616
+ this._selectedLabelTooltipFocusTrigger = null;
9617
+ if (this._selectedLabelTooltipDismissedTrigger === label)
9618
+ this._selectedLabelTooltipDismissedTrigger = null;
9619
+ if (this._selectedLabelTooltipTrigger === label)
9620
+ this._hideSelectedLabelTooltip();
9621
+ }
9622
+ badge.dataset.motion = 'exiting';
9623
+ badge.setAttribute('aria-hidden', 'true');
9624
+ badge.setAttribute('inert', '');
9625
+ badge.setAttribute('part', 'chip-exiting');
9626
+ const removeButton = badge.querySelector('[part="chip-remove"]');
9627
+ if (removeButton)
9628
+ removeButton.disabled = true;
9629
+ // Force style resolution after the exiting part is exposed. This also
9630
+ // verifies that a consumer keyframe is actually available across Shadow DOM.
9631
+ badge.getBoundingClientRect();
9632
+ const animations = (typeof badge.getAnimations === 'function' ? badge.getAnimations() : []).filter((animation) => {
9633
+ const cssAnimation = animation;
9634
+ return typeof cssAnimation.animationName === 'string'
9635
+ && cssAnimation.animationName !== 'none'
9636
+ && animation.playState !== 'idle';
9637
+ });
9638
+ const reducedMotion = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches ?? false;
9639
+ if (reducedMotion || animations.length === 0) {
9640
+ badge.removeAttribute('data-motion');
9641
+ this._chipExitStates.set(key, { badge, animations: [], timer: 0 });
9642
+ this._finishChipExit(key, badge);
9643
+ return;
9644
+ }
9645
+ const endTimes = animations.map((animation) => Number(animation.effect?.getComputedTiming().endTime ?? 0));
9646
+ const maxEndTime = Math.max(0, ...endTimes);
9647
+ const fallbackDelay = Math.min(Number.isFinite(maxEndTime) ? maxEndTime + 100 : 1000, 5000);
9648
+ const timer = window.setTimeout(() => this._finishChipExit(key, badge), fallbackDelay);
9649
+ this._chipExitStates.set(key, { badge, animations, timer });
9650
+ void Promise.allSettled(animations.map((animation) => animation.finished))
9651
+ .then(() => this._finishChipExit(key, badge));
9652
+ }
9653
+ _createChip(key) {
9654
+ const badge = document.createElement('span');
9655
+ badge.className = 'selection-badge';
9656
+ badge.setAttribute('part', 'chip');
9657
+ const label = document.createElement('span');
9658
+ label.className = 'selection-badge-label';
9659
+ label.setAttribute('part', 'chip-label');
9660
+ this._selectedLabelKeys.set(label, key);
9661
+ badge.appendChild(label);
9662
+ this._chipElements.set(key, badge);
9663
+ return badge;
9664
+ }
9665
+ _updateChip(key, index, item, badge) {
9666
+ const getLabel = this._config.serverSide.getLabelFromItem || ((value) => value?.label ?? String(value));
9667
+ const labelText = getLabel(item);
9668
+ badge.className = 'selection-badge';
9669
+ if (this._config.styles.classNames?.badge) {
9670
+ badge.classList.add(...this._config.styles.classNames.badge.split(' ').filter(Boolean));
9671
+ }
9672
+ badge.setAttribute('part', 'chip');
9673
+ badge.removeAttribute('aria-hidden');
9674
+ badge.removeAttribute('inert');
9675
+ badge.removeAttribute('data-motion');
9676
+ const label = badge.querySelector('.selection-badge-label');
9677
+ label.className = 'selection-badge-label';
9678
+ if (this._config.styles.classNames?.badgeLabel) {
9679
+ label.classList.add(...this._config.styles.classNames.badgeLabel.split(' ').filter(Boolean));
9680
+ }
9681
+ label.textContent = labelText;
9682
+ this._selectedLabelKeys.set(label, key);
9683
+ const shouldShowRemove = this._config.selection.showRemoveButton !== false;
9684
+ let removeButton = badge.querySelector('[part="chip-remove"]');
9685
+ if (!shouldShowRemove) {
9686
+ removeButton?.remove();
9687
+ return;
9688
+ }
9689
+ if (!removeButton) {
9690
+ removeButton = document.createElement('button');
9691
+ removeButton.type = 'button';
9692
+ removeButton.addEventListener('pointerdown', (event) => {
9693
+ event.stopPropagation();
9694
+ event.preventDefault();
9695
+ });
9696
+ removeButton.addEventListener('click', (event) => {
9697
+ event.stopPropagation();
9698
+ event.preventDefault();
9699
+ this._handleOptionRemove(index, key);
9700
+ });
9701
+ const removeIcon = document.createElement('span');
9702
+ removeIcon.className = 'badge-remove-icon';
9703
+ removeIcon.setAttribute('part', 'chip-remove-icon');
9704
+ removeButton.appendChild(removeIcon);
9705
+ badge.appendChild(removeButton);
9706
+ }
9707
+ removeButton.className = 'badge-remove';
9708
+ if (this._config.styles.classNames?.removeButton) {
9709
+ removeButton.classList.add(...this._config.styles.classNames.removeButton.split(' ').filter(Boolean));
9710
+ }
9711
+ if (this._config.styles.classNames?.badgeRemove) {
9712
+ removeButton.classList.add(...this._config.styles.classNames.badgeRemove.split(' ').filter(Boolean));
9713
+ }
9714
+ removeButton.setAttribute('part', 'chip-remove');
9715
+ removeButton.setAttribute('aria-label', `Remove ${labelText}`);
9716
+ removeButton.disabled = false;
9717
+ const removeIcon = removeButton.querySelector('[part="chip-remove-icon"]');
9718
+ removeIcon.className = 'badge-remove-icon';
9719
+ if (this._config.styles.classNames?.badgeRemoveIcon) {
9720
+ removeIcon.classList.add(...this._config.styles.classNames.badgeRemoveIcon.split(' ').filter(Boolean));
9721
+ }
9722
+ this._setIconContent(removeIcon, this._config.selection.removeButtonIcon, '×');
9723
+ }
9724
+ _renderSelectedChips(entries) {
9725
+ const selectedKeys = new Set(entries.map(({ key }) => key));
9726
+ for (const { key, index, item } of entries) {
9727
+ let badge = this._chipElements.get(key);
9728
+ if (!badge)
9729
+ badge = this._createChip(key);
9730
+ this._cancelChipExit(key, badge);
9731
+ this._updateChip(key, index, item, badge);
9732
+ }
9733
+ for (const [key, badge] of this._chipElements) {
9734
+ if (!selectedKeys.has(key))
9735
+ this._beginChipExit(key, badge);
9736
+ }
9737
+ // Do not move chips merely because another chip entered its exit period.
9738
+ // That keeps the exiting chip in its original layout slot while the active
9739
+ // sequence remains correct. Reorder only when selected-key order changed.
9740
+ const desiredBadges = entries
9741
+ .map(({ key }) => this._chipElements.get(key))
9742
+ .filter((badge) => badge !== undefined);
9743
+ const currentBadges = this._getActiveChipBadges();
9744
+ const orderChanged = desiredBadges.length !== currentBadges.length
9745
+ || desiredBadges.some((badge, index) => badge !== currentBadges[index]);
9746
+ if (orderChanged) {
9747
+ let nextSibling = this._input;
9748
+ for (let index = desiredBadges.length - 1; index >= 0; index -= 1) {
9749
+ const badge = desiredBadges[index];
9750
+ if (badge.nextSibling !== nextSibling)
9751
+ this._inputContent.insertBefore(badge, nextSibling);
9752
+ nextSibling = badge;
9753
+ }
9754
+ }
9755
+ }
8493
9756
  _updateInputDisplay() {
8494
9757
  const selectedEntries = this._getSelectedEntries();
9758
+ const focusedElement = this._shadow.activeElement;
9759
+ const focusedSelectedKey = focusedElement?.classList.contains('selection-badge-label')
9760
+ ? this._selectedLabelKeys.get(focusedElement) ?? null
9761
+ : null;
9762
+ const focusedBadge = focusedElement?.closest('.selection-badge');
9763
+ const focusedChipKey = focusedBadge
9764
+ ? Array.from(this._chipElements.entries()).find(([, badge]) => badge === focusedBadge)?.[0] ?? null
9765
+ : null;
9766
+ const focusedBadgeIndex = focusedBadge ? this._getActiveChipBadges().indexOf(focusedBadge) : -1;
8495
9767
  const selectedItems = selectedEntries.map(({ item }) => item);
8496
9768
  const nextKeys = new Set(selectedEntries.map(({ key }) => key));
8497
9769
  const previousKeys = this._lastRenderedChipKeys;
@@ -8507,73 +9779,27 @@
8507
9779
  // Only a newly added selected key can initiate auto-scroll.
8508
9780
  this._cancelLatestChipScroll();
8509
9781
  const getLabel = this._config.serverSide.getLabelFromItem || ((item) => item?.label ?? String(item));
8510
- if (selectedItems.length === 0) {
8511
- this._input.value = '';
8512
- this._input.placeholder = this._config.placeholder || 'Select an option...';
8513
- // Clear any badges
8514
- const existingBadges = this._inputContent.querySelectorAll('.selection-badge');
8515
- existingBadges.forEach(badge => badge.remove());
8516
- }
8517
- else if (this._config.selection.mode === 'single') {
8518
- this._input.value = getLabel(selectedItems[0]);
9782
+ if (this._config.selection.mode === 'multi') {
9783
+ if (selectedItems.length === 0) {
9784
+ this._input.value = '';
9785
+ this._input.placeholder = this._config.placeholder || 'Select an option...';
9786
+ }
9787
+ else {
9788
+ this._input.value = '';
9789
+ this._input.placeholder = '';
9790
+ }
9791
+ this._renderSelectedChips(selectedEntries);
8519
9792
  }
8520
9793
  else {
8521
- // Multi-select: show badges instead of text in input
8522
- this._input.value = '';
8523
- this._input.placeholder = '';
8524
- // Clear existing badges
8525
- const existingBadges = this._inputContent.querySelectorAll('.selection-badge');
8526
- existingBadges.forEach(badge => badge.remove());
8527
- // Create badges for each selected item
8528
- selectedEntries.forEach(({ key, index, item }) => {
8529
- const badge = document.createElement('span');
8530
- badge.className = 'selection-badge';
8531
- if (this._config.styles.classNames?.badge) {
8532
- badge.classList.add(...this._config.styles.classNames.badge.split(' ').filter(Boolean));
8533
- }
8534
- badge.setAttribute('part', 'chip');
8535
- const badgeLabel = document.createElement('span');
8536
- badgeLabel.className = 'selection-badge-label';
8537
- if (this._config.styles.classNames?.badgeLabel) {
8538
- badgeLabel.classList.add(...this._config.styles.classNames.badgeLabel.split(' ').filter(Boolean));
8539
- }
8540
- badgeLabel.setAttribute('part', 'chip-label');
8541
- badgeLabel.textContent = getLabel(item);
8542
- badge.appendChild(badgeLabel);
8543
- // Add remove button to badge
8544
- if (this._config.selection.showRemoveButton !== false) {
8545
- const removeBtn = document.createElement('button');
8546
- removeBtn.type = 'button';
8547
- removeBtn.className = 'badge-remove';
8548
- if (this._config.styles.classNames?.removeButton) {
8549
- removeBtn.classList.add(...this._config.styles.classNames.removeButton.split(' ').filter(Boolean));
8550
- }
8551
- if (this._config.styles.classNames?.badgeRemove) {
8552
- removeBtn.classList.add(...this._config.styles.classNames.badgeRemove.split(' ').filter(Boolean));
8553
- }
8554
- removeBtn.setAttribute('part', 'chip-remove');
8555
- removeBtn.setAttribute('aria-label', `Remove ${getLabel(item)}`);
8556
- const removeIcon = document.createElement('span');
8557
- removeIcon.className = 'badge-remove-icon';
8558
- if (this._config.styles.classNames?.badgeRemoveIcon) {
8559
- removeIcon.classList.add(...this._config.styles.classNames.badgeRemoveIcon.split(' ').filter(Boolean));
8560
- }
8561
- removeIcon.setAttribute('part', 'chip-remove-icon');
8562
- this._setIconContent(removeIcon, this._config.selection.removeButtonIcon, '×');
8563
- removeBtn.appendChild(removeIcon);
8564
- removeBtn.addEventListener('pointerdown', (e) => {
8565
- e.stopPropagation();
8566
- e.preventDefault();
8567
- });
8568
- removeBtn.addEventListener('click', (e) => {
8569
- e.stopPropagation();
8570
- e.preventDefault();
8571
- this._handleOptionRemove(index, key);
8572
- });
8573
- badge.appendChild(removeBtn);
8574
- }
8575
- this._inputContent.insertBefore(badge, this._input);
8576
- });
9794
+ // A mode switch ends visual exits immediately; a single-select has no chip presentation.
9795
+ this._clearChipPresentation();
9796
+ if (selectedItems.length === 0) {
9797
+ this._input.value = '';
9798
+ this._input.placeholder = this._config.placeholder || 'Select an option...';
9799
+ }
9800
+ else {
9801
+ this._input.value = getLabel(selectedItems[0]);
9802
+ }
8577
9803
  }
8578
9804
  // A query typed during an accepted-snapshot projection is a pending user
8579
9805
  // intent, not part of the committed projection state. Keep it visible even
@@ -8581,14 +9807,60 @@
8581
9807
  if (this._acknowledgedPendingSearchQuery !== null) {
8582
9808
  this._input.value = this._acknowledgedPendingSearchQuery;
8583
9809
  }
8584
- // Recreating the chip DOM must not reset manual scrolling. In particular,
8585
- // remove/clear, config rerenders, and item refreshes are not scroll intents.
9810
+ // Preserve manual scrolling. Only a newly selected key can request auto-scroll.
8586
9811
  if (this._config.selection.mode === 'multi') {
8587
9812
  this._inputContent.scrollLeft = previousChipScrollLeft;
8588
9813
  if (newlyAddedKey !== undefined)
8589
9814
  this._scheduleLatestChipScroll(newlyAddedKey);
8590
9815
  }
8591
9816
  this._syncClearControlState();
9817
+ this._observeSelectedLabelTooltipTargets();
9818
+ this._refreshSelectedLabelTooltipMeasurements();
9819
+ if (focusedChipKey !== null && !nextKeys.has(focusedChipKey)) {
9820
+ const removeButtons = this._getActiveChipRemoveButtons();
9821
+ if (removeButtons.length > 0) {
9822
+ const nextFocusIndex = Math.min(Math.max(focusedBadgeIndex, 0), removeButtons.length - 1);
9823
+ removeButtons[nextFocusIndex].focus({ preventScroll: true });
9824
+ }
9825
+ else {
9826
+ this._input.focus({ preventScroll: true });
9827
+ }
9828
+ }
9829
+ else if (focusedChipKey !== null && focusedElement && !focusedElement.isConnected) {
9830
+ const badge = this._chipElements.get(focusedChipKey);
9831
+ const removeButton = badge?.querySelector('[part="chip-remove"]');
9832
+ if (removeButton && !removeButton.disabled)
9833
+ removeButton.focus({ preventScroll: true });
9834
+ else
9835
+ this._input.focus({ preventScroll: true });
9836
+ }
9837
+ else if (focusedSelectedKey !== null) {
9838
+ const replacement = this._getActiveChipBadges()
9839
+ .map((badge) => badge.querySelector('.selection-badge-label'))
9840
+ .find((label) => label && this._selectedLabelKeys.get(label) === focusedSelectedKey);
9841
+ if (!replacement) {
9842
+ const removeButtons = this._getActiveChipRemoveButtons();
9843
+ if (removeButtons.length > 0) {
9844
+ const nextFocusIndex = Math.min(Math.max(focusedBadgeIndex, 0), removeButtons.length - 1);
9845
+ removeButtons[nextFocusIndex].focus({ preventScroll: true });
9846
+ }
9847
+ else {
9848
+ this._input.focus({ preventScroll: true });
9849
+ }
9850
+ }
9851
+ else if (this._isSelectedLabelTruncated(replacement)) {
9852
+ // The measurement pass assigns the tab stop before focus restoration.
9853
+ replacement.tabIndex = 0;
9854
+ replacement.focus({ preventScroll: true });
9855
+ }
9856
+ else {
9857
+ this._input.focus({ preventScroll: true });
9858
+ }
9859
+ }
9860
+ if (this._selectedLabelTooltipFocusTrigger === this._input
9861
+ || this._selectedLabelTooltipPointerTrigger === this._input) {
9862
+ this._showSelectedLabelTooltip(this._input);
9863
+ }
8592
9864
  }
8593
9865
  _cancelLatestChipScroll() {
8594
9866
  this._latestChipScrollGeneration += 1;
@@ -8620,7 +9892,7 @@
8620
9892
  const index = entries.findIndex((entry) => entry.key === key);
8621
9893
  if (index < 0)
8622
9894
  return;
8623
- const chip = this._inputContent.querySelectorAll('.selection-badge')[index];
9895
+ const chip = this._getActiveChipBadges()[index];
8624
9896
  if (!chip)
8625
9897
  return;
8626
9898
  const hostBounds = this._inputContent.getBoundingClientRect();
@@ -8678,58 +9950,71 @@
8678
9950
  this._optionsContainer.style.transition = 'opacity 0.2s ease-in';
8679
9951
  }, 150);
8680
9952
  }
8681
- _scrollToSelected() {
8682
- if (this._state.selectedIndices.size === 0)
8683
- return;
8684
- const target = this._config.scrollToSelected.multiSelectTarget;
8685
- const indices = Array.from(this._state.selectedIndices).filter((index) => index >= 0).sort((a, b) => a - b);
8686
- if (indices.length === 0)
8687
- return;
8688
- // For multi-select, find the closest selected item to the current scroll position
8689
- let targetIndex;
8690
- if (this._config.selection.mode === 'multi' && indices.length > 1) {
8691
- // Calculate which selected item is closest to the center of the viewport
8692
- const dropdownRect = this._dropdown.getBoundingClientRect();
8693
- const viewportCenter = this._dropdown.scrollTop + (dropdownRect.height / 2);
8694
- // Find the selected item closest to viewport center
8695
- let closestIndex = indices[0];
8696
- let closestDistance = Infinity;
8697
- for (const index of indices) {
8698
- const option = this._getOptionElementByIndex(index);
8699
- if (option) {
8700
- const optionTop = option.offsetTop;
8701
- const distance = Math.abs(optionTop - viewportCenter);
8702
- if (distance < closestDistance) {
8703
- closestDistance = distance;
8704
- closestIndex = index;
8705
- }
8706
- }
8707
- }
8708
- targetIndex = closestIndex;
8709
- }
8710
- else {
8711
- // For single select or only one selected item, use the configured target
8712
- targetIndex = target === 'first' ? indices[0] : indices[indices.length - 1];
8713
- }
8714
- // Find and scroll to the target option
9953
+ _scrollToSelected(options = {}) {
9954
+ const config = options.config ?? this._config.scrollToSelected;
9955
+ if (!config.enabled)
9956
+ return;
9957
+ const targetKey = resolveSelectedTargetKey(this._renderPlan.filteredKeys, this._engine.state.selectedKeys, config.multiSelectTarget);
9958
+ if (targetKey === null)
9959
+ return;
9960
+ const targetIndex = this._renderPlan.sourceIndexByKey.get(targetKey)
9961
+ ?? this._itemRegistry.keyToIndex.get(targetKey);
9962
+ if (targetIndex === undefined)
9963
+ return;
9964
+ // Resolve against the current eligible render plan first. A selected key
9965
+ // outside the filtered projection must never trigger materialization.
8715
9966
  let option = this._getOptionElementByIndex(targetIndex);
8716
9967
  if (!option && this._guardedVirtualizer) {
8717
- const targetKey = this._itemRegistry.indexToKey.get(targetIndex);
8718
- if (targetKey !== undefined) {
8719
- this._materializeGuardedVirtualKey(targetKey);
8720
- option = this._getOptionElementByIndex(targetIndex);
8721
- }
9968
+ this._materializeGuardedVirtualKey(targetKey);
9969
+ option = this._getOptionElementByIndex(targetIndex);
8722
9970
  }
8723
9971
  if (option) {
8724
- // Use smooth scrolling with center alignment for better UX
8725
- if (typeof option.scrollIntoView === 'function') {
8726
- option.scrollIntoView({
8727
- block: this._config.scrollToSelected.block || 'center',
8728
- behavior: 'smooth',
8729
- });
9972
+ const reducedMotion = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches ?? false;
9973
+ this._scrollOptionWithinOptionsContainer(option, config.block || 'nearest', reducedMotion && config.behavior === 'smooth' ? 'auto' : (config.behavior || 'smooth'), options.onlyIfNeeded === true);
9974
+ if (options.setActive !== false) {
9975
+ // Active/ARIA synchronization must not start a second physical scroll.
9976
+ this._setActive(targetIndex, 'programmatic', { scroll: false });
8730
9977
  }
8731
- // Also set it as active for keyboard navigation
8732
- this._setActive(targetIndex, 'programmatic');
9978
+ }
9979
+ }
9980
+ _scrollOptionWithinOptionsContainer(option, block, behavior, onlyIfNeeded) {
9981
+ const scroller = this._optionsContainer;
9982
+ const scrollerRect = scroller.getBoundingClientRect();
9983
+ const viewportTop = scrollerRect.top + scroller.clientTop;
9984
+ const viewportBottom = viewportTop + scroller.clientHeight;
9985
+ const optionRect = option.getBoundingClientRect();
9986
+ if (onlyIfNeeded && optionRect.top >= viewportTop && optionRect.bottom <= viewportBottom)
9987
+ return;
9988
+ if (scroller.clientHeight <= 0 || optionRect.height <= 0)
9989
+ return;
9990
+ let targetScrollTop = scroller.scrollTop;
9991
+ if (block === 'start') {
9992
+ targetScrollTop += optionRect.top - viewportTop;
9993
+ }
9994
+ else if (block === 'center') {
9995
+ targetScrollTop += (optionRect.top + optionRect.bottom - viewportTop - viewportBottom) / 2;
9996
+ }
9997
+ else if (block === 'end') {
9998
+ targetScrollTop += optionRect.bottom - viewportBottom;
9999
+ }
10000
+ else if (optionRect.top < viewportTop) {
10001
+ targetScrollTop += optionRect.top - viewportTop;
10002
+ }
10003
+ else if (optionRect.bottom > viewportBottom) {
10004
+ targetScrollTop += optionRect.bottom - viewportBottom;
10005
+ }
10006
+ else {
10007
+ return;
10008
+ }
10009
+ const maxScrollTop = Math.max(0, scroller.scrollHeight - scroller.clientHeight);
10010
+ targetScrollTop = Math.max(0, Math.min(targetScrollTop, maxScrollTop));
10011
+ if (Math.abs(targetScrollTop - scroller.scrollTop) < 1)
10012
+ return;
10013
+ if (typeof scroller.scrollTo === 'function') {
10014
+ scroller.scrollTo({ top: targetScrollTop, behavior });
10015
+ }
10016
+ else {
10017
+ scroller.scrollTop = targetScrollTop;
8733
10018
  }
8734
10019
  }
8735
10020
  async _loadMoreItems(trigger = 'manual') {
@@ -9215,10 +10500,21 @@
9215
10500
  this._invalidateGuardedMeasurements();
9216
10501
  const previousMode = this._config.selection.mode;
9217
10502
  const previousEnabled = this._config.enabled;
10503
+ const previousOpenScrollEnabled = this._config.scrollToSelected.enabled;
9218
10504
  const previousDataLoadingConfig = this._dataLoadingConfig;
9219
10505
  let searchEligibilityBecameInactive = false;
9220
- const { dataLoading, callbacks, ...legacyConfig } = config;
10506
+ const { dataLoading, callbacks, selectedOptions, scrollToSelected, ...legacyConfig } = config;
9221
10507
  const legacyUpdate = { ...legacyConfig };
10508
+ if (selectedOptions !== undefined) {
10509
+ const validation = validateSelectedOptionsConfig(selectedOptions);
10510
+ if (validation.valid)
10511
+ legacyUpdate.selectedOptions = validation.value;
10512
+ }
10513
+ if (scrollToSelected !== undefined) {
10514
+ const validation = validateScrollToSelectedConfig(scrollToSelected);
10515
+ if (validation.valid)
10516
+ legacyUpdate.scrollToSelected = validation.value;
10517
+ }
9222
10518
  let configErrorDetail;
9223
10519
  if (callbacks !== undefined && callbacks !== null) {
9224
10520
  const callbackInput = callbacks;
@@ -9238,6 +10534,10 @@
9238
10534
  legacyUpdate.callbacks = legacyCallbacks;
9239
10535
  }
9240
10536
  this._config = this._mergeConfig(this._config, legacyUpdate);
10537
+ if (previousOpenScrollEnabled && !this._config.scrollToSelected.enabled) {
10538
+ this._openOptionsViewportAnchor = null;
10539
+ this._cancelOpenSelectedScroll();
10540
+ }
9241
10541
  if (dataLoading !== undefined) {
9242
10542
  const dataLoadingPrototype = dataLoading !== null && typeof dataLoading === 'object'
9243
10543
  ? Object.getPrototypeOf(dataLoading)
@@ -9784,19 +11084,39 @@
9784
11084
  activeKey: this._engine.state.activeKey,
9785
11085
  };
9786
11086
  }
9787
- _createLegacyRenderPlan(filteredIndices) {
9788
- const indices = [...filteredIndices];
9789
- const filteredKeys = indices
9790
- .map((index) => this._itemRegistry.indexToKey.get(index))
9791
- .filter((key) => key !== undefined);
9792
- const filteredIndexByKey = new Map();
9793
- filteredKeys.forEach((key, filteredIndex) => filteredIndexByKey.set(key, filteredIndex));
11087
+ _createLegacyRenderPlan(filteredIndices, groupedPresentation = []) {
11088
+ const sourceIndices = [...filteredIndices];
11089
+ const sourceOrderedKeys = groupedPresentation.length > 0
11090
+ ? groupedPresentation.flatMap((group) => group.orderedKeys)
11091
+ : sourceIndices
11092
+ .map((index) => this._itemRegistry.indexToKey.get(index))
11093
+ .filter((key) => key !== undefined);
11094
+ const shouldProjectSelectedFirst = this._usesSelectedFirstVisualOrder()
11095
+ && groupedPresentation.length === 0;
11096
+ const selectedKeys = this._selectedOptionsSelectionAtOpen ?? this._engine.state.selectedKeys;
11097
+ const filteredKeys = shouldProjectSelectedFirst
11098
+ ? projectSelectedOptionKeys(sourceOrderedKeys, selectedKeys)
11099
+ : sourceOrderedKeys;
11100
+ const indices = filteredKeys
11101
+ .map((key) => this._itemRegistry.keyToIndex.get(key))
11102
+ .filter((index) => index !== undefined);
11103
+ const displayIndexByKey = new Map();
11104
+ const sourceIndexByKey = new Map();
11105
+ filteredKeys.forEach((key, displayIndex) => {
11106
+ displayIndexByKey.set(key, displayIndex);
11107
+ const sourceIndex = this._itemRegistry.keyToIndex.get(key);
11108
+ if (sourceIndex !== undefined)
11109
+ sourceIndexByKey.set(key, sourceIndex);
11110
+ });
9794
11111
  return {
9795
11112
  mode: 'legacy-full',
9796
11113
  filteredIndices: indices,
9797
11114
  filteredKeys,
9798
11115
  intendedRenderKeys: filteredKeys.slice(),
9799
- filteredIndexByKey,
11116
+ displayIndexByKey,
11117
+ sourceIndexByKey,
11118
+ filteredIndexByKey: displayIndexByKey,
11119
+ groupedPresentation,
9800
11120
  };
9801
11121
  }
9802
11122
  _createVirtualRenderPlan(startIndex, endIndex) {
@@ -9805,12 +11125,16 @@
9805
11125
  const filteredIndices = intendedRenderKeys
9806
11126
  .map((key) => this._itemRegistry.keyToIndex.get(key))
9807
11127
  .filter((index) => index !== undefined);
11128
+ const displayIndexByKey = new Map(this._renderPlan.displayIndexByKey);
9808
11129
  return {
9809
11130
  mode: 'virtual-window',
9810
11131
  filteredIndices,
9811
11132
  filteredKeys,
9812
11133
  intendedRenderKeys,
9813
- filteredIndexByKey: new Map(this._renderPlan.filteredIndexByKey),
11134
+ displayIndexByKey,
11135
+ sourceIndexByKey: new Map(this._renderPlan.sourceIndexByKey),
11136
+ filteredIndexByKey: displayIndexByKey,
11137
+ groupedPresentation: this._renderPlan.groupedPresentation,
9814
11138
  };
9815
11139
  }
9816
11140
  _ensureGuardedVirtualizer(filteredKeys) {
@@ -10764,11 +12088,31 @@
10764
12088
  // Handle Grouped Items Rendering (when no search query)
10765
12089
  if (this._state.groupedItems.length > 0 && !query) {
10766
12090
  this._destroyGuardedVirtualizer();
10767
- this._renderPlan = this._createLegacyRenderPlan(this._itemRegistry.records.map((record) => record.index));
12091
+ const groupedSource = this._state.groupedItems.map((group, groupIndex) => ({
12092
+ group,
12093
+ groupIndex,
12094
+ orderedKeys: group.options
12095
+ .map((item) => this._state.loadedItems.indexOf(item))
12096
+ .filter((index) => index >= 0)
12097
+ .map((index) => this._itemRegistry.indexToKey.get(index))
12098
+ .filter((key) => key !== undefined),
12099
+ }));
12100
+ const groupedOrder = this._usesSelectedFirstVisualOrder()
12101
+ ? projectSelectedOptionGroups(groupedSource.map(({ groupIndex, orderedKeys }) => ({ groupIdentity: groupIndex, orderedKeys })), this._selectedOptionsSelectionAtOpen ?? this._engine.state.selectedKeys)
12102
+ : groupedSource.map(({ groupIndex, orderedKeys }) => ({ groupIdentity: groupIndex, orderedKeys }));
12103
+ const groupedPresentation = groupedOrder.map(({ groupIdentity, orderedKeys }) => ({
12104
+ group: this._state.groupedItems[groupIdentity],
12105
+ groupIndex: groupIdentity,
12106
+ orderedKeys,
12107
+ }));
12108
+ const groupedIndices = groupedPresentation.flatMap(({ orderedKeys }) => orderedKeys
12109
+ .map((key) => this._itemRegistry.keyToIndex.get(key))
12110
+ .filter((index) => index !== undefined));
12111
+ this._renderPlan = this._createLegacyRenderPlan(groupedIndices, groupedPresentation);
10768
12112
  filteredIndicesForScope = this._renderPlan.filteredIndices;
10769
12113
  this._registerShadowItems(filteredIndicesForScope);
10770
12114
  this._refreshVirtualizationScope(filteredIndicesForScope);
10771
- this._state.groupedItems.forEach((group, groupIndex) => {
12115
+ this._renderPlan.groupedPresentation.forEach(({ group, groupIndex, orderedKeys }) => {
10772
12116
  let header;
10773
12117
  if (this.groupHeaderRenderer) {
10774
12118
  header = this.groupHeaderRenderer(group, groupIndex);
@@ -10794,10 +12138,10 @@
10794
12138
  }
10795
12139
  header.setAttribute('part', 'group-header');
10796
12140
  this._optionsContainer.appendChild(header);
10797
- group.options.forEach(item => {
10798
- // Find original index for correct ID generation and selection
10799
- const index = this._state.loadedItems.indexOf(item);
10800
- if (index !== -1) {
12141
+ orderedKeys.forEach((key) => {
12142
+ const index = this._itemRegistry.keyToIndex.get(key);
12143
+ if (index !== undefined) {
12144
+ const item = this._state.loadedItems[index];
10801
12145
  this._renderSingleOption(item, index, getValue, getLabel);
10802
12146
  }
10803
12147
  });
@@ -10866,13 +12210,16 @@
10866
12210
  const chunkSize = 80;
10867
12211
  let cursor = 0;
10868
12212
  let maxRenderTarget = 0;
10869
- if (this._state.selectedIndices.size > 0 && this._config.scrollToSelected.enabled) {
10870
- const indices = Array.from(this._state.selectedIndices).filter((index) => index >= 0).sort((a, b) => a - b);
10871
- const targetIndex = this._config.scrollToSelected.multiSelectTarget === 'first' ? indices[0] : indices[indices.length - 1];
10872
- const filteredPos = filteredIndices.indexOf(targetIndex);
10873
- if (filteredPos !== -1) {
10874
- maxRenderTarget = filteredPos + 20; // Ensure we render up to the selection
10875
- }
12213
+ if (this._state.isOpen
12214
+ && this._config.scrollToSelected.enabled
12215
+ && this._scrollToSelectedConfigAtOpen.enabled
12216
+ && this._scrollToSelectedConfigAtOpen.onOpen !== 'preserve') {
12217
+ const targetKey = resolveSelectedTargetKey(this._renderPlan.filteredKeys, this._engine.state.selectedKeys, this._scrollToSelectedConfigAtOpen.multiSelectTarget);
12218
+ const targetPosition = targetKey === null
12219
+ ? undefined
12220
+ : this._renderPlan.displayIndexByKey.get(targetKey);
12221
+ if (targetPosition !== undefined)
12222
+ maxRenderTarget = targetPosition + 20;
10876
12223
  }
10877
12224
  const renderChunk = () => {
10878
12225
  if (renderCycleId !== this._renderCycleId) {
@@ -12382,6 +13729,9 @@
12382
13729
  exports.toggleClass = toggleClass;
12383
13730
  exports.transition = transition;
12384
13731
  exports.validateDataLoadingConfig = validateDataLoadingConfig;
13732
+ exports.validateScrollToSelectedConfig = validateScrollToSelectedConfig;
13733
+ exports.validateSelectedOptionsConfig = validateSelectedOptionsConfig;
13734
+ exports.validateSelectedOptionsConfigUpdate = validateSelectedOptionsConfigUpdate;
12385
13735
  exports.validateTemplate = validateTemplate;
12386
13736
  exports.valuesEqual = valuesEqual;
12387
13737
  exports.warnCSPViolation = warnCSPViolation;