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