@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.umd.js CHANGED
@@ -2078,6 +2078,123 @@
2078
2078
  customElements.define("smilodon-select", NativeSelectElement);
2079
2079
  }
2080
2080
 
2081
+ const SELECTED_OPTIONS_FIELDS = new Set(['placement', 'groupedPlacement']);
2082
+ const SCROLL_TO_SELECTED_FIELDS = new Set([
2083
+ 'enabled',
2084
+ 'multiSelectTarget',
2085
+ 'onOpen',
2086
+ 'behavior',
2087
+ 'block',
2088
+ ]);
2089
+ const placements = new Set(['original', 'selected-first']);
2090
+ const groupedPlacements = new Set(['within-group']);
2091
+ const scrollTargets = new Set(['first', 'last']);
2092
+ const openPolicies = new Set(['preserve', 'reveal', 'align']);
2093
+ const scrollBehaviors = new Set(['auto', 'instant', 'smooth']);
2094
+ const scrollBlocks = new Set(['start', 'center', 'end', 'nearest']);
2095
+ function asPlainRecord(value) {
2096
+ if (value === null || typeof value !== 'object' || Array.isArray(value))
2097
+ return null;
2098
+ const prototype = Object.getPrototypeOf(value);
2099
+ return prototype === Object.prototype || prototype === null ? value : null;
2100
+ }
2101
+ function unknownFieldIssues(record, allowed) {
2102
+ return Object.keys(record)
2103
+ .filter((key) => !allowed.has(key))
2104
+ .sort()
2105
+ .map((key) => ({
2106
+ path: key,
2107
+ code: 'unknown-field',
2108
+ message: `Unknown configuration field: ${key}.`,
2109
+ }));
2110
+ }
2111
+ function validateEnum(record, field, allowed, issues) {
2112
+ const value = record[field];
2113
+ if (value === undefined)
2114
+ return;
2115
+ if (typeof value !== 'string') {
2116
+ issues.push({ path: field, code: 'invalid-type', message: `${field} must be a string.` });
2117
+ }
2118
+ else if (!allowed.has(value)) {
2119
+ issues.push({ path: field, code: 'invalid-value', message: `${field} has an unsupported value.` });
2120
+ }
2121
+ }
2122
+ /** Validate a partial selected-options configuration update. */
2123
+ function validateSelectedOptionsConfig(candidate) {
2124
+ const record = asPlainRecord(candidate);
2125
+ if (!record) {
2126
+ return {
2127
+ valid: false,
2128
+ issues: [{ path: 'selectedOptions', code: 'invalid-type', message: 'selectedOptions must be a plain object.' }],
2129
+ };
2130
+ }
2131
+ const issues = unknownFieldIssues(record, SELECTED_OPTIONS_FIELDS);
2132
+ validateEnum(record, 'placement', placements, issues);
2133
+ validateEnum(record, 'groupedPlacement', groupedPlacements, issues);
2134
+ if (issues.length > 0)
2135
+ return { valid: false, issues };
2136
+ return {
2137
+ valid: true,
2138
+ value: {
2139
+ ...(record.placement === undefined ? {} : { placement: record.placement }),
2140
+ ...(record.groupedPlacement === undefined
2141
+ ? {}
2142
+ : { groupedPlacement: record.groupedPlacement }),
2143
+ },
2144
+ };
2145
+ }
2146
+ /** Validate a partial scroll-to-selected configuration update. */
2147
+ function validateScrollToSelectedConfig(candidate) {
2148
+ const record = asPlainRecord(candidate);
2149
+ if (!record) {
2150
+ return {
2151
+ valid: false,
2152
+ issues: [{ path: 'scrollToSelected', code: 'invalid-type', message: 'scrollToSelected must be a plain object.' }],
2153
+ };
2154
+ }
2155
+ const issues = unknownFieldIssues(record, SCROLL_TO_SELECTED_FIELDS);
2156
+ if (record.enabled !== undefined && typeof record.enabled !== 'boolean') {
2157
+ issues.push({ path: 'enabled', code: 'invalid-type', message: 'enabled must be a boolean.' });
2158
+ }
2159
+ validateEnum(record, 'multiSelectTarget', scrollTargets, issues);
2160
+ validateEnum(record, 'onOpen', openPolicies, issues);
2161
+ validateEnum(record, 'behavior', scrollBehaviors, issues);
2162
+ validateEnum(record, 'block', scrollBlocks, issues);
2163
+ if (issues.length > 0)
2164
+ return { valid: false, issues };
2165
+ return {
2166
+ valid: true,
2167
+ value: {
2168
+ ...(record.enabled === undefined ? {} : { enabled: record.enabled }),
2169
+ ...(record.multiSelectTarget === undefined
2170
+ ? {}
2171
+ : { multiSelectTarget: record.multiSelectTarget }),
2172
+ ...(record.onOpen === undefined ? {} : { onOpen: record.onOpen }),
2173
+ ...(record.behavior === undefined ? {} : { behavior: record.behavior }),
2174
+ ...(record.block === undefined ? {} : { block: record.block }),
2175
+ },
2176
+ };
2177
+ }
2178
+ /** Validate and copy only the new public configuration sections. */
2179
+ function validateSelectedOptionsConfigUpdate(config) {
2180
+ const result = { ...config };
2181
+ if (config.selectedOptions !== undefined) {
2182
+ const validation = validateSelectedOptionsConfig(config.selectedOptions);
2183
+ if (validation.valid)
2184
+ result.selectedOptions = validation.value;
2185
+ else
2186
+ delete result.selectedOptions;
2187
+ }
2188
+ if (config.scrollToSelected !== undefined) {
2189
+ const validation = validateScrollToSelectedConfig(config.scrollToSelected);
2190
+ if (validation.valid)
2191
+ result.scrollToSelected = validation.value;
2192
+ else
2193
+ delete result.scrollToSelected;
2194
+ }
2195
+ return result;
2196
+ }
2197
+
2081
2198
  /**
2082
2199
  * Global Configuration System for Select Components
2083
2200
  * Allows users to define default behaviors that can be overridden at component level
@@ -2117,9 +2234,14 @@
2117
2234
  scrollToSelected: {
2118
2235
  enabled: true,
2119
2236
  multiSelectTarget: 'first',
2237
+ onOpen: 'reveal',
2120
2238
  behavior: 'smooth',
2121
2239
  block: 'nearest',
2122
2240
  },
2241
+ selectedOptions: {
2242
+ placement: 'original',
2243
+ groupedPlacement: 'within-group',
2244
+ },
2123
2245
  loadMore: {
2124
2246
  enabled: false,
2125
2247
  itemsPerLoad: 3,
@@ -2202,7 +2324,8 @@
2202
2324
  * Update global configuration (deep merge)
2203
2325
  */
2204
2326
  updateConfig(updates) {
2205
- this.config = this.deepMerge(this.config, updates);
2327
+ const acceptedUpdates = validateSelectedOptionsConfigUpdate(updates);
2328
+ this.config = this.deepMerge(this.config, acceptedUpdates);
2206
2329
  }
2207
2330
  /**
2208
2331
  * Reset to default configuration
@@ -3163,6 +3286,94 @@
3163
3286
  return true;
3164
3287
  }
3165
3288
 
3289
+ function createVisualNavigationModel(orderedKeys, isSelectable) {
3290
+ const ordered = [...orderedKeys];
3291
+ const selectableKeys = [];
3292
+ const positionByKey = new Map();
3293
+ const selectablePositionByKey = new Map();
3294
+ ordered.forEach((key, position) => {
3295
+ positionByKey.set(key, position);
3296
+ if (isSelectable(key)) {
3297
+ selectablePositionByKey.set(key, selectableKeys.length);
3298
+ selectableKeys.push(key);
3299
+ }
3300
+ });
3301
+ return { orderedKeys: ordered, selectableKeys, positionByKey, selectablePositionByKey };
3302
+ }
3303
+ /** Resolve a clamped keyboard movement in visual order. */
3304
+ function resolveVisualMovement(model, currentKey, delta) {
3305
+ const { selectableKeys, selectablePositionByKey } = model;
3306
+ if (selectableKeys.length === 0)
3307
+ return null;
3308
+ const currentPosition = currentKey === null ? undefined : selectablePositionByKey.get(currentKey);
3309
+ const basePosition = currentPosition ?? (delta >= 0 ? -1 : selectableKeys.length);
3310
+ const nextPosition = Math.max(0, Math.min(selectableKeys.length - 1, basePosition + delta));
3311
+ return selectableKeys[nextPosition] ?? null;
3312
+ }
3313
+ function resolveVisualBoundary(model, boundary) {
3314
+ return boundary === 'first'
3315
+ ? model.selectableKeys[0] ?? null
3316
+ : model.selectableKeys[model.selectableKeys.length - 1] ?? null;
3317
+ }
3318
+ /** Return selectable keys in the inclusive visual interval between two keys. */
3319
+ function resolveVisualRange(model, startKey, endKey) {
3320
+ const startPosition = model.positionByKey.get(startKey);
3321
+ const endPosition = model.positionByKey.get(endKey);
3322
+ if (startPosition === undefined || endPosition === undefined)
3323
+ return [];
3324
+ const low = Math.min(startPosition, endPosition);
3325
+ const high = Math.max(startPosition, endPosition);
3326
+ const selectable = new Set(model.selectableKeys);
3327
+ return model.orderedKeys.slice(low, high + 1).filter((key) => selectable.has(key));
3328
+ }
3329
+
3330
+ /**
3331
+ * Return a presentation-only ordering for option keys.
3332
+ *
3333
+ * The source array and selection set are never mutated. Callers remain
3334
+ * responsible for retaining the returned order as the displayed ordering for
3335
+ * the relevant render/open transaction.
3336
+ */
3337
+ function projectSelectedOptionKeys(orderedKeys, selectedKeys, placement) {
3338
+ const selected = [];
3339
+ const unselected = [];
3340
+ for (const key of orderedKeys) {
3341
+ (selectedKeys.has(key) ? selected : unselected).push(key);
3342
+ }
3343
+ return [...selected, ...unselected];
3344
+ }
3345
+ /**
3346
+ * Stably partitions selected keys to the front of each group independently.
3347
+ * Group order, identity, membership, and the source arrays are preserved.
3348
+ */
3349
+ function projectSelectedOptionGroups(groups, selectedKeys) {
3350
+ return groups.map(({ groupIdentity, orderedKeys }) => {
3351
+ const selected = [];
3352
+ const unselected = [];
3353
+ for (const key of orderedKeys) {
3354
+ (selectedKeys.has(key) ? selected : unselected).push(key);
3355
+ }
3356
+ return { groupIdentity, orderedKeys: [...selected, ...unselected] };
3357
+ });
3358
+ }
3359
+
3360
+ /** Resolve the selected key at an edge of the displayed eligible ordering. */
3361
+ function resolveSelectedTargetKey(orderedKeys, selectedKeys, target) {
3362
+ if (target === 'first') {
3363
+ for (const key of orderedKeys) {
3364
+ if (selectedKeys.has(key))
3365
+ return key;
3366
+ }
3367
+ return null;
3368
+ }
3369
+ for (let index = orderedKeys.length - 1; index >= 0; index -= 1) {
3370
+ const key = orderedKeys[index];
3371
+ if (selectedKeys.has(key))
3372
+ return key;
3373
+ }
3374
+ return null;
3375
+ }
3376
+
3166
3377
  /**
3167
3378
  * DOM-independent coordinator for the opt-in acknowledged data-loading
3168
3379
  * protocol. This module is intentionally not re-exported from the package
@@ -4257,8 +4468,27 @@
4257
4468
  filteredIndices: [],
4258
4469
  filteredKeys: [],
4259
4470
  intendedRenderKeys: [],
4471
+ displayIndexByKey: new Map(),
4472
+ sourceIndexByKey: new Map(),
4260
4473
  filteredIndexByKey: new Map(),
4474
+ groupedPresentation: [],
4475
+ };
4476
+ // Presentation policy and membership are snapshotted when the dropdown opens
4477
+ // so selection/config updates cannot reorder an active list.
4478
+ this._selectedOptionsSelectionAtOpen = null;
4479
+ this._selectedOptionsConfigAtOpen = {
4480
+ placement: 'original',
4481
+ groupedPlacement: 'within-group',
4261
4482
  };
4483
+ this._scrollToSelectedConfigAtOpen = {
4484
+ enabled: true,
4485
+ multiSelectTarget: 'first',
4486
+ onOpen: 'reveal',
4487
+ behavior: 'smooth',
4488
+ block: 'nearest',
4489
+ };
4490
+ this._closedOptionsViewportAnchor = null;
4491
+ this._openOptionsViewportAnchor = null;
4262
4492
  this._emptyStateContext = null;
4263
4493
  // Null keeps the public/default renderer on its legacy full path. This
4264
4494
  // private state is only used by guarded virtualization integration.
@@ -4315,7 +4545,7 @@
4315
4545
  this._boundArrowClick = null;
4316
4546
  this._pendingFirstRenderMark = false;
4317
4547
  this._pendingSearchRenderMark = false;
4318
- this._rangeAnchorIndex = null;
4548
+ this._rangeAnchorKey = null;
4319
4549
  /** Chip identity is tracked independently of dropdown option positions. */
4320
4550
  this._lastRenderedChipKeys = null;
4321
4551
  this._latestChipScrollGeneration = 0;
@@ -4333,6 +4563,9 @@
4333
4563
  this._lifecycleTimers = new Set();
4334
4564
  this._lifecycleRafs = new Set();
4335
4565
  this._keyboardActiveChangeGeneration = 0;
4566
+ /** Invalidates selected-option positioning scheduled by an earlier opening. */
4567
+ this._openSelectedScrollGeneration = 0;
4568
+ this._openSelectedScrollCleanup = null;
4336
4569
  this._tracking = { events: [], styles: [], limitations: [] };
4337
4570
  this._suppressBlurClose = false;
4338
4571
  this._renderCycleId = 0;
@@ -4510,6 +4743,7 @@
4510
4743
  this._syncListboxAccessibility();
4511
4744
  }
4512
4745
  disconnectedCallback() {
4746
+ this._cancelOpenSelectedScroll();
4513
4747
  this._cancelLatestChipScroll();
4514
4748
  this._cancelBusyPresentation();
4515
4749
  if (this._dataRequestCoordinator) {
@@ -5096,12 +5330,12 @@
5096
5330
  duplicateKeyPolicy: this._getDuplicateKeyPolicy(),
5097
5331
  });
5098
5332
  const activeKey = this._engine.state.activeKey;
5099
- const anchorKey = this._rangeAnchorIndex === null ? undefined : this._itemRegistry.indexToKey.get(this._rangeAnchorIndex);
5333
+ const anchorKey = this._rangeAnchorKey;
5100
5334
  this._itemRegistry = registry;
5101
5335
  this._state.loadedItems = items;
5102
5336
  this._registryItemsRef = items;
5103
5337
  const disabledKeys = this._getBlockedDisabledKeys();
5104
- this._rangeAnchorIndex = anchorKey === undefined ? null : registry.keyToIndex.get(anchorKey) ?? null;
5338
+ this._rangeAnchorKey = anchorKey !== null && registry.keyToRecord.has(anchorKey) ? anchorKey : null;
5105
5339
  this._engine.dispatch({
5106
5340
  type: 'ITEMS_REGISTERED',
5107
5341
  keys: registry.records.map((record) => record.key),
@@ -7646,6 +7880,15 @@
7646
7880
  this._dropdown.removeAttribute('inert');
7647
7881
  this._dropdown.removeAttribute('aria-hidden');
7648
7882
  this._markOpenStart();
7883
+ this._scrollToSelectedConfigAtOpen = { ...this._config.scrollToSelected };
7884
+ this._openOptionsViewportAnchor = this._scrollToSelectedConfigAtOpen.onOpen === 'preserve'
7885
+ ? (this._closedOptionsViewportAnchor ?? this._captureOptionsViewportAnchor())
7886
+ : null;
7887
+ this._closedOptionsViewportAnchor = null;
7888
+ this._selectedOptionsConfigAtOpen = { ...this._config.selectedOptions };
7889
+ this._selectedOptionsSelectionAtOpen = this._config.selectedOptions.placement === 'selected-first'
7890
+ ? new Set(this._engine.state.selectedKeys)
7891
+ : null;
7649
7892
  this.setAttribute('data-open', 'true');
7650
7893
  this._liftStackingAncestors();
7651
7894
  this._dropdown.style.display = 'block';
@@ -7657,28 +7900,17 @@
7657
7900
  this._emit('open', {});
7658
7901
  this._config.callbacks.onOpen?.();
7659
7902
  this._announce('Options expanded');
7660
- // Scroll to selected if configured
7661
- if (this._config.scrollToSelected.enabled) {
7662
- const keyboardActiveChangeGeneration = this._keyboardActiveChangeGeneration;
7663
- const canRestoreOpenSelection = () => this._state.isOpen
7664
- && this._keyboardActiveChangeGeneration === keyboardActiveChangeGeneration;
7665
- // Use requestAnimationFrame for better timing after render
7666
- this._requestLifecycleFrame(() => {
7667
- if (!canRestoreOpenSelection())
7668
- return;
7669
- // Double RAF to ensure layout is complete
7670
- this._requestLifecycleFrame(() => {
7671
- if (!canRestoreOpenSelection())
7672
- return;
7673
- this._scrollToSelected();
7674
- });
7675
- });
7676
- }
7903
+ this._scheduleOpenSelectedScroll();
7677
7904
  }
7678
7905
  _handleClose(reason = 'programmatic') {
7906
+ if (this._state.isOpen) {
7907
+ this._closedOptionsViewportAnchor = this._captureOptionsViewportAnchor();
7908
+ }
7679
7909
  const effects = this._engine.dispatch({ type: 'CLOSE_REQUEST', reason });
7680
7910
  if (!effects.some((effect) => effect.type === 'POPUP_CLOSED'))
7681
7911
  return;
7912
+ this._cancelOpenSelectedScroll();
7913
+ this._selectedOptionsSelectionAtOpen = null;
7682
7914
  this.removeAttribute('data-open');
7683
7915
  this._restoreLiftedAncestors();
7684
7916
  this._dropdown.setAttribute('data-placement', this._resolvedDropdownPlacement);
@@ -7690,6 +7922,257 @@
7690
7922
  this._config.callbacks.onClose?.();
7691
7923
  this._announce('Options collapsed');
7692
7924
  }
7925
+ /**
7926
+ * Defer the one automatic selected-option positioning operation until the
7927
+ * dropdown's own entrance geometry has settled. Logical active/ARIA state
7928
+ * remains synchronous in _setInitialActiveOption().
7929
+ */
7930
+ _scheduleOpenSelectedScroll() {
7931
+ this._cancelOpenSelectedScroll();
7932
+ const openingConfig = this._scrollToSelectedConfigAtOpen;
7933
+ if (!openingConfig.enabled)
7934
+ return;
7935
+ const generation = this._openSelectedScrollGeneration;
7936
+ const keyboardGeneration = this._keyboardActiveChangeGeneration;
7937
+ const initialScrollTop = this._optionsContainer.scrollTop;
7938
+ const animations = [];
7939
+ const frameIds = new Set();
7940
+ let timerId = null;
7941
+ let completed = false;
7942
+ const isCurrent = () => generation === this._openSelectedScrollGeneration
7943
+ && this._state.isOpen
7944
+ && this.isConnected
7945
+ && this._config.scrollToSelected.enabled
7946
+ && keyboardGeneration === this._keyboardActiveChangeGeneration;
7947
+ const removeListeners = () => {
7948
+ this._optionsContainer.removeEventListener('wheel', cancelForUserInput);
7949
+ this._optionsContainer.removeEventListener('touchstart', cancelForUserInput);
7950
+ this._optionsContainer.removeEventListener('pointerdown', cancelForUserInput);
7951
+ this._optionsContainer.removeEventListener('scroll', cancelForUserScroll);
7952
+ for (const animation of animations) {
7953
+ animation.removeEventListener('finish', onAnimationStateChange);
7954
+ animation.removeEventListener('cancel', onAnimationStateChange);
7955
+ }
7956
+ };
7957
+ const cleanup = () => {
7958
+ removeListeners();
7959
+ for (const id of frameIds)
7960
+ cancelAnimationFrame(id);
7961
+ frameIds.clear();
7962
+ if (timerId !== null) {
7963
+ clearTimeout(timerId);
7964
+ this._lifecycleTimers.delete(timerId);
7965
+ timerId = null;
7966
+ }
7967
+ if (this._openSelectedScrollCleanup === cleanup) {
7968
+ this._openSelectedScrollCleanup = null;
7969
+ }
7970
+ };
7971
+ const cancelForUserInput = () => this._cancelOpenSelectedScroll();
7972
+ const cancelForUserScroll = () => {
7973
+ if (Math.abs(this._optionsContainer.scrollTop - initialScrollTop) > 1) {
7974
+ this._cancelOpenSelectedScroll();
7975
+ }
7976
+ };
7977
+ const finish = () => {
7978
+ if (completed)
7979
+ return;
7980
+ completed = true;
7981
+ cleanup();
7982
+ if (!isCurrent())
7983
+ return;
7984
+ const frameId = requestAnimationFrame(() => {
7985
+ frameIds.delete(frameId);
7986
+ cleanup();
7987
+ if (!isCurrent())
7988
+ return;
7989
+ if (openingConfig.onOpen === 'preserve') {
7990
+ this._restorePreservedOptionsViewport();
7991
+ }
7992
+ else {
7993
+ this._scrollToSelected({
7994
+ onlyIfNeeded: openingConfig.onOpen === 'reveal',
7995
+ setActive: false,
7996
+ config: openingConfig,
7997
+ });
7998
+ }
7999
+ });
8000
+ frameIds.add(frameId);
8001
+ this._openSelectedScrollCleanup = cleanup;
8002
+ };
8003
+ const onAnimationStateChange = () => {
8004
+ if (animations.every((animation) => animation.playState === 'finished' || animation.playState === 'idle'))
8005
+ finish();
8006
+ };
8007
+ const begin = () => {
8008
+ if (!isCurrent()) {
8009
+ cleanup();
8010
+ return;
8011
+ }
8012
+ const getAnimations = this._dropdown.getAnimations;
8013
+ const reducedMotion = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches ?? false;
8014
+ if (!reducedMotion && typeof getAnimations === 'function') {
8015
+ for (const animation of getAnimations.call(this._dropdown)) {
8016
+ const timing = animation.effect?.getComputedTiming();
8017
+ if (!timing || timing.iterations === Infinity || animation.playState === 'finished'
8018
+ || animation.playState === 'idle')
8019
+ continue;
8020
+ animations.push(animation);
8021
+ }
8022
+ }
8023
+ if (animations.length === 0) {
8024
+ if (!reducedMotion && typeof getAnimations !== 'function') {
8025
+ const fallbackWait = this._getDropdownEntranceFallbackDurationMs();
8026
+ if (fallbackWait > 0) {
8027
+ timerId = window.setTimeout(finish, fallbackWait + 34);
8028
+ this._lifecycleTimers.add(timerId);
8029
+ return;
8030
+ }
8031
+ }
8032
+ finish();
8033
+ return;
8034
+ }
8035
+ for (const animation of animations) {
8036
+ animation.addEventListener('finish', onAnimationStateChange);
8037
+ animation.addEventListener('cancel', onAnimationStateChange);
8038
+ }
8039
+ const remainingMs = Math.max(...animations.map((animation) => {
8040
+ const timing = animation.effect?.getComputedTiming();
8041
+ const endTime = Number(timing?.endTime);
8042
+ const currentTime = Number(animation.currentTime ?? 0);
8043
+ return Number.isFinite(endTime) ? Math.max(0, endTime - currentTime) : 0;
8044
+ }));
8045
+ const boundedWait = Math.min(10000, remainingMs + 50);
8046
+ timerId = window.setTimeout(finish, boundedWait);
8047
+ this._lifecycleTimers.add(timerId);
8048
+ };
8049
+ this._optionsContainer.addEventListener('wheel', cancelForUserInput, { passive: true });
8050
+ this._optionsContainer.addEventListener('touchstart', cancelForUserInput, { passive: true });
8051
+ this._optionsContainer.addEventListener('pointerdown', cancelForUserInput, { passive: true });
8052
+ this._optionsContainer.addEventListener('scroll', cancelForUserScroll, { passive: true });
8053
+ this._openSelectedScrollCleanup = cleanup;
8054
+ const frameId = requestAnimationFrame(() => {
8055
+ frameIds.delete(frameId);
8056
+ begin();
8057
+ });
8058
+ frameIds.add(frameId);
8059
+ }
8060
+ _cancelOpenSelectedScroll() {
8061
+ this._openSelectedScrollGeneration += 1;
8062
+ this._openSelectedScrollCleanup?.();
8063
+ this._openSelectedScrollCleanup = null;
8064
+ }
8065
+ _captureOptionsViewportAnchor() {
8066
+ const scroller = this._optionsContainer;
8067
+ const scrollTop = scroller.scrollTop;
8068
+ const order = this._renderPlan.filteredKeys.slice();
8069
+ const viewportTop = scroller.getBoundingClientRect().top + scroller.clientTop;
8070
+ const viewportBottom = viewportTop + scroller.clientHeight;
8071
+ const visible = Array.from(scroller.querySelectorAll('[data-sm-selectable], [data-selectable]'))
8072
+ .map((option) => ({ option, rect: option.getBoundingClientRect() }))
8073
+ .filter(({ rect }) => rect.height > 0 && rect.bottom > viewportTop && rect.top < viewportBottom)
8074
+ .sort((left, right) => left.rect.top - right.rect.top)[0];
8075
+ if (visible) {
8076
+ const sourceIndex = Number(visible.option.getAttribute('data-sm-index') ?? visible.option.getAttribute('data-index'));
8077
+ const key = Number.isInteger(sourceIndex) ? this._itemRegistry.indexToKey.get(sourceIndex) ?? null : null;
8078
+ if (key !== null) {
8079
+ return { key, offset: visible.rect.top - viewportTop, scrollTop, order };
8080
+ }
8081
+ }
8082
+ if (this._guardedVirtualizer && order.length > 0
8083
+ && typeof this._guardedVirtualizer.computeWindow === 'function') {
8084
+ const viewportHeight = this._resolveGuardedViewportHeight();
8085
+ const index = this._guardedVirtualizer.computeWindow(scrollTop, viewportHeight).startIndex;
8086
+ const key = order[index] ?? null;
8087
+ if (key !== null) {
8088
+ return {
8089
+ key,
8090
+ offset: this._guardedVirtualizer.cumulativeOffset(index) - scrollTop,
8091
+ scrollTop,
8092
+ order,
8093
+ };
8094
+ }
8095
+ }
8096
+ return { key: null, offset: 0, scrollTop, order };
8097
+ }
8098
+ /** Restore the previous visible option only when this opening changed order. */
8099
+ _restorePreservedOptionsViewport() {
8100
+ const anchor = this._openOptionsViewportAnchor;
8101
+ this._openOptionsViewportAnchor = null;
8102
+ if (!anchor)
8103
+ return;
8104
+ const nextOrder = this._renderPlan.filteredKeys;
8105
+ const nextPositionByKey = new Map(nextOrder.map((key, index) => [key, index]));
8106
+ const orderChanged = anchor.order.some((key, oldIndex) => {
8107
+ const nextIndex = nextPositionByKey.get(key);
8108
+ return nextIndex !== undefined && nextIndex !== oldIndex;
8109
+ });
8110
+ if (!orderChanged)
8111
+ return;
8112
+ const scroller = this._optionsContainer;
8113
+ const viewportHeight = this._resolveGuardedViewportHeight() || scroller.clientHeight;
8114
+ let targetScrollTop = null;
8115
+ if (anchor.key !== null) {
8116
+ const displayIndex = this._renderPlan.displayIndexByKey.get(anchor.key);
8117
+ if (displayIndex !== undefined) {
8118
+ const sourceIndex = this._renderPlan.sourceIndexByKey.get(anchor.key);
8119
+ const option = sourceIndex === undefined ? null : this._getOptionElementByIndex(sourceIndex);
8120
+ const viewportTop = scroller.getBoundingClientRect().top + scroller.clientTop;
8121
+ const optionTop = option?.getBoundingClientRect().top;
8122
+ if (option && option.getBoundingClientRect().height > 0 && Number.isFinite(optionTop)) {
8123
+ targetScrollTop = scroller.scrollTop + optionTop - viewportTop - anchor.offset;
8124
+ }
8125
+ else if (this._guardedVirtualizer) {
8126
+ targetScrollTop = this._guardedVirtualizer.cumulativeOffset(displayIndex) - anchor.offset;
8127
+ }
8128
+ }
8129
+ }
8130
+ if (targetScrollTop === null)
8131
+ targetScrollTop = anchor.scrollTop;
8132
+ let maxScrollTop = Number.POSITIVE_INFINITY;
8133
+ if (this._guardedVirtualizer) {
8134
+ maxScrollTop = Math.max(0, this._guardedVirtualizer.cumulativeOffset(nextOrder.length) - viewportHeight);
8135
+ }
8136
+ else if (scroller.scrollHeight > 0 && scroller.clientHeight > 0) {
8137
+ maxScrollTop = Math.max(0, scroller.scrollHeight - scroller.clientHeight);
8138
+ }
8139
+ targetScrollTop = Math.max(0, Math.min(targetScrollTop, maxScrollTop));
8140
+ if (Math.abs(targetScrollTop - scroller.scrollTop) < 1)
8141
+ return;
8142
+ // The coordinator owns this single restoration write. The virtualizer may
8143
+ // update its mounted window in response, but it must not issue a second
8144
+ // physical positioning correction for this transaction.
8145
+ this._guardedVirtualScrollTop = targetScrollTop;
8146
+ scroller.scrollTop = targetScrollTop;
8147
+ }
8148
+ /** Used only when Element.getAnimations() is unavailable. */
8149
+ _getDropdownEntranceFallbackDurationMs() {
8150
+ if (window.matchMedia?.('(prefers-reduced-motion: reduce)').matches)
8151
+ return 0;
8152
+ const style = getComputedStyle(this._dropdown);
8153
+ const parseTime = (value) => {
8154
+ const trimmed = value.trim();
8155
+ const parsed = Number.parseFloat(trimmed);
8156
+ if (!Number.isFinite(parsed))
8157
+ return 0;
8158
+ return trimmed.endsWith('ms') ? parsed : trimmed.endsWith('s') ? parsed * 1000 : 0;
8159
+ };
8160
+ const animationDurations = style.animationDuration.split(',');
8161
+ const animationDelays = style.animationDelay.split(',');
8162
+ const animationIterations = style.animationIterationCount.split(',');
8163
+ const maxAnimation = Math.max(0, ...animationDurations.map((duration, index) => {
8164
+ const count = Number.parseFloat(animationIterations[index % animationIterations.length] ?? '1');
8165
+ if (!Number.isFinite(count))
8166
+ return 0;
8167
+ return parseTime(duration)
8168
+ * Math.max(0, count)
8169
+ + parseTime(animationDelays[index % animationDelays.length] ?? '0s');
8170
+ }));
8171
+ const transitionDurations = style.transitionDuration.split(',');
8172
+ const transitionDelays = style.transitionDelay.split(',');
8173
+ const maxTransition = Math.max(0, ...transitionDurations.map((duration, index) => parseTime(duration) + parseTime(transitionDelays[index % transitionDelays.length] ?? '0s')));
8174
+ return Math.min(10000, Math.max(maxAnimation, maxTransition));
8175
+ }
7693
8176
  /** Stop an outstanding exit before reopening, disconnecting or starting another one. */
7694
8177
  _cancelDropdownExit() {
7695
8178
  if (this._dropdownExitTimer !== null) {
@@ -8044,26 +8527,38 @@
8044
8527
  case 'Home':
8045
8528
  e.preventDefault();
8046
8529
  if (this._state.isOpen) {
8530
+ if (this._usesSelectedFirstVisualOrder()) {
8531
+ this._moveToVisualBoundary('first', { shiftKey: e.shiftKey, toggleKey: e.ctrlKey || e.metaKey });
8532
+ break;
8533
+ }
8047
8534
  const selectableIndices = this._getSelectableOptionIndices();
8048
8535
  const firstIndex = selectableIndices[0];
8049
8536
  if (firstIndex === undefined)
8050
8537
  break;
8051
8538
  this._setActive(firstIndex);
8052
8539
  if (this._config.selection.mode === 'multi' && e.shiftKey) {
8053
- this._selectRange(this._rangeAnchorIndex ?? firstIndex, firstIndex, { clear: !(e.ctrlKey || e.metaKey) });
8540
+ const targetKey = this._itemRegistry.indexToKey.get(firstIndex);
8541
+ if (targetKey !== undefined)
8542
+ this._selectKeyboardRange(this._rangeAnchorKey ?? targetKey, targetKey, { clear: !(e.ctrlKey || e.metaKey) });
8054
8543
  }
8055
8544
  }
8056
8545
  break;
8057
8546
  case 'End':
8058
8547
  e.preventDefault();
8059
8548
  if (this._state.isOpen) {
8549
+ if (this._usesSelectedFirstVisualOrder()) {
8550
+ this._moveToVisualBoundary('last', { shiftKey: e.shiftKey, toggleKey: e.ctrlKey || e.metaKey });
8551
+ break;
8552
+ }
8060
8553
  const selectableIndices = this._getSelectableOptionIndices();
8061
8554
  const lastIndex = selectableIndices[selectableIndices.length - 1];
8062
8555
  if (lastIndex === undefined)
8063
8556
  break;
8064
8557
  this._setActive(lastIndex);
8065
8558
  if (this._config.selection.mode === 'multi' && e.shiftKey) {
8066
- this._selectRange(this._rangeAnchorIndex ?? lastIndex, lastIndex, { clear: !(e.ctrlKey || e.metaKey) });
8559
+ const targetKey = this._itemRegistry.indexToKey.get(lastIndex);
8560
+ if (targetKey !== undefined)
8561
+ this._selectKeyboardRange(this._rangeAnchorKey ?? targetKey, targetKey, { clear: !(e.ctrlKey || e.metaKey) });
8067
8562
  }
8068
8563
  }
8069
8564
  break;
@@ -8118,6 +8613,26 @@
8118
8613
  }
8119
8614
  }
8120
8615
  _moveActive(delta, opts) {
8616
+ if (this._usesSelectedFirstVisualOrder()) {
8617
+ const model = this._getVisualNavigationModel();
8618
+ if (model.selectableKeys.length === 0)
8619
+ return;
8620
+ const activeKey = this._engine.state.activeKey;
8621
+ const currentPosition = activeKey === null ? undefined : model.selectablePositionByKey.get(activeKey);
8622
+ // Load-more is only requested after movement reaches the actual visual end.
8623
+ if (delta === 1 && currentPosition === model.selectableKeys.length - 1 && this._requestKeyboardLoadMore())
8624
+ return;
8625
+ const nextKey = resolveVisualMovement(model, activeKey, delta);
8626
+ if (nextKey === null)
8627
+ return;
8628
+ this._setActiveForVisualKey(nextKey);
8629
+ if (this._config.selection.mode === 'multi' && opts?.shiftKey) {
8630
+ const anchorKey = this._rangeAnchorKey ?? activeKey ?? nextKey;
8631
+ this._rangeAnchorKey = anchorKey;
8632
+ this._selectKeyboardRange(anchorKey, nextKey, { clear: !opts.toggleKey });
8633
+ }
8634
+ return;
8635
+ }
8121
8636
  const selectableIndices = this._getSelectableOptionIndices();
8122
8637
  if (selectableIndices.length === 0)
8123
8638
  return;
@@ -8139,13 +8654,89 @@
8139
8654
  const next = selectableIndices[nextPosition];
8140
8655
  this._setActive(next);
8141
8656
  if (this._config.selection.mode === 'multi' && opts?.shiftKey) {
8142
- const anchor = this._rangeAnchorIndex ?? currentIndex;
8143
- const anchorIndex = anchor >= 0 ? anchor : next;
8144
- if (this._rangeAnchorIndex === null) {
8145
- this._rangeAnchorIndex = anchorIndex;
8146
- }
8147
- this._selectRange(anchorIndex, next, { clear: !opts?.toggleKey });
8657
+ const nextKey = this._itemRegistry.indexToKey.get(next);
8658
+ if (nextKey === undefined)
8659
+ return;
8660
+ const anchorKey = this._rangeAnchorKey ?? (currentIndex >= 0 ? this._itemRegistry.indexToKey.get(currentIndex) : undefined) ?? nextKey;
8661
+ this._rangeAnchorKey = anchorKey;
8662
+ this._selectKeyboardRange(anchorKey, nextKey, { clear: !opts?.toggleKey });
8663
+ }
8664
+ }
8665
+ _usesSelectedFirstVisualOrder() {
8666
+ return this._selectedOptionsConfigAtOpen.placement === 'selected-first';
8667
+ }
8668
+ _getVisualNavigationModel() {
8669
+ this._ensureRegistryCurrent();
8670
+ return createVisualNavigationModel(this._renderPlan.filteredKeys, (key) => {
8671
+ const record = this._itemRegistry.keyToRecord.get(key);
8672
+ if (!record || record.disabled)
8673
+ return false;
8674
+ const option = this._getOptionElementByIndex(record.index);
8675
+ return option?.getAttribute('aria-disabled') !== 'true';
8676
+ });
8677
+ }
8678
+ _setActiveForVisualKey(key, reason = 'keyboard', options = {}) {
8679
+ const sourceIndex = this._renderPlan.sourceIndexByKey.get(key)
8680
+ ?? this._itemRegistry.keyToIndex.get(key);
8681
+ if (sourceIndex === undefined)
8682
+ return;
8683
+ this._setActive(sourceIndex, reason, options);
8684
+ }
8685
+ _moveToVisualBoundary(boundary, opts) {
8686
+ const model = this._getVisualNavigationModel();
8687
+ const targetKey = resolveVisualBoundary(model, boundary);
8688
+ if (targetKey === null)
8689
+ return;
8690
+ const currentKey = this._engine.state.activeKey;
8691
+ this._setActiveForVisualKey(targetKey);
8692
+ if (this._config.selection.mode === 'multi' && opts?.shiftKey) {
8693
+ const anchorKey = this._rangeAnchorKey ?? currentKey ?? targetKey;
8694
+ this._rangeAnchorKey = anchorKey;
8695
+ this._selectKeyboardRange(anchorKey, targetKey, { clear: !opts.toggleKey });
8696
+ }
8697
+ }
8698
+ _selectKeyboardRange(anchorKey, targetKey, opts) {
8699
+ if (this._usesSelectedFirstVisualOrder()) {
8700
+ const model = this._getVisualNavigationModel();
8701
+ const resolvedAnchor = model.selectablePositionByKey.has(anchorKey) ? anchorKey : targetKey;
8702
+ this._rangeAnchorKey = resolvedAnchor;
8703
+ this._selectVisualRange(resolvedAnchor, targetKey, opts);
8704
+ return;
8705
+ }
8706
+ const start = this._itemRegistry.keyToIndex.get(anchorKey);
8707
+ const end = this._itemRegistry.keyToIndex.get(targetKey);
8708
+ if (start !== undefined && end !== undefined)
8709
+ this._selectRange(start, end, opts);
8710
+ }
8711
+ _selectVisualRange(anchorKey, targetKey, opts) {
8712
+ if (this._config.selection.mode !== 'multi')
8713
+ return;
8714
+ this._ensureRegistryCurrent();
8715
+ const model = this._getVisualNavigationModel();
8716
+ const rangeKeys = resolveVisualRange(model, anchorKey, targetKey);
8717
+ if (rangeKeys.length === 0)
8718
+ return;
8719
+ const selectedEntries = this._getSelectedEntries();
8720
+ const entries = opts?.clear
8721
+ ? selectedEntries.filter((entry) => !this._itemRegistry.keyToRecord.has(entry.key))
8722
+ : selectedEntries;
8723
+ for (const key of rangeKeys) {
8724
+ const record = this._itemRegistry.keyToRecord.get(key);
8725
+ if (!record || this._isOptionSelectionBlocked(record.item))
8726
+ continue;
8727
+ entries.push(record);
8148
8728
  }
8729
+ this._requestSelectionReplacement(entries, opts?.reason ?? 'keyboard', 'select visual range');
8730
+ this._renderOptions();
8731
+ this._updateInputDisplay();
8732
+ const target = this._itemRegistry.keyToRecord.get(targetKey);
8733
+ const selectDetail = target ? this._getSelectEventDetail(target) : null;
8734
+ if (selectDetail)
8735
+ this._emit('select', selectDetail);
8736
+ this._emitChange();
8737
+ this._announce(`${this._state.selectedIndices.size} items selected`);
8738
+ if (selectDetail)
8739
+ this._config.callbacks.onSelect?.(selectDetail);
8149
8740
  }
8150
8741
  /** Return true only when boundary navigation is held for an in-flight/new page. */
8151
8742
  _requestKeyboardLoadMore() {
@@ -8174,7 +8765,7 @@
8174
8765
  this._dispatchAcknowledgedActions(actions);
8175
8766
  return true;
8176
8767
  }
8177
- _setActive(index, reason = 'keyboard') {
8768
+ _setActive(index, reason = 'keyboard', options = {}) {
8178
8769
  this._ensureRegistryCurrent();
8179
8770
  const record = this._getRecordByIndex(index);
8180
8771
  let option = this._getOptionElementByIndex(index);
@@ -8185,8 +8776,10 @@
8185
8776
  if (!record || record.disabled || !option || option.getAttribute('aria-disabled') === 'true') {
8186
8777
  return;
8187
8778
  }
8188
- if (reason === 'keyboard')
8779
+ if (reason === 'keyboard' || reason === 'search') {
8189
8780
  this._keyboardActiveChangeGeneration += 1;
8781
+ this._cancelOpenSelectedScroll();
8782
+ }
8190
8783
  const previousIndex = this._state.activeIndex;
8191
8784
  this._dispatchActiveKey(record.key, reason, 'set active');
8192
8785
  if (this._state.activeIndex !== index)
@@ -8213,8 +8806,7 @@
8213
8806
  else {
8214
8807
  this._syncCustomOptionActiveClasses(option, true);
8215
8808
  }
8216
- if (typeof option.scrollIntoView === 'function') {
8217
- // Don't scroll wildly when just opening with pre-selections
8809
+ if (options.scroll !== false && typeof option.scrollIntoView === 'function') {
8218
8810
  option.scrollIntoView({ block: 'nearest', behavior: 'smooth' });
8219
8811
  }
8220
8812
  // Announce position for screen readers
@@ -8270,8 +8862,22 @@
8270
8862
  this._typeTimeout = window.setTimeout(() => {
8271
8863
  this._typeBuffer = '';
8272
8864
  }, 500);
8273
- // Find first matching option
8865
+ // Type-ahead uses the displayed candidate order when a presentation projection is active.
8274
8866
  const getValue = this._config.serverSide.getLabelFromItem || ((item) => item?.label ?? String(item));
8867
+ if (this._usesSelectedFirstVisualOrder()) {
8868
+ const model = this._getVisualNavigationModel();
8869
+ const matchKey = model.selectableKeys.find((key) => {
8870
+ const record = this._itemRegistry.keyToRecord.get(key);
8871
+ return record !== undefined && getValue(record.item).toLowerCase().startsWith(this._typeBuffer);
8872
+ });
8873
+ if (matchKey !== undefined) {
8874
+ const sourceIndex = this._renderPlan.sourceIndexByKey.get(matchKey)
8875
+ ?? this._itemRegistry.keyToIndex.get(matchKey);
8876
+ if (sourceIndex !== undefined)
8877
+ this._setActive(sourceIndex, 'search');
8878
+ }
8879
+ return;
8880
+ }
8275
8881
  const matchIndex = this._state.loadedItems.findIndex((item) => getValue(item).toLowerCase().startsWith(this._typeBuffer));
8276
8882
  if (matchIndex >= 0) {
8277
8883
  this._setActive(matchIndex, 'search');
@@ -8340,6 +8946,17 @@
8340
8946
  };
8341
8947
  }
8342
8948
  _setInitialActiveOption() {
8949
+ if (this._usesSelectedFirstVisualOrder()) {
8950
+ const model = this._getVisualNavigationModel();
8951
+ const selectedKey = model.selectableKeys.find((key) => this._engine.state.selectedKeys.has(key));
8952
+ if (selectedKey === undefined) {
8953
+ this._dispatchActiveKey(null, 'open', 'initial active option');
8954
+ return;
8955
+ }
8956
+ // Resolve via stable identity so the open-time projection remains authoritative.
8957
+ this._setActiveForVisualKey(selectedKey, 'open', { scroll: false });
8958
+ return;
8959
+ }
8343
8960
  const selectableIndices = this._getSelectableOptionIndices();
8344
8961
  const selected = Array.from(this._state.selectedIndices).sort((a, b) => a - b);
8345
8962
  // Opening an empty select must not implicitly assign an active descendant.
@@ -8349,7 +8966,9 @@
8349
8966
  return;
8350
8967
  }
8351
8968
  const target = selected.find((index) => selectableIndices.includes(index)) ?? selectableIndices[0];
8352
- this._setActive(target, 'open');
8969
+ // Set logical active state and ARIA immediately. The open-time coordinator
8970
+ // owns any physical positioning after the dropdown's entrance settles.
8971
+ this._setActive(target, 'open', { scroll: false });
8353
8972
  }
8354
8973
  _announce(message) {
8355
8974
  const effects = computeAccessibilityEffects(deriveAccessibilityState(this._engine.state), {
@@ -8403,9 +9022,10 @@
8403
9022
  const toggleKey = Boolean(opts?.toggleKey);
8404
9023
  const shiftKey = Boolean(opts?.shiftKey);
8405
9024
  if (shiftKey) {
8406
- const anchor = this._rangeAnchorIndex ?? index;
8407
- this._selectRange(anchor, index, { clear: !toggleKey, reason });
8408
- this._rangeAnchorIndex = anchor;
9025
+ const targetKey = record.key;
9026
+ const anchorKey = this._rangeAnchorKey ?? targetKey;
9027
+ this._selectKeyboardRange(anchorKey, targetKey, { clear: !toggleKey, reason });
9028
+ this._rangeAnchorKey = anchorKey;
8409
9029
  return;
8410
9030
  }
8411
9031
  // Multi select with toggle
@@ -8419,7 +9039,7 @@
8419
9039
  // Re-render to update styles (safer than trying to find the element in filtered list)
8420
9040
  this._renderOptions();
8421
9041
  }
8422
- this._rangeAnchorIndex = index;
9042
+ this._rangeAnchorKey = record.key;
8423
9043
  this._updateInputDisplay();
8424
9044
  const selectDetail = this._getSelectEventDetail(record);
8425
9045
  this._emit('select', selectDetail);
@@ -8678,58 +9298,71 @@
8678
9298
  this._optionsContainer.style.transition = 'opacity 0.2s ease-in';
8679
9299
  }, 150);
8680
9300
  }
8681
- _scrollToSelected() {
8682
- if (this._state.selectedIndices.size === 0)
8683
- return;
8684
- const target = this._config.scrollToSelected.multiSelectTarget;
8685
- const indices = Array.from(this._state.selectedIndices).filter((index) => index >= 0).sort((a, b) => a - b);
8686
- if (indices.length === 0)
8687
- return;
8688
- // For multi-select, find the closest selected item to the current scroll position
8689
- let targetIndex;
8690
- if (this._config.selection.mode === 'multi' && indices.length > 1) {
8691
- // Calculate which selected item is closest to the center of the viewport
8692
- const dropdownRect = this._dropdown.getBoundingClientRect();
8693
- const viewportCenter = this._dropdown.scrollTop + (dropdownRect.height / 2);
8694
- // Find the selected item closest to viewport center
8695
- let closestIndex = indices[0];
8696
- let closestDistance = Infinity;
8697
- for (const index of indices) {
8698
- const option = this._getOptionElementByIndex(index);
8699
- if (option) {
8700
- const optionTop = option.offsetTop;
8701
- const distance = Math.abs(optionTop - viewportCenter);
8702
- if (distance < closestDistance) {
8703
- closestDistance = distance;
8704
- closestIndex = index;
8705
- }
8706
- }
8707
- }
8708
- targetIndex = closestIndex;
8709
- }
8710
- else {
8711
- // For single select or only one selected item, use the configured target
8712
- targetIndex = target === 'first' ? indices[0] : indices[indices.length - 1];
8713
- }
8714
- // Find and scroll to the target option
9301
+ _scrollToSelected(options = {}) {
9302
+ const config = options.config ?? this._config.scrollToSelected;
9303
+ if (!config.enabled)
9304
+ return;
9305
+ const targetKey = resolveSelectedTargetKey(this._renderPlan.filteredKeys, this._engine.state.selectedKeys, config.multiSelectTarget);
9306
+ if (targetKey === null)
9307
+ return;
9308
+ const targetIndex = this._renderPlan.sourceIndexByKey.get(targetKey)
9309
+ ?? this._itemRegistry.keyToIndex.get(targetKey);
9310
+ if (targetIndex === undefined)
9311
+ return;
9312
+ // Resolve against the current eligible render plan first. A selected key
9313
+ // outside the filtered projection must never trigger materialization.
8715
9314
  let option = this._getOptionElementByIndex(targetIndex);
8716
9315
  if (!option && this._guardedVirtualizer) {
8717
- const targetKey = this._itemRegistry.indexToKey.get(targetIndex);
8718
- if (targetKey !== undefined) {
8719
- this._materializeGuardedVirtualKey(targetKey);
8720
- option = this._getOptionElementByIndex(targetIndex);
8721
- }
9316
+ this._materializeGuardedVirtualKey(targetKey);
9317
+ option = this._getOptionElementByIndex(targetIndex);
8722
9318
  }
8723
9319
  if (option) {
8724
- // Use smooth scrolling with center alignment for better UX
8725
- if (typeof option.scrollIntoView === 'function') {
8726
- option.scrollIntoView({
8727
- block: this._config.scrollToSelected.block || 'center',
8728
- behavior: 'smooth',
8729
- });
9320
+ const reducedMotion = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches ?? false;
9321
+ this._scrollOptionWithinOptionsContainer(option, config.block || 'nearest', reducedMotion && config.behavior === 'smooth' ? 'auto' : (config.behavior || 'smooth'), options.onlyIfNeeded === true);
9322
+ if (options.setActive !== false) {
9323
+ // Active/ARIA synchronization must not start a second physical scroll.
9324
+ this._setActive(targetIndex, 'programmatic', { scroll: false });
8730
9325
  }
8731
- // Also set it as active for keyboard navigation
8732
- this._setActive(targetIndex, 'programmatic');
9326
+ }
9327
+ }
9328
+ _scrollOptionWithinOptionsContainer(option, block, behavior, onlyIfNeeded) {
9329
+ const scroller = this._optionsContainer;
9330
+ const scrollerRect = scroller.getBoundingClientRect();
9331
+ const viewportTop = scrollerRect.top + scroller.clientTop;
9332
+ const viewportBottom = viewportTop + scroller.clientHeight;
9333
+ const optionRect = option.getBoundingClientRect();
9334
+ if (onlyIfNeeded && optionRect.top >= viewportTop && optionRect.bottom <= viewportBottom)
9335
+ return;
9336
+ if (scroller.clientHeight <= 0 || optionRect.height <= 0)
9337
+ return;
9338
+ let targetScrollTop = scroller.scrollTop;
9339
+ if (block === 'start') {
9340
+ targetScrollTop += optionRect.top - viewportTop;
9341
+ }
9342
+ else if (block === 'center') {
9343
+ targetScrollTop += (optionRect.top + optionRect.bottom - viewportTop - viewportBottom) / 2;
9344
+ }
9345
+ else if (block === 'end') {
9346
+ targetScrollTop += optionRect.bottom - viewportBottom;
9347
+ }
9348
+ else if (optionRect.top < viewportTop) {
9349
+ targetScrollTop += optionRect.top - viewportTop;
9350
+ }
9351
+ else if (optionRect.bottom > viewportBottom) {
9352
+ targetScrollTop += optionRect.bottom - viewportBottom;
9353
+ }
9354
+ else {
9355
+ return;
9356
+ }
9357
+ const maxScrollTop = Math.max(0, scroller.scrollHeight - scroller.clientHeight);
9358
+ targetScrollTop = Math.max(0, Math.min(targetScrollTop, maxScrollTop));
9359
+ if (Math.abs(targetScrollTop - scroller.scrollTop) < 1)
9360
+ return;
9361
+ if (typeof scroller.scrollTo === 'function') {
9362
+ scroller.scrollTo({ top: targetScrollTop, behavior });
9363
+ }
9364
+ else {
9365
+ scroller.scrollTop = targetScrollTop;
8733
9366
  }
8734
9367
  }
8735
9368
  async _loadMoreItems(trigger = 'manual') {
@@ -9215,10 +9848,21 @@
9215
9848
  this._invalidateGuardedMeasurements();
9216
9849
  const previousMode = this._config.selection.mode;
9217
9850
  const previousEnabled = this._config.enabled;
9851
+ const previousOpenScrollEnabled = this._config.scrollToSelected.enabled;
9218
9852
  const previousDataLoadingConfig = this._dataLoadingConfig;
9219
9853
  let searchEligibilityBecameInactive = false;
9220
- const { dataLoading, callbacks, ...legacyConfig } = config;
9854
+ const { dataLoading, callbacks, selectedOptions, scrollToSelected, ...legacyConfig } = config;
9221
9855
  const legacyUpdate = { ...legacyConfig };
9856
+ if (selectedOptions !== undefined) {
9857
+ const validation = validateSelectedOptionsConfig(selectedOptions);
9858
+ if (validation.valid)
9859
+ legacyUpdate.selectedOptions = validation.value;
9860
+ }
9861
+ if (scrollToSelected !== undefined) {
9862
+ const validation = validateScrollToSelectedConfig(scrollToSelected);
9863
+ if (validation.valid)
9864
+ legacyUpdate.scrollToSelected = validation.value;
9865
+ }
9222
9866
  let configErrorDetail;
9223
9867
  if (callbacks !== undefined && callbacks !== null) {
9224
9868
  const callbackInput = callbacks;
@@ -9238,6 +9882,10 @@
9238
9882
  legacyUpdate.callbacks = legacyCallbacks;
9239
9883
  }
9240
9884
  this._config = this._mergeConfig(this._config, legacyUpdate);
9885
+ if (previousOpenScrollEnabled && !this._config.scrollToSelected.enabled) {
9886
+ this._openOptionsViewportAnchor = null;
9887
+ this._cancelOpenSelectedScroll();
9888
+ }
9241
9889
  if (dataLoading !== undefined) {
9242
9890
  const dataLoadingPrototype = dataLoading !== null && typeof dataLoading === 'object'
9243
9891
  ? Object.getPrototypeOf(dataLoading)
@@ -9784,19 +10432,39 @@
9784
10432
  activeKey: this._engine.state.activeKey,
9785
10433
  };
9786
10434
  }
9787
- _createLegacyRenderPlan(filteredIndices) {
9788
- const indices = [...filteredIndices];
9789
- const filteredKeys = indices
9790
- .map((index) => this._itemRegistry.indexToKey.get(index))
9791
- .filter((key) => key !== undefined);
9792
- const filteredIndexByKey = new Map();
9793
- filteredKeys.forEach((key, filteredIndex) => filteredIndexByKey.set(key, filteredIndex));
10435
+ _createLegacyRenderPlan(filteredIndices, groupedPresentation = []) {
10436
+ const sourceIndices = [...filteredIndices];
10437
+ const sourceOrderedKeys = groupedPresentation.length > 0
10438
+ ? groupedPresentation.flatMap((group) => group.orderedKeys)
10439
+ : sourceIndices
10440
+ .map((index) => this._itemRegistry.indexToKey.get(index))
10441
+ .filter((key) => key !== undefined);
10442
+ const shouldProjectSelectedFirst = this._usesSelectedFirstVisualOrder()
10443
+ && groupedPresentation.length === 0;
10444
+ const selectedKeys = this._selectedOptionsSelectionAtOpen ?? this._engine.state.selectedKeys;
10445
+ const filteredKeys = shouldProjectSelectedFirst
10446
+ ? projectSelectedOptionKeys(sourceOrderedKeys, selectedKeys)
10447
+ : sourceOrderedKeys;
10448
+ const indices = filteredKeys
10449
+ .map((key) => this._itemRegistry.keyToIndex.get(key))
10450
+ .filter((index) => index !== undefined);
10451
+ const displayIndexByKey = new Map();
10452
+ const sourceIndexByKey = new Map();
10453
+ filteredKeys.forEach((key, displayIndex) => {
10454
+ displayIndexByKey.set(key, displayIndex);
10455
+ const sourceIndex = this._itemRegistry.keyToIndex.get(key);
10456
+ if (sourceIndex !== undefined)
10457
+ sourceIndexByKey.set(key, sourceIndex);
10458
+ });
9794
10459
  return {
9795
10460
  mode: 'legacy-full',
9796
10461
  filteredIndices: indices,
9797
10462
  filteredKeys,
9798
10463
  intendedRenderKeys: filteredKeys.slice(),
9799
- filteredIndexByKey,
10464
+ displayIndexByKey,
10465
+ sourceIndexByKey,
10466
+ filteredIndexByKey: displayIndexByKey,
10467
+ groupedPresentation,
9800
10468
  };
9801
10469
  }
9802
10470
  _createVirtualRenderPlan(startIndex, endIndex) {
@@ -9805,12 +10473,16 @@
9805
10473
  const filteredIndices = intendedRenderKeys
9806
10474
  .map((key) => this._itemRegistry.keyToIndex.get(key))
9807
10475
  .filter((index) => index !== undefined);
10476
+ const displayIndexByKey = new Map(this._renderPlan.displayIndexByKey);
9808
10477
  return {
9809
10478
  mode: 'virtual-window',
9810
10479
  filteredIndices,
9811
10480
  filteredKeys,
9812
10481
  intendedRenderKeys,
9813
- filteredIndexByKey: new Map(this._renderPlan.filteredIndexByKey),
10482
+ displayIndexByKey,
10483
+ sourceIndexByKey: new Map(this._renderPlan.sourceIndexByKey),
10484
+ filteredIndexByKey: displayIndexByKey,
10485
+ groupedPresentation: this._renderPlan.groupedPresentation,
9814
10486
  };
9815
10487
  }
9816
10488
  _ensureGuardedVirtualizer(filteredKeys) {
@@ -10764,11 +11436,31 @@
10764
11436
  // Handle Grouped Items Rendering (when no search query)
10765
11437
  if (this._state.groupedItems.length > 0 && !query) {
10766
11438
  this._destroyGuardedVirtualizer();
10767
- this._renderPlan = this._createLegacyRenderPlan(this._itemRegistry.records.map((record) => record.index));
11439
+ const groupedSource = this._state.groupedItems.map((group, groupIndex) => ({
11440
+ group,
11441
+ groupIndex,
11442
+ orderedKeys: group.options
11443
+ .map((item) => this._state.loadedItems.indexOf(item))
11444
+ .filter((index) => index >= 0)
11445
+ .map((index) => this._itemRegistry.indexToKey.get(index))
11446
+ .filter((key) => key !== undefined),
11447
+ }));
11448
+ const groupedOrder = this._usesSelectedFirstVisualOrder()
11449
+ ? projectSelectedOptionGroups(groupedSource.map(({ groupIndex, orderedKeys }) => ({ groupIdentity: groupIndex, orderedKeys })), this._selectedOptionsSelectionAtOpen ?? this._engine.state.selectedKeys)
11450
+ : groupedSource.map(({ groupIndex, orderedKeys }) => ({ groupIdentity: groupIndex, orderedKeys }));
11451
+ const groupedPresentation = groupedOrder.map(({ groupIdentity, orderedKeys }) => ({
11452
+ group: this._state.groupedItems[groupIdentity],
11453
+ groupIndex: groupIdentity,
11454
+ orderedKeys,
11455
+ }));
11456
+ const groupedIndices = groupedPresentation.flatMap(({ orderedKeys }) => orderedKeys
11457
+ .map((key) => this._itemRegistry.keyToIndex.get(key))
11458
+ .filter((index) => index !== undefined));
11459
+ this._renderPlan = this._createLegacyRenderPlan(groupedIndices, groupedPresentation);
10768
11460
  filteredIndicesForScope = this._renderPlan.filteredIndices;
10769
11461
  this._registerShadowItems(filteredIndicesForScope);
10770
11462
  this._refreshVirtualizationScope(filteredIndicesForScope);
10771
- this._state.groupedItems.forEach((group, groupIndex) => {
11463
+ this._renderPlan.groupedPresentation.forEach(({ group, groupIndex, orderedKeys }) => {
10772
11464
  let header;
10773
11465
  if (this.groupHeaderRenderer) {
10774
11466
  header = this.groupHeaderRenderer(group, groupIndex);
@@ -10794,10 +11486,10 @@
10794
11486
  }
10795
11487
  header.setAttribute('part', 'group-header');
10796
11488
  this._optionsContainer.appendChild(header);
10797
- group.options.forEach(item => {
10798
- // Find original index for correct ID generation and selection
10799
- const index = this._state.loadedItems.indexOf(item);
10800
- if (index !== -1) {
11489
+ orderedKeys.forEach((key) => {
11490
+ const index = this._itemRegistry.keyToIndex.get(key);
11491
+ if (index !== undefined) {
11492
+ const item = this._state.loadedItems[index];
10801
11493
  this._renderSingleOption(item, index, getValue, getLabel);
10802
11494
  }
10803
11495
  });
@@ -10866,13 +11558,16 @@
10866
11558
  const chunkSize = 80;
10867
11559
  let cursor = 0;
10868
11560
  let maxRenderTarget = 0;
10869
- if (this._state.selectedIndices.size > 0 && this._config.scrollToSelected.enabled) {
10870
- const indices = Array.from(this._state.selectedIndices).filter((index) => index >= 0).sort((a, b) => a - b);
10871
- const targetIndex = this._config.scrollToSelected.multiSelectTarget === 'first' ? indices[0] : indices[indices.length - 1];
10872
- const filteredPos = filteredIndices.indexOf(targetIndex);
10873
- if (filteredPos !== -1) {
10874
- maxRenderTarget = filteredPos + 20; // Ensure we render up to the selection
10875
- }
11561
+ if (this._state.isOpen
11562
+ && this._config.scrollToSelected.enabled
11563
+ && this._scrollToSelectedConfigAtOpen.enabled
11564
+ && this._scrollToSelectedConfigAtOpen.onOpen !== 'preserve') {
11565
+ const targetKey = resolveSelectedTargetKey(this._renderPlan.filteredKeys, this._engine.state.selectedKeys, this._scrollToSelectedConfigAtOpen.multiSelectTarget);
11566
+ const targetPosition = targetKey === null
11567
+ ? undefined
11568
+ : this._renderPlan.displayIndexByKey.get(targetKey);
11569
+ if (targetPosition !== undefined)
11570
+ maxRenderTarget = targetPosition + 20;
10876
11571
  }
10877
11572
  const renderChunk = () => {
10878
11573
  if (renderCycleId !== this._renderCycleId) {
@@ -12382,6 +13077,9 @@
12382
13077
  exports.toggleClass = toggleClass;
12383
13078
  exports.transition = transition;
12384
13079
  exports.validateDataLoadingConfig = validateDataLoadingConfig;
13080
+ exports.validateScrollToSelectedConfig = validateScrollToSelectedConfig;
13081
+ exports.validateSelectedOptionsConfig = validateSelectedOptionsConfig;
13082
+ exports.validateSelectedOptionsConfigUpdate = validateSelectedOptionsConfigUpdate;
12385
13083
  exports.validateTemplate = validateTemplate;
12386
13084
  exports.valuesEqual = valuesEqual;
12387
13085
  exports.warnCSPViolation = warnCSPViolation;