@smilodon/core 1.19.0 → 1.20.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
@@ -4253,8 +4464,27 @@ class EnhancedSelect extends HTMLElement {
4253
4464
  filteredIndices: [],
4254
4465
  filteredKeys: [],
4255
4466
  intendedRenderKeys: [],
4467
+ displayIndexByKey: new Map(),
4468
+ sourceIndexByKey: new Map(),
4256
4469
  filteredIndexByKey: new Map(),
4470
+ groupedPresentation: [],
4471
+ };
4472
+ // Presentation policy and membership are snapshotted when the dropdown opens
4473
+ // so selection/config updates cannot reorder an active list.
4474
+ this._selectedOptionsSelectionAtOpen = null;
4475
+ this._selectedOptionsConfigAtOpen = {
4476
+ placement: 'original',
4477
+ groupedPlacement: 'within-group',
4478
+ };
4479
+ this._scrollToSelectedConfigAtOpen = {
4480
+ enabled: true,
4481
+ multiSelectTarget: 'first',
4482
+ onOpen: 'reveal',
4483
+ behavior: 'smooth',
4484
+ block: 'nearest',
4257
4485
  };
4486
+ this._closedOptionsViewportAnchor = null;
4487
+ this._openOptionsViewportAnchor = null;
4258
4488
  this._emptyStateContext = null;
4259
4489
  // Null keeps the public/default renderer on its legacy full path. This
4260
4490
  // private state is only used by guarded virtualization integration.
@@ -4311,7 +4541,7 @@ class EnhancedSelect extends HTMLElement {
4311
4541
  this._boundArrowClick = null;
4312
4542
  this._pendingFirstRenderMark = false;
4313
4543
  this._pendingSearchRenderMark = false;
4314
- this._rangeAnchorIndex = null;
4544
+ this._rangeAnchorKey = null;
4315
4545
  /** Chip identity is tracked independently of dropdown option positions. */
4316
4546
  this._lastRenderedChipKeys = null;
4317
4547
  this._latestChipScrollGeneration = 0;
@@ -4329,6 +4559,9 @@ class EnhancedSelect extends HTMLElement {
4329
4559
  this._lifecycleTimers = new Set();
4330
4560
  this._lifecycleRafs = new Set();
4331
4561
  this._keyboardActiveChangeGeneration = 0;
4562
+ /** Invalidates selected-option positioning scheduled by an earlier opening. */
4563
+ this._openSelectedScrollGeneration = 0;
4564
+ this._openSelectedScrollCleanup = null;
4332
4565
  this._tracking = { events: [], styles: [], limitations: [] };
4333
4566
  this._suppressBlurClose = false;
4334
4567
  this._renderCycleId = 0;
@@ -4506,6 +4739,7 @@ class EnhancedSelect extends HTMLElement {
4506
4739
  this._syncListboxAccessibility();
4507
4740
  }
4508
4741
  disconnectedCallback() {
4742
+ this._cancelOpenSelectedScroll();
4509
4743
  this._cancelLatestChipScroll();
4510
4744
  this._cancelBusyPresentation();
4511
4745
  if (this._dataRequestCoordinator) {
@@ -5092,12 +5326,12 @@ class EnhancedSelect extends HTMLElement {
5092
5326
  duplicateKeyPolicy: this._getDuplicateKeyPolicy(),
5093
5327
  });
5094
5328
  const activeKey = this._engine.state.activeKey;
5095
- const anchorKey = this._rangeAnchorIndex === null ? undefined : this._itemRegistry.indexToKey.get(this._rangeAnchorIndex);
5329
+ const anchorKey = this._rangeAnchorKey;
5096
5330
  this._itemRegistry = registry;
5097
5331
  this._state.loadedItems = items;
5098
5332
  this._registryItemsRef = items;
5099
5333
  const disabledKeys = this._getBlockedDisabledKeys();
5100
- this._rangeAnchorIndex = anchorKey === undefined ? null : registry.keyToIndex.get(anchorKey) ?? null;
5334
+ this._rangeAnchorKey = anchorKey !== null && registry.keyToRecord.has(anchorKey) ? anchorKey : null;
5101
5335
  this._engine.dispatch({
5102
5336
  type: 'ITEMS_REGISTERED',
5103
5337
  keys: registry.records.map((record) => record.key),
@@ -7642,6 +7876,15 @@ class EnhancedSelect extends HTMLElement {
7642
7876
  this._dropdown.removeAttribute('inert');
7643
7877
  this._dropdown.removeAttribute('aria-hidden');
7644
7878
  this._markOpenStart();
7879
+ this._scrollToSelectedConfigAtOpen = { ...this._config.scrollToSelected };
7880
+ this._openOptionsViewportAnchor = this._scrollToSelectedConfigAtOpen.onOpen === 'preserve'
7881
+ ? (this._closedOptionsViewportAnchor ?? this._captureOptionsViewportAnchor())
7882
+ : null;
7883
+ this._closedOptionsViewportAnchor = null;
7884
+ this._selectedOptionsConfigAtOpen = { ...this._config.selectedOptions };
7885
+ this._selectedOptionsSelectionAtOpen = this._config.selectedOptions.placement === 'selected-first'
7886
+ ? new Set(this._engine.state.selectedKeys)
7887
+ : null;
7645
7888
  this.setAttribute('data-open', 'true');
7646
7889
  this._liftStackingAncestors();
7647
7890
  this._dropdown.style.display = 'block';
@@ -7653,28 +7896,17 @@ class EnhancedSelect extends HTMLElement {
7653
7896
  this._emit('open', {});
7654
7897
  this._config.callbacks.onOpen?.();
7655
7898
  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
- }
7899
+ this._scheduleOpenSelectedScroll();
7673
7900
  }
7674
7901
  _handleClose(reason = 'programmatic') {
7902
+ if (this._state.isOpen) {
7903
+ this._closedOptionsViewportAnchor = this._captureOptionsViewportAnchor();
7904
+ }
7675
7905
  const effects = this._engine.dispatch({ type: 'CLOSE_REQUEST', reason });
7676
7906
  if (!effects.some((effect) => effect.type === 'POPUP_CLOSED'))
7677
7907
  return;
7908
+ this._cancelOpenSelectedScroll();
7909
+ this._selectedOptionsSelectionAtOpen = null;
7678
7910
  this.removeAttribute('data-open');
7679
7911
  this._restoreLiftedAncestors();
7680
7912
  this._dropdown.setAttribute('data-placement', this._resolvedDropdownPlacement);
@@ -7686,6 +7918,257 @@ class EnhancedSelect extends HTMLElement {
7686
7918
  this._config.callbacks.onClose?.();
7687
7919
  this._announce('Options collapsed');
7688
7920
  }
7921
+ /**
7922
+ * Defer the one automatic selected-option positioning operation until the
7923
+ * dropdown's own entrance geometry has settled. Logical active/ARIA state
7924
+ * remains synchronous in _setInitialActiveOption().
7925
+ */
7926
+ _scheduleOpenSelectedScroll() {
7927
+ this._cancelOpenSelectedScroll();
7928
+ const openingConfig = this._scrollToSelectedConfigAtOpen;
7929
+ if (!openingConfig.enabled)
7930
+ return;
7931
+ const generation = this._openSelectedScrollGeneration;
7932
+ const keyboardGeneration = this._keyboardActiveChangeGeneration;
7933
+ const initialScrollTop = this._optionsContainer.scrollTop;
7934
+ const animations = [];
7935
+ const frameIds = new Set();
7936
+ let timerId = null;
7937
+ let completed = false;
7938
+ const isCurrent = () => generation === this._openSelectedScrollGeneration
7939
+ && this._state.isOpen
7940
+ && this.isConnected
7941
+ && this._config.scrollToSelected.enabled
7942
+ && keyboardGeneration === this._keyboardActiveChangeGeneration;
7943
+ const removeListeners = () => {
7944
+ this._optionsContainer.removeEventListener('wheel', cancelForUserInput);
7945
+ this._optionsContainer.removeEventListener('touchstart', cancelForUserInput);
7946
+ this._optionsContainer.removeEventListener('pointerdown', cancelForUserInput);
7947
+ this._optionsContainer.removeEventListener('scroll', cancelForUserScroll);
7948
+ for (const animation of animations) {
7949
+ animation.removeEventListener('finish', onAnimationStateChange);
7950
+ animation.removeEventListener('cancel', onAnimationStateChange);
7951
+ }
7952
+ };
7953
+ const cleanup = () => {
7954
+ removeListeners();
7955
+ for (const id of frameIds)
7956
+ cancelAnimationFrame(id);
7957
+ frameIds.clear();
7958
+ if (timerId !== null) {
7959
+ clearTimeout(timerId);
7960
+ this._lifecycleTimers.delete(timerId);
7961
+ timerId = null;
7962
+ }
7963
+ if (this._openSelectedScrollCleanup === cleanup) {
7964
+ this._openSelectedScrollCleanup = null;
7965
+ }
7966
+ };
7967
+ const cancelForUserInput = () => this._cancelOpenSelectedScroll();
7968
+ const cancelForUserScroll = () => {
7969
+ if (Math.abs(this._optionsContainer.scrollTop - initialScrollTop) > 1) {
7970
+ this._cancelOpenSelectedScroll();
7971
+ }
7972
+ };
7973
+ const finish = () => {
7974
+ if (completed)
7975
+ return;
7976
+ completed = true;
7977
+ cleanup();
7978
+ if (!isCurrent())
7979
+ return;
7980
+ const frameId = requestAnimationFrame(() => {
7981
+ frameIds.delete(frameId);
7982
+ cleanup();
7983
+ if (!isCurrent())
7984
+ return;
7985
+ if (openingConfig.onOpen === 'preserve') {
7986
+ this._restorePreservedOptionsViewport();
7987
+ }
7988
+ else {
7989
+ this._scrollToSelected({
7990
+ onlyIfNeeded: openingConfig.onOpen === 'reveal',
7991
+ setActive: false,
7992
+ config: openingConfig,
7993
+ });
7994
+ }
7995
+ });
7996
+ frameIds.add(frameId);
7997
+ this._openSelectedScrollCleanup = cleanup;
7998
+ };
7999
+ const onAnimationStateChange = () => {
8000
+ if (animations.every((animation) => animation.playState === 'finished' || animation.playState === 'idle'))
8001
+ finish();
8002
+ };
8003
+ const begin = () => {
8004
+ if (!isCurrent()) {
8005
+ cleanup();
8006
+ return;
8007
+ }
8008
+ const getAnimations = this._dropdown.getAnimations;
8009
+ const reducedMotion = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches ?? false;
8010
+ if (!reducedMotion && typeof getAnimations === 'function') {
8011
+ for (const animation of getAnimations.call(this._dropdown)) {
8012
+ const timing = animation.effect?.getComputedTiming();
8013
+ if (!timing || timing.iterations === Infinity || animation.playState === 'finished'
8014
+ || animation.playState === 'idle')
8015
+ continue;
8016
+ animations.push(animation);
8017
+ }
8018
+ }
8019
+ if (animations.length === 0) {
8020
+ if (!reducedMotion && typeof getAnimations !== 'function') {
8021
+ const fallbackWait = this._getDropdownEntranceFallbackDurationMs();
8022
+ if (fallbackWait > 0) {
8023
+ timerId = window.setTimeout(finish, fallbackWait + 34);
8024
+ this._lifecycleTimers.add(timerId);
8025
+ return;
8026
+ }
8027
+ }
8028
+ finish();
8029
+ return;
8030
+ }
8031
+ for (const animation of animations) {
8032
+ animation.addEventListener('finish', onAnimationStateChange);
8033
+ animation.addEventListener('cancel', onAnimationStateChange);
8034
+ }
8035
+ const remainingMs = Math.max(...animations.map((animation) => {
8036
+ const timing = animation.effect?.getComputedTiming();
8037
+ const endTime = Number(timing?.endTime);
8038
+ const currentTime = Number(animation.currentTime ?? 0);
8039
+ return Number.isFinite(endTime) ? Math.max(0, endTime - currentTime) : 0;
8040
+ }));
8041
+ const boundedWait = Math.min(10000, remainingMs + 50);
8042
+ timerId = window.setTimeout(finish, boundedWait);
8043
+ this._lifecycleTimers.add(timerId);
8044
+ };
8045
+ this._optionsContainer.addEventListener('wheel', cancelForUserInput, { passive: true });
8046
+ this._optionsContainer.addEventListener('touchstart', cancelForUserInput, { passive: true });
8047
+ this._optionsContainer.addEventListener('pointerdown', cancelForUserInput, { passive: true });
8048
+ this._optionsContainer.addEventListener('scroll', cancelForUserScroll, { passive: true });
8049
+ this._openSelectedScrollCleanup = cleanup;
8050
+ const frameId = requestAnimationFrame(() => {
8051
+ frameIds.delete(frameId);
8052
+ begin();
8053
+ });
8054
+ frameIds.add(frameId);
8055
+ }
8056
+ _cancelOpenSelectedScroll() {
8057
+ this._openSelectedScrollGeneration += 1;
8058
+ this._openSelectedScrollCleanup?.();
8059
+ this._openSelectedScrollCleanup = null;
8060
+ }
8061
+ _captureOptionsViewportAnchor() {
8062
+ const scroller = this._optionsContainer;
8063
+ const scrollTop = scroller.scrollTop;
8064
+ const order = this._renderPlan.filteredKeys.slice();
8065
+ const viewportTop = scroller.getBoundingClientRect().top + scroller.clientTop;
8066
+ const viewportBottom = viewportTop + scroller.clientHeight;
8067
+ const visible = Array.from(scroller.querySelectorAll('[data-sm-selectable], [data-selectable]'))
8068
+ .map((option) => ({ option, rect: option.getBoundingClientRect() }))
8069
+ .filter(({ rect }) => rect.height > 0 && rect.bottom > viewportTop && rect.top < viewportBottom)
8070
+ .sort((left, right) => left.rect.top - right.rect.top)[0];
8071
+ if (visible) {
8072
+ const sourceIndex = Number(visible.option.getAttribute('data-sm-index') ?? visible.option.getAttribute('data-index'));
8073
+ const key = Number.isInteger(sourceIndex) ? this._itemRegistry.indexToKey.get(sourceIndex) ?? null : null;
8074
+ if (key !== null) {
8075
+ return { key, offset: visible.rect.top - viewportTop, scrollTop, order };
8076
+ }
8077
+ }
8078
+ if (this._guardedVirtualizer && order.length > 0
8079
+ && typeof this._guardedVirtualizer.computeWindow === 'function') {
8080
+ const viewportHeight = this._resolveGuardedViewportHeight();
8081
+ const index = this._guardedVirtualizer.computeWindow(scrollTop, viewportHeight).startIndex;
8082
+ const key = order[index] ?? null;
8083
+ if (key !== null) {
8084
+ return {
8085
+ key,
8086
+ offset: this._guardedVirtualizer.cumulativeOffset(index) - scrollTop,
8087
+ scrollTop,
8088
+ order,
8089
+ };
8090
+ }
8091
+ }
8092
+ return { key: null, offset: 0, scrollTop, order };
8093
+ }
8094
+ /** Restore the previous visible option only when this opening changed order. */
8095
+ _restorePreservedOptionsViewport() {
8096
+ const anchor = this._openOptionsViewportAnchor;
8097
+ this._openOptionsViewportAnchor = null;
8098
+ if (!anchor)
8099
+ return;
8100
+ const nextOrder = this._renderPlan.filteredKeys;
8101
+ const nextPositionByKey = new Map(nextOrder.map((key, index) => [key, index]));
8102
+ const orderChanged = anchor.order.some((key, oldIndex) => {
8103
+ const nextIndex = nextPositionByKey.get(key);
8104
+ return nextIndex !== undefined && nextIndex !== oldIndex;
8105
+ });
8106
+ if (!orderChanged)
8107
+ return;
8108
+ const scroller = this._optionsContainer;
8109
+ const viewportHeight = this._resolveGuardedViewportHeight() || scroller.clientHeight;
8110
+ let targetScrollTop = null;
8111
+ if (anchor.key !== null) {
8112
+ const displayIndex = this._renderPlan.displayIndexByKey.get(anchor.key);
8113
+ if (displayIndex !== undefined) {
8114
+ const sourceIndex = this._renderPlan.sourceIndexByKey.get(anchor.key);
8115
+ const option = sourceIndex === undefined ? null : this._getOptionElementByIndex(sourceIndex);
8116
+ const viewportTop = scroller.getBoundingClientRect().top + scroller.clientTop;
8117
+ const optionTop = option?.getBoundingClientRect().top;
8118
+ if (option && option.getBoundingClientRect().height > 0 && Number.isFinite(optionTop)) {
8119
+ targetScrollTop = scroller.scrollTop + optionTop - viewportTop - anchor.offset;
8120
+ }
8121
+ else if (this._guardedVirtualizer) {
8122
+ targetScrollTop = this._guardedVirtualizer.cumulativeOffset(displayIndex) - anchor.offset;
8123
+ }
8124
+ }
8125
+ }
8126
+ if (targetScrollTop === null)
8127
+ targetScrollTop = anchor.scrollTop;
8128
+ let maxScrollTop = Number.POSITIVE_INFINITY;
8129
+ if (this._guardedVirtualizer) {
8130
+ maxScrollTop = Math.max(0, this._guardedVirtualizer.cumulativeOffset(nextOrder.length) - viewportHeight);
8131
+ }
8132
+ else if (scroller.scrollHeight > 0 && scroller.clientHeight > 0) {
8133
+ maxScrollTop = Math.max(0, scroller.scrollHeight - scroller.clientHeight);
8134
+ }
8135
+ targetScrollTop = Math.max(0, Math.min(targetScrollTop, maxScrollTop));
8136
+ if (Math.abs(targetScrollTop - scroller.scrollTop) < 1)
8137
+ return;
8138
+ // The coordinator owns this single restoration write. The virtualizer may
8139
+ // update its mounted window in response, but it must not issue a second
8140
+ // physical positioning correction for this transaction.
8141
+ this._guardedVirtualScrollTop = targetScrollTop;
8142
+ scroller.scrollTop = targetScrollTop;
8143
+ }
8144
+ /** Used only when Element.getAnimations() is unavailable. */
8145
+ _getDropdownEntranceFallbackDurationMs() {
8146
+ if (window.matchMedia?.('(prefers-reduced-motion: reduce)').matches)
8147
+ return 0;
8148
+ const style = getComputedStyle(this._dropdown);
8149
+ const parseTime = (value) => {
8150
+ const trimmed = value.trim();
8151
+ const parsed = Number.parseFloat(trimmed);
8152
+ if (!Number.isFinite(parsed))
8153
+ return 0;
8154
+ return trimmed.endsWith('ms') ? parsed : trimmed.endsWith('s') ? parsed * 1000 : 0;
8155
+ };
8156
+ const animationDurations = style.animationDuration.split(',');
8157
+ const animationDelays = style.animationDelay.split(',');
8158
+ const animationIterations = style.animationIterationCount.split(',');
8159
+ const maxAnimation = Math.max(0, ...animationDurations.map((duration, index) => {
8160
+ const count = Number.parseFloat(animationIterations[index % animationIterations.length] ?? '1');
8161
+ if (!Number.isFinite(count))
8162
+ return 0;
8163
+ return parseTime(duration)
8164
+ * Math.max(0, count)
8165
+ + parseTime(animationDelays[index % animationDelays.length] ?? '0s');
8166
+ }));
8167
+ const transitionDurations = style.transitionDuration.split(',');
8168
+ const transitionDelays = style.transitionDelay.split(',');
8169
+ const maxTransition = Math.max(0, ...transitionDurations.map((duration, index) => parseTime(duration) + parseTime(transitionDelays[index % transitionDelays.length] ?? '0s')));
8170
+ return Math.min(10000, Math.max(maxAnimation, maxTransition));
8171
+ }
7689
8172
  /** Stop an outstanding exit before reopening, disconnecting or starting another one. */
7690
8173
  _cancelDropdownExit() {
7691
8174
  if (this._dropdownExitTimer !== null) {
@@ -8040,26 +8523,38 @@ class EnhancedSelect extends HTMLElement {
8040
8523
  case 'Home':
8041
8524
  e.preventDefault();
8042
8525
  if (this._state.isOpen) {
8526
+ if (this._usesSelectedFirstVisualOrder()) {
8527
+ this._moveToVisualBoundary('first', { shiftKey: e.shiftKey, toggleKey: e.ctrlKey || e.metaKey });
8528
+ break;
8529
+ }
8043
8530
  const selectableIndices = this._getSelectableOptionIndices();
8044
8531
  const firstIndex = selectableIndices[0];
8045
8532
  if (firstIndex === undefined)
8046
8533
  break;
8047
8534
  this._setActive(firstIndex);
8048
8535
  if (this._config.selection.mode === 'multi' && e.shiftKey) {
8049
- this._selectRange(this._rangeAnchorIndex ?? firstIndex, firstIndex, { clear: !(e.ctrlKey || e.metaKey) });
8536
+ const targetKey = this._itemRegistry.indexToKey.get(firstIndex);
8537
+ if (targetKey !== undefined)
8538
+ this._selectKeyboardRange(this._rangeAnchorKey ?? targetKey, targetKey, { clear: !(e.ctrlKey || e.metaKey) });
8050
8539
  }
8051
8540
  }
8052
8541
  break;
8053
8542
  case 'End':
8054
8543
  e.preventDefault();
8055
8544
  if (this._state.isOpen) {
8545
+ if (this._usesSelectedFirstVisualOrder()) {
8546
+ this._moveToVisualBoundary('last', { shiftKey: e.shiftKey, toggleKey: e.ctrlKey || e.metaKey });
8547
+ break;
8548
+ }
8056
8549
  const selectableIndices = this._getSelectableOptionIndices();
8057
8550
  const lastIndex = selectableIndices[selectableIndices.length - 1];
8058
8551
  if (lastIndex === undefined)
8059
8552
  break;
8060
8553
  this._setActive(lastIndex);
8061
8554
  if (this._config.selection.mode === 'multi' && e.shiftKey) {
8062
- this._selectRange(this._rangeAnchorIndex ?? lastIndex, lastIndex, { clear: !(e.ctrlKey || e.metaKey) });
8555
+ const targetKey = this._itemRegistry.indexToKey.get(lastIndex);
8556
+ if (targetKey !== undefined)
8557
+ this._selectKeyboardRange(this._rangeAnchorKey ?? targetKey, targetKey, { clear: !(e.ctrlKey || e.metaKey) });
8063
8558
  }
8064
8559
  }
8065
8560
  break;
@@ -8114,6 +8609,26 @@ class EnhancedSelect extends HTMLElement {
8114
8609
  }
8115
8610
  }
8116
8611
  _moveActive(delta, opts) {
8612
+ if (this._usesSelectedFirstVisualOrder()) {
8613
+ const model = this._getVisualNavigationModel();
8614
+ if (model.selectableKeys.length === 0)
8615
+ return;
8616
+ const activeKey = this._engine.state.activeKey;
8617
+ const currentPosition = activeKey === null ? undefined : model.selectablePositionByKey.get(activeKey);
8618
+ // Load-more is only requested after movement reaches the actual visual end.
8619
+ if (delta === 1 && currentPosition === model.selectableKeys.length - 1 && this._requestKeyboardLoadMore())
8620
+ return;
8621
+ const nextKey = resolveVisualMovement(model, activeKey, delta);
8622
+ if (nextKey === null)
8623
+ return;
8624
+ this._setActiveForVisualKey(nextKey);
8625
+ if (this._config.selection.mode === 'multi' && opts?.shiftKey) {
8626
+ const anchorKey = this._rangeAnchorKey ?? activeKey ?? nextKey;
8627
+ this._rangeAnchorKey = anchorKey;
8628
+ this._selectKeyboardRange(anchorKey, nextKey, { clear: !opts.toggleKey });
8629
+ }
8630
+ return;
8631
+ }
8117
8632
  const selectableIndices = this._getSelectableOptionIndices();
8118
8633
  if (selectableIndices.length === 0)
8119
8634
  return;
@@ -8135,13 +8650,89 @@ class EnhancedSelect extends HTMLElement {
8135
8650
  const next = selectableIndices[nextPosition];
8136
8651
  this._setActive(next);
8137
8652
  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 });
8653
+ const nextKey = this._itemRegistry.indexToKey.get(next);
8654
+ if (nextKey === undefined)
8655
+ return;
8656
+ const anchorKey = this._rangeAnchorKey ?? (currentIndex >= 0 ? this._itemRegistry.indexToKey.get(currentIndex) : undefined) ?? nextKey;
8657
+ this._rangeAnchorKey = anchorKey;
8658
+ this._selectKeyboardRange(anchorKey, nextKey, { clear: !opts?.toggleKey });
8659
+ }
8660
+ }
8661
+ _usesSelectedFirstVisualOrder() {
8662
+ return this._selectedOptionsConfigAtOpen.placement === 'selected-first';
8663
+ }
8664
+ _getVisualNavigationModel() {
8665
+ this._ensureRegistryCurrent();
8666
+ return createVisualNavigationModel(this._renderPlan.filteredKeys, (key) => {
8667
+ const record = this._itemRegistry.keyToRecord.get(key);
8668
+ if (!record || record.disabled)
8669
+ return false;
8670
+ const option = this._getOptionElementByIndex(record.index);
8671
+ return option?.getAttribute('aria-disabled') !== 'true';
8672
+ });
8673
+ }
8674
+ _setActiveForVisualKey(key, reason = 'keyboard', options = {}) {
8675
+ const sourceIndex = this._renderPlan.sourceIndexByKey.get(key)
8676
+ ?? this._itemRegistry.keyToIndex.get(key);
8677
+ if (sourceIndex === undefined)
8678
+ return;
8679
+ this._setActive(sourceIndex, reason, options);
8680
+ }
8681
+ _moveToVisualBoundary(boundary, opts) {
8682
+ const model = this._getVisualNavigationModel();
8683
+ const targetKey = resolveVisualBoundary(model, boundary);
8684
+ if (targetKey === null)
8685
+ return;
8686
+ const currentKey = this._engine.state.activeKey;
8687
+ this._setActiveForVisualKey(targetKey);
8688
+ if (this._config.selection.mode === 'multi' && opts?.shiftKey) {
8689
+ const anchorKey = this._rangeAnchorKey ?? currentKey ?? targetKey;
8690
+ this._rangeAnchorKey = anchorKey;
8691
+ this._selectKeyboardRange(anchorKey, targetKey, { clear: !opts.toggleKey });
8692
+ }
8693
+ }
8694
+ _selectKeyboardRange(anchorKey, targetKey, opts) {
8695
+ if (this._usesSelectedFirstVisualOrder()) {
8696
+ const model = this._getVisualNavigationModel();
8697
+ const resolvedAnchor = model.selectablePositionByKey.has(anchorKey) ? anchorKey : targetKey;
8698
+ this._rangeAnchorKey = resolvedAnchor;
8699
+ this._selectVisualRange(resolvedAnchor, targetKey, opts);
8700
+ return;
8701
+ }
8702
+ const start = this._itemRegistry.keyToIndex.get(anchorKey);
8703
+ const end = this._itemRegistry.keyToIndex.get(targetKey);
8704
+ if (start !== undefined && end !== undefined)
8705
+ this._selectRange(start, end, opts);
8706
+ }
8707
+ _selectVisualRange(anchorKey, targetKey, opts) {
8708
+ if (this._config.selection.mode !== 'multi')
8709
+ return;
8710
+ this._ensureRegistryCurrent();
8711
+ const model = this._getVisualNavigationModel();
8712
+ const rangeKeys = resolveVisualRange(model, anchorKey, targetKey);
8713
+ if (rangeKeys.length === 0)
8714
+ return;
8715
+ const selectedEntries = this._getSelectedEntries();
8716
+ const entries = opts?.clear
8717
+ ? selectedEntries.filter((entry) => !this._itemRegistry.keyToRecord.has(entry.key))
8718
+ : selectedEntries;
8719
+ for (const key of rangeKeys) {
8720
+ const record = this._itemRegistry.keyToRecord.get(key);
8721
+ if (!record || this._isOptionSelectionBlocked(record.item))
8722
+ continue;
8723
+ entries.push(record);
8144
8724
  }
8725
+ this._requestSelectionReplacement(entries, opts?.reason ?? 'keyboard', 'select visual range');
8726
+ this._renderOptions();
8727
+ this._updateInputDisplay();
8728
+ const target = this._itemRegistry.keyToRecord.get(targetKey);
8729
+ const selectDetail = target ? this._getSelectEventDetail(target) : null;
8730
+ if (selectDetail)
8731
+ this._emit('select', selectDetail);
8732
+ this._emitChange();
8733
+ this._announce(`${this._state.selectedIndices.size} items selected`);
8734
+ if (selectDetail)
8735
+ this._config.callbacks.onSelect?.(selectDetail);
8145
8736
  }
8146
8737
  /** Return true only when boundary navigation is held for an in-flight/new page. */
8147
8738
  _requestKeyboardLoadMore() {
@@ -8170,7 +8761,7 @@ class EnhancedSelect extends HTMLElement {
8170
8761
  this._dispatchAcknowledgedActions(actions);
8171
8762
  return true;
8172
8763
  }
8173
- _setActive(index, reason = 'keyboard') {
8764
+ _setActive(index, reason = 'keyboard', options = {}) {
8174
8765
  this._ensureRegistryCurrent();
8175
8766
  const record = this._getRecordByIndex(index);
8176
8767
  let option = this._getOptionElementByIndex(index);
@@ -8181,8 +8772,10 @@ class EnhancedSelect extends HTMLElement {
8181
8772
  if (!record || record.disabled || !option || option.getAttribute('aria-disabled') === 'true') {
8182
8773
  return;
8183
8774
  }
8184
- if (reason === 'keyboard')
8775
+ if (reason === 'keyboard' || reason === 'search') {
8185
8776
  this._keyboardActiveChangeGeneration += 1;
8777
+ this._cancelOpenSelectedScroll();
8778
+ }
8186
8779
  const previousIndex = this._state.activeIndex;
8187
8780
  this._dispatchActiveKey(record.key, reason, 'set active');
8188
8781
  if (this._state.activeIndex !== index)
@@ -8209,8 +8802,7 @@ class EnhancedSelect extends HTMLElement {
8209
8802
  else {
8210
8803
  this._syncCustomOptionActiveClasses(option, true);
8211
8804
  }
8212
- if (typeof option.scrollIntoView === 'function') {
8213
- // Don't scroll wildly when just opening with pre-selections
8805
+ if (options.scroll !== false && typeof option.scrollIntoView === 'function') {
8214
8806
  option.scrollIntoView({ block: 'nearest', behavior: 'smooth' });
8215
8807
  }
8216
8808
  // Announce position for screen readers
@@ -8266,8 +8858,22 @@ class EnhancedSelect extends HTMLElement {
8266
8858
  this._typeTimeout = window.setTimeout(() => {
8267
8859
  this._typeBuffer = '';
8268
8860
  }, 500);
8269
- // Find first matching option
8861
+ // Type-ahead uses the displayed candidate order when a presentation projection is active.
8270
8862
  const getValue = this._config.serverSide.getLabelFromItem || ((item) => item?.label ?? String(item));
8863
+ if (this._usesSelectedFirstVisualOrder()) {
8864
+ const model = this._getVisualNavigationModel();
8865
+ const matchKey = model.selectableKeys.find((key) => {
8866
+ const record = this._itemRegistry.keyToRecord.get(key);
8867
+ return record !== undefined && getValue(record.item).toLowerCase().startsWith(this._typeBuffer);
8868
+ });
8869
+ if (matchKey !== undefined) {
8870
+ const sourceIndex = this._renderPlan.sourceIndexByKey.get(matchKey)
8871
+ ?? this._itemRegistry.keyToIndex.get(matchKey);
8872
+ if (sourceIndex !== undefined)
8873
+ this._setActive(sourceIndex, 'search');
8874
+ }
8875
+ return;
8876
+ }
8271
8877
  const matchIndex = this._state.loadedItems.findIndex((item) => getValue(item).toLowerCase().startsWith(this._typeBuffer));
8272
8878
  if (matchIndex >= 0) {
8273
8879
  this._setActive(matchIndex, 'search');
@@ -8336,6 +8942,17 @@ class EnhancedSelect extends HTMLElement {
8336
8942
  };
8337
8943
  }
8338
8944
  _setInitialActiveOption() {
8945
+ if (this._usesSelectedFirstVisualOrder()) {
8946
+ const model = this._getVisualNavigationModel();
8947
+ const selectedKey = model.selectableKeys.find((key) => this._engine.state.selectedKeys.has(key));
8948
+ if (selectedKey === undefined) {
8949
+ this._dispatchActiveKey(null, 'open', 'initial active option');
8950
+ return;
8951
+ }
8952
+ // Resolve via stable identity so the open-time projection remains authoritative.
8953
+ this._setActiveForVisualKey(selectedKey, 'open', { scroll: false });
8954
+ return;
8955
+ }
8339
8956
  const selectableIndices = this._getSelectableOptionIndices();
8340
8957
  const selected = Array.from(this._state.selectedIndices).sort((a, b) => a - b);
8341
8958
  // Opening an empty select must not implicitly assign an active descendant.
@@ -8345,7 +8962,9 @@ class EnhancedSelect extends HTMLElement {
8345
8962
  return;
8346
8963
  }
8347
8964
  const target = selected.find((index) => selectableIndices.includes(index)) ?? selectableIndices[0];
8348
- this._setActive(target, 'open');
8965
+ // Set logical active state and ARIA immediately. The open-time coordinator
8966
+ // owns any physical positioning after the dropdown's entrance settles.
8967
+ this._setActive(target, 'open', { scroll: false });
8349
8968
  }
8350
8969
  _announce(message) {
8351
8970
  const effects = computeAccessibilityEffects(deriveAccessibilityState(this._engine.state), {
@@ -8399,9 +9018,10 @@ class EnhancedSelect extends HTMLElement {
8399
9018
  const toggleKey = Boolean(opts?.toggleKey);
8400
9019
  const shiftKey = Boolean(opts?.shiftKey);
8401
9020
  if (shiftKey) {
8402
- const anchor = this._rangeAnchorIndex ?? index;
8403
- this._selectRange(anchor, index, { clear: !toggleKey, reason });
8404
- this._rangeAnchorIndex = anchor;
9021
+ const targetKey = record.key;
9022
+ const anchorKey = this._rangeAnchorKey ?? targetKey;
9023
+ this._selectKeyboardRange(anchorKey, targetKey, { clear: !toggleKey, reason });
9024
+ this._rangeAnchorKey = anchorKey;
8405
9025
  return;
8406
9026
  }
8407
9027
  // Multi select with toggle
@@ -8415,7 +9035,7 @@ class EnhancedSelect extends HTMLElement {
8415
9035
  // Re-render to update styles (safer than trying to find the element in filtered list)
8416
9036
  this._renderOptions();
8417
9037
  }
8418
- this._rangeAnchorIndex = index;
9038
+ this._rangeAnchorKey = record.key;
8419
9039
  this._updateInputDisplay();
8420
9040
  const selectDetail = this._getSelectEventDetail(record);
8421
9041
  this._emit('select', selectDetail);
@@ -8674,58 +9294,71 @@ class EnhancedSelect extends HTMLElement {
8674
9294
  this._optionsContainer.style.transition = 'opacity 0.2s ease-in';
8675
9295
  }, 150);
8676
9296
  }
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
9297
+ _scrollToSelected(options = {}) {
9298
+ const config = options.config ?? this._config.scrollToSelected;
9299
+ if (!config.enabled)
9300
+ return;
9301
+ const targetKey = resolveSelectedTargetKey(this._renderPlan.filteredKeys, this._engine.state.selectedKeys, config.multiSelectTarget);
9302
+ if (targetKey === null)
9303
+ return;
9304
+ const targetIndex = this._renderPlan.sourceIndexByKey.get(targetKey)
9305
+ ?? this._itemRegistry.keyToIndex.get(targetKey);
9306
+ if (targetIndex === undefined)
9307
+ return;
9308
+ // Resolve against the current eligible render plan first. A selected key
9309
+ // outside the filtered projection must never trigger materialization.
8711
9310
  let option = this._getOptionElementByIndex(targetIndex);
8712
9311
  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
- }
9312
+ this._materializeGuardedVirtualKey(targetKey);
9313
+ option = this._getOptionElementByIndex(targetIndex);
8718
9314
  }
8719
9315
  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
- });
9316
+ const reducedMotion = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches ?? false;
9317
+ this._scrollOptionWithinOptionsContainer(option, config.block || 'nearest', reducedMotion && config.behavior === 'smooth' ? 'auto' : (config.behavior || 'smooth'), options.onlyIfNeeded === true);
9318
+ if (options.setActive !== false) {
9319
+ // Active/ARIA synchronization must not start a second physical scroll.
9320
+ this._setActive(targetIndex, 'programmatic', { scroll: false });
8726
9321
  }
8727
- // Also set it as active for keyboard navigation
8728
- this._setActive(targetIndex, 'programmatic');
9322
+ }
9323
+ }
9324
+ _scrollOptionWithinOptionsContainer(option, block, behavior, onlyIfNeeded) {
9325
+ const scroller = this._optionsContainer;
9326
+ const scrollerRect = scroller.getBoundingClientRect();
9327
+ const viewportTop = scrollerRect.top + scroller.clientTop;
9328
+ const viewportBottom = viewportTop + scroller.clientHeight;
9329
+ const optionRect = option.getBoundingClientRect();
9330
+ if (onlyIfNeeded && optionRect.top >= viewportTop && optionRect.bottom <= viewportBottom)
9331
+ return;
9332
+ if (scroller.clientHeight <= 0 || optionRect.height <= 0)
9333
+ return;
9334
+ let targetScrollTop = scroller.scrollTop;
9335
+ if (block === 'start') {
9336
+ targetScrollTop += optionRect.top - viewportTop;
9337
+ }
9338
+ else if (block === 'center') {
9339
+ targetScrollTop += (optionRect.top + optionRect.bottom - viewportTop - viewportBottom) / 2;
9340
+ }
9341
+ else if (block === 'end') {
9342
+ targetScrollTop += optionRect.bottom - viewportBottom;
9343
+ }
9344
+ else if (optionRect.top < viewportTop) {
9345
+ targetScrollTop += optionRect.top - viewportTop;
9346
+ }
9347
+ else if (optionRect.bottom > viewportBottom) {
9348
+ targetScrollTop += optionRect.bottom - viewportBottom;
9349
+ }
9350
+ else {
9351
+ return;
9352
+ }
9353
+ const maxScrollTop = Math.max(0, scroller.scrollHeight - scroller.clientHeight);
9354
+ targetScrollTop = Math.max(0, Math.min(targetScrollTop, maxScrollTop));
9355
+ if (Math.abs(targetScrollTop - scroller.scrollTop) < 1)
9356
+ return;
9357
+ if (typeof scroller.scrollTo === 'function') {
9358
+ scroller.scrollTo({ top: targetScrollTop, behavior });
9359
+ }
9360
+ else {
9361
+ scroller.scrollTop = targetScrollTop;
8729
9362
  }
8730
9363
  }
8731
9364
  async _loadMoreItems(trigger = 'manual') {
@@ -9211,10 +9844,21 @@ class EnhancedSelect extends HTMLElement {
9211
9844
  this._invalidateGuardedMeasurements();
9212
9845
  const previousMode = this._config.selection.mode;
9213
9846
  const previousEnabled = this._config.enabled;
9847
+ const previousOpenScrollEnabled = this._config.scrollToSelected.enabled;
9214
9848
  const previousDataLoadingConfig = this._dataLoadingConfig;
9215
9849
  let searchEligibilityBecameInactive = false;
9216
- const { dataLoading, callbacks, ...legacyConfig } = config;
9850
+ const { dataLoading, callbacks, selectedOptions, scrollToSelected, ...legacyConfig } = config;
9217
9851
  const legacyUpdate = { ...legacyConfig };
9852
+ if (selectedOptions !== undefined) {
9853
+ const validation = validateSelectedOptionsConfig(selectedOptions);
9854
+ if (validation.valid)
9855
+ legacyUpdate.selectedOptions = validation.value;
9856
+ }
9857
+ if (scrollToSelected !== undefined) {
9858
+ const validation = validateScrollToSelectedConfig(scrollToSelected);
9859
+ if (validation.valid)
9860
+ legacyUpdate.scrollToSelected = validation.value;
9861
+ }
9218
9862
  let configErrorDetail;
9219
9863
  if (callbacks !== undefined && callbacks !== null) {
9220
9864
  const callbackInput = callbacks;
@@ -9234,6 +9878,10 @@ class EnhancedSelect extends HTMLElement {
9234
9878
  legacyUpdate.callbacks = legacyCallbacks;
9235
9879
  }
9236
9880
  this._config = this._mergeConfig(this._config, legacyUpdate);
9881
+ if (previousOpenScrollEnabled && !this._config.scrollToSelected.enabled) {
9882
+ this._openOptionsViewportAnchor = null;
9883
+ this._cancelOpenSelectedScroll();
9884
+ }
9237
9885
  if (dataLoading !== undefined) {
9238
9886
  const dataLoadingPrototype = dataLoading !== null && typeof dataLoading === 'object'
9239
9887
  ? Object.getPrototypeOf(dataLoading)
@@ -9780,19 +10428,39 @@ class EnhancedSelect extends HTMLElement {
9780
10428
  activeKey: this._engine.state.activeKey,
9781
10429
  };
9782
10430
  }
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));
10431
+ _createLegacyRenderPlan(filteredIndices, groupedPresentation = []) {
10432
+ const sourceIndices = [...filteredIndices];
10433
+ const sourceOrderedKeys = groupedPresentation.length > 0
10434
+ ? groupedPresentation.flatMap((group) => group.orderedKeys)
10435
+ : sourceIndices
10436
+ .map((index) => this._itemRegistry.indexToKey.get(index))
10437
+ .filter((key) => key !== undefined);
10438
+ const shouldProjectSelectedFirst = this._usesSelectedFirstVisualOrder()
10439
+ && groupedPresentation.length === 0;
10440
+ const selectedKeys = this._selectedOptionsSelectionAtOpen ?? this._engine.state.selectedKeys;
10441
+ const filteredKeys = shouldProjectSelectedFirst
10442
+ ? projectSelectedOptionKeys(sourceOrderedKeys, selectedKeys)
10443
+ : sourceOrderedKeys;
10444
+ const indices = filteredKeys
10445
+ .map((key) => this._itemRegistry.keyToIndex.get(key))
10446
+ .filter((index) => index !== undefined);
10447
+ const displayIndexByKey = new Map();
10448
+ const sourceIndexByKey = new Map();
10449
+ filteredKeys.forEach((key, displayIndex) => {
10450
+ displayIndexByKey.set(key, displayIndex);
10451
+ const sourceIndex = this._itemRegistry.keyToIndex.get(key);
10452
+ if (sourceIndex !== undefined)
10453
+ sourceIndexByKey.set(key, sourceIndex);
10454
+ });
9790
10455
  return {
9791
10456
  mode: 'legacy-full',
9792
10457
  filteredIndices: indices,
9793
10458
  filteredKeys,
9794
10459
  intendedRenderKeys: filteredKeys.slice(),
9795
- filteredIndexByKey,
10460
+ displayIndexByKey,
10461
+ sourceIndexByKey,
10462
+ filteredIndexByKey: displayIndexByKey,
10463
+ groupedPresentation,
9796
10464
  };
9797
10465
  }
9798
10466
  _createVirtualRenderPlan(startIndex, endIndex) {
@@ -9801,12 +10469,16 @@ class EnhancedSelect extends HTMLElement {
9801
10469
  const filteredIndices = intendedRenderKeys
9802
10470
  .map((key) => this._itemRegistry.keyToIndex.get(key))
9803
10471
  .filter((index) => index !== undefined);
10472
+ const displayIndexByKey = new Map(this._renderPlan.displayIndexByKey);
9804
10473
  return {
9805
10474
  mode: 'virtual-window',
9806
10475
  filteredIndices,
9807
10476
  filteredKeys,
9808
10477
  intendedRenderKeys,
9809
- filteredIndexByKey: new Map(this._renderPlan.filteredIndexByKey),
10478
+ displayIndexByKey,
10479
+ sourceIndexByKey: new Map(this._renderPlan.sourceIndexByKey),
10480
+ filteredIndexByKey: displayIndexByKey,
10481
+ groupedPresentation: this._renderPlan.groupedPresentation,
9810
10482
  };
9811
10483
  }
9812
10484
  _ensureGuardedVirtualizer(filteredKeys) {
@@ -10760,11 +11432,31 @@ class EnhancedSelect extends HTMLElement {
10760
11432
  // Handle Grouped Items Rendering (when no search query)
10761
11433
  if (this._state.groupedItems.length > 0 && !query) {
10762
11434
  this._destroyGuardedVirtualizer();
10763
- this._renderPlan = this._createLegacyRenderPlan(this._itemRegistry.records.map((record) => record.index));
11435
+ const groupedSource = this._state.groupedItems.map((group, groupIndex) => ({
11436
+ group,
11437
+ groupIndex,
11438
+ orderedKeys: group.options
11439
+ .map((item) => this._state.loadedItems.indexOf(item))
11440
+ .filter((index) => index >= 0)
11441
+ .map((index) => this._itemRegistry.indexToKey.get(index))
11442
+ .filter((key) => key !== undefined),
11443
+ }));
11444
+ const groupedOrder = this._usesSelectedFirstVisualOrder()
11445
+ ? projectSelectedOptionGroups(groupedSource.map(({ groupIndex, orderedKeys }) => ({ groupIdentity: groupIndex, orderedKeys })), this._selectedOptionsSelectionAtOpen ?? this._engine.state.selectedKeys)
11446
+ : groupedSource.map(({ groupIndex, orderedKeys }) => ({ groupIdentity: groupIndex, orderedKeys }));
11447
+ const groupedPresentation = groupedOrder.map(({ groupIdentity, orderedKeys }) => ({
11448
+ group: this._state.groupedItems[groupIdentity],
11449
+ groupIndex: groupIdentity,
11450
+ orderedKeys,
11451
+ }));
11452
+ const groupedIndices = groupedPresentation.flatMap(({ orderedKeys }) => orderedKeys
11453
+ .map((key) => this._itemRegistry.keyToIndex.get(key))
11454
+ .filter((index) => index !== undefined));
11455
+ this._renderPlan = this._createLegacyRenderPlan(groupedIndices, groupedPresentation);
10764
11456
  filteredIndicesForScope = this._renderPlan.filteredIndices;
10765
11457
  this._registerShadowItems(filteredIndicesForScope);
10766
11458
  this._refreshVirtualizationScope(filteredIndicesForScope);
10767
- this._state.groupedItems.forEach((group, groupIndex) => {
11459
+ this._renderPlan.groupedPresentation.forEach(({ group, groupIndex, orderedKeys }) => {
10768
11460
  let header;
10769
11461
  if (this.groupHeaderRenderer) {
10770
11462
  header = this.groupHeaderRenderer(group, groupIndex);
@@ -10790,10 +11482,10 @@ class EnhancedSelect extends HTMLElement {
10790
11482
  }
10791
11483
  header.setAttribute('part', 'group-header');
10792
11484
  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) {
11485
+ orderedKeys.forEach((key) => {
11486
+ const index = this._itemRegistry.keyToIndex.get(key);
11487
+ if (index !== undefined) {
11488
+ const item = this._state.loadedItems[index];
10797
11489
  this._renderSingleOption(item, index, getValue, getLabel);
10798
11490
  }
10799
11491
  });
@@ -10862,13 +11554,16 @@ class EnhancedSelect extends HTMLElement {
10862
11554
  const chunkSize = 80;
10863
11555
  let cursor = 0;
10864
11556
  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
- }
11557
+ if (this._state.isOpen
11558
+ && this._config.scrollToSelected.enabled
11559
+ && this._scrollToSelectedConfigAtOpen.enabled
11560
+ && this._scrollToSelectedConfigAtOpen.onOpen !== 'preserve') {
11561
+ const targetKey = resolveSelectedTargetKey(this._renderPlan.filteredKeys, this._engine.state.selectedKeys, this._scrollToSelectedConfigAtOpen.multiSelectTarget);
11562
+ const targetPosition = targetKey === null
11563
+ ? undefined
11564
+ : this._renderPlan.displayIndexByKey.get(targetKey);
11565
+ if (targetPosition !== undefined)
11566
+ maxRenderTarget = targetPosition + 20;
10872
11567
  }
10873
11568
  const renderChunk = () => {
10874
11569
  if (renderCycleId !== this._renderCycleId) {
@@ -12378,6 +13073,9 @@ exports.shadowDOMStyles = shadowDOMStyles;
12378
13073
  exports.toggleClass = toggleClass;
12379
13074
  exports.transition = transition;
12380
13075
  exports.validateDataLoadingConfig = validateDataLoadingConfig;
13076
+ exports.validateScrollToSelectedConfig = validateScrollToSelectedConfig;
13077
+ exports.validateSelectedOptionsConfig = validateSelectedOptionsConfig;
13078
+ exports.validateSelectedOptionsConfigUpdate = validateSelectedOptionsConfigUpdate;
12381
13079
  exports.validateTemplate = validateTemplate;
12382
13080
  exports.valuesEqual = valuesEqual;
12383
13081
  exports.warnCSPViolation = warnCSPViolation;