@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.js CHANGED
@@ -2072,6 +2072,123 @@ if (!customElements.get("smilodon-select")) {
2072
2072
  customElements.define("smilodon-select", NativeSelectElement);
2073
2073
  }
2074
2074
 
2075
+ const SELECTED_OPTIONS_FIELDS = new Set(['placement', 'groupedPlacement']);
2076
+ const SCROLL_TO_SELECTED_FIELDS = new Set([
2077
+ 'enabled',
2078
+ 'multiSelectTarget',
2079
+ 'onOpen',
2080
+ 'behavior',
2081
+ 'block',
2082
+ ]);
2083
+ const placements = new Set(['original', 'selected-first']);
2084
+ const groupedPlacements = new Set(['within-group']);
2085
+ const scrollTargets = new Set(['first', 'last']);
2086
+ const openPolicies = new Set(['preserve', 'reveal', 'align']);
2087
+ const scrollBehaviors = new Set(['auto', 'instant', 'smooth']);
2088
+ const scrollBlocks = new Set(['start', 'center', 'end', 'nearest']);
2089
+ function asPlainRecord(value) {
2090
+ if (value === null || typeof value !== 'object' || Array.isArray(value))
2091
+ return null;
2092
+ const prototype = Object.getPrototypeOf(value);
2093
+ return prototype === Object.prototype || prototype === null ? value : null;
2094
+ }
2095
+ function unknownFieldIssues(record, allowed) {
2096
+ return Object.keys(record)
2097
+ .filter((key) => !allowed.has(key))
2098
+ .sort()
2099
+ .map((key) => ({
2100
+ path: key,
2101
+ code: 'unknown-field',
2102
+ message: `Unknown configuration field: ${key}.`,
2103
+ }));
2104
+ }
2105
+ function validateEnum(record, field, allowed, issues) {
2106
+ const value = record[field];
2107
+ if (value === undefined)
2108
+ return;
2109
+ if (typeof value !== 'string') {
2110
+ issues.push({ path: field, code: 'invalid-type', message: `${field} must be a string.` });
2111
+ }
2112
+ else if (!allowed.has(value)) {
2113
+ issues.push({ path: field, code: 'invalid-value', message: `${field} has an unsupported value.` });
2114
+ }
2115
+ }
2116
+ /** Validate a partial selected-options configuration update. */
2117
+ function validateSelectedOptionsConfig(candidate) {
2118
+ const record = asPlainRecord(candidate);
2119
+ if (!record) {
2120
+ return {
2121
+ valid: false,
2122
+ issues: [{ path: 'selectedOptions', code: 'invalid-type', message: 'selectedOptions must be a plain object.' }],
2123
+ };
2124
+ }
2125
+ const issues = unknownFieldIssues(record, SELECTED_OPTIONS_FIELDS);
2126
+ validateEnum(record, 'placement', placements, issues);
2127
+ validateEnum(record, 'groupedPlacement', groupedPlacements, issues);
2128
+ if (issues.length > 0)
2129
+ return { valid: false, issues };
2130
+ return {
2131
+ valid: true,
2132
+ value: {
2133
+ ...(record.placement === undefined ? {} : { placement: record.placement }),
2134
+ ...(record.groupedPlacement === undefined
2135
+ ? {}
2136
+ : { groupedPlacement: record.groupedPlacement }),
2137
+ },
2138
+ };
2139
+ }
2140
+ /** Validate a partial scroll-to-selected configuration update. */
2141
+ function validateScrollToSelectedConfig(candidate) {
2142
+ const record = asPlainRecord(candidate);
2143
+ if (!record) {
2144
+ return {
2145
+ valid: false,
2146
+ issues: [{ path: 'scrollToSelected', code: 'invalid-type', message: 'scrollToSelected must be a plain object.' }],
2147
+ };
2148
+ }
2149
+ const issues = unknownFieldIssues(record, SCROLL_TO_SELECTED_FIELDS);
2150
+ if (record.enabled !== undefined && typeof record.enabled !== 'boolean') {
2151
+ issues.push({ path: 'enabled', code: 'invalid-type', message: 'enabled must be a boolean.' });
2152
+ }
2153
+ validateEnum(record, 'multiSelectTarget', scrollTargets, issues);
2154
+ validateEnum(record, 'onOpen', openPolicies, issues);
2155
+ validateEnum(record, 'behavior', scrollBehaviors, issues);
2156
+ validateEnum(record, 'block', scrollBlocks, issues);
2157
+ if (issues.length > 0)
2158
+ return { valid: false, issues };
2159
+ return {
2160
+ valid: true,
2161
+ value: {
2162
+ ...(record.enabled === undefined ? {} : { enabled: record.enabled }),
2163
+ ...(record.multiSelectTarget === undefined
2164
+ ? {}
2165
+ : { multiSelectTarget: record.multiSelectTarget }),
2166
+ ...(record.onOpen === undefined ? {} : { onOpen: record.onOpen }),
2167
+ ...(record.behavior === undefined ? {} : { behavior: record.behavior }),
2168
+ ...(record.block === undefined ? {} : { block: record.block }),
2169
+ },
2170
+ };
2171
+ }
2172
+ /** Validate and copy only the new public configuration sections. */
2173
+ function validateSelectedOptionsConfigUpdate(config) {
2174
+ const result = { ...config };
2175
+ if (config.selectedOptions !== undefined) {
2176
+ const validation = validateSelectedOptionsConfig(config.selectedOptions);
2177
+ if (validation.valid)
2178
+ result.selectedOptions = validation.value;
2179
+ else
2180
+ delete result.selectedOptions;
2181
+ }
2182
+ if (config.scrollToSelected !== undefined) {
2183
+ const validation = validateScrollToSelectedConfig(config.scrollToSelected);
2184
+ if (validation.valid)
2185
+ result.scrollToSelected = validation.value;
2186
+ else
2187
+ delete result.scrollToSelected;
2188
+ }
2189
+ return result;
2190
+ }
2191
+
2075
2192
  /**
2076
2193
  * Global Configuration System for Select Components
2077
2194
  * Allows users to define default behaviors that can be overridden at component level
@@ -2111,9 +2228,14 @@ const defaultConfig = {
2111
2228
  scrollToSelected: {
2112
2229
  enabled: true,
2113
2230
  multiSelectTarget: 'first',
2231
+ onOpen: 'reveal',
2114
2232
  behavior: 'smooth',
2115
2233
  block: 'nearest',
2116
2234
  },
2235
+ selectedOptions: {
2236
+ placement: 'original',
2237
+ groupedPlacement: 'within-group',
2238
+ },
2117
2239
  loadMore: {
2118
2240
  enabled: false,
2119
2241
  itemsPerLoad: 3,
@@ -2196,7 +2318,8 @@ class SelectConfigManager {
2196
2318
  * Update global configuration (deep merge)
2197
2319
  */
2198
2320
  updateConfig(updates) {
2199
- this.config = this.deepMerge(this.config, updates);
2321
+ const acceptedUpdates = validateSelectedOptionsConfigUpdate(updates);
2322
+ this.config = this.deepMerge(this.config, acceptedUpdates);
2200
2323
  }
2201
2324
  /**
2202
2325
  * Reset to default configuration
@@ -3157,6 +3280,94 @@ function arraysEqualByValue(a, b) {
3157
3280
  return true;
3158
3281
  }
3159
3282
 
3283
+ function createVisualNavigationModel(orderedKeys, isSelectable) {
3284
+ const ordered = [...orderedKeys];
3285
+ const selectableKeys = [];
3286
+ const positionByKey = new Map();
3287
+ const selectablePositionByKey = new Map();
3288
+ ordered.forEach((key, position) => {
3289
+ positionByKey.set(key, position);
3290
+ if (isSelectable(key)) {
3291
+ selectablePositionByKey.set(key, selectableKeys.length);
3292
+ selectableKeys.push(key);
3293
+ }
3294
+ });
3295
+ return { orderedKeys: ordered, selectableKeys, positionByKey, selectablePositionByKey };
3296
+ }
3297
+ /** Resolve a clamped keyboard movement in visual order. */
3298
+ function resolveVisualMovement(model, currentKey, delta) {
3299
+ const { selectableKeys, selectablePositionByKey } = model;
3300
+ if (selectableKeys.length === 0)
3301
+ return null;
3302
+ const currentPosition = currentKey === null ? undefined : selectablePositionByKey.get(currentKey);
3303
+ const basePosition = currentPosition ?? (delta >= 0 ? -1 : selectableKeys.length);
3304
+ const nextPosition = Math.max(0, Math.min(selectableKeys.length - 1, basePosition + delta));
3305
+ return selectableKeys[nextPosition] ?? null;
3306
+ }
3307
+ function resolveVisualBoundary(model, boundary) {
3308
+ return boundary === 'first'
3309
+ ? model.selectableKeys[0] ?? null
3310
+ : model.selectableKeys[model.selectableKeys.length - 1] ?? null;
3311
+ }
3312
+ /** Return selectable keys in the inclusive visual interval between two keys. */
3313
+ function resolveVisualRange(model, startKey, endKey) {
3314
+ const startPosition = model.positionByKey.get(startKey);
3315
+ const endPosition = model.positionByKey.get(endKey);
3316
+ if (startPosition === undefined || endPosition === undefined)
3317
+ return [];
3318
+ const low = Math.min(startPosition, endPosition);
3319
+ const high = Math.max(startPosition, endPosition);
3320
+ const selectable = new Set(model.selectableKeys);
3321
+ return model.orderedKeys.slice(low, high + 1).filter((key) => selectable.has(key));
3322
+ }
3323
+
3324
+ /**
3325
+ * Return a presentation-only ordering for option keys.
3326
+ *
3327
+ * The source array and selection set are never mutated. Callers remain
3328
+ * responsible for retaining the returned order as the displayed ordering for
3329
+ * the relevant render/open transaction.
3330
+ */
3331
+ function projectSelectedOptionKeys(orderedKeys, selectedKeys, placement) {
3332
+ const selected = [];
3333
+ const unselected = [];
3334
+ for (const key of orderedKeys) {
3335
+ (selectedKeys.has(key) ? selected : unselected).push(key);
3336
+ }
3337
+ return [...selected, ...unselected];
3338
+ }
3339
+ /**
3340
+ * Stably partitions selected keys to the front of each group independently.
3341
+ * Group order, identity, membership, and the source arrays are preserved.
3342
+ */
3343
+ function projectSelectedOptionGroups(groups, selectedKeys) {
3344
+ return groups.map(({ groupIdentity, orderedKeys }) => {
3345
+ const selected = [];
3346
+ const unselected = [];
3347
+ for (const key of orderedKeys) {
3348
+ (selectedKeys.has(key) ? selected : unselected).push(key);
3349
+ }
3350
+ return { groupIdentity, orderedKeys: [...selected, ...unselected] };
3351
+ });
3352
+ }
3353
+
3354
+ /** Resolve the selected key at an edge of the displayed eligible ordering. */
3355
+ function resolveSelectedTargetKey(orderedKeys, selectedKeys, target) {
3356
+ if (target === 'first') {
3357
+ for (const key of orderedKeys) {
3358
+ if (selectedKeys.has(key))
3359
+ return key;
3360
+ }
3361
+ return null;
3362
+ }
3363
+ for (let index = orderedKeys.length - 1; index >= 0; index -= 1) {
3364
+ const key = orderedKeys[index];
3365
+ if (selectedKeys.has(key))
3366
+ return key;
3367
+ }
3368
+ return null;
3369
+ }
3370
+
3160
3371
  /**
3161
3372
  * DOM-independent coordinator for the opt-in acknowledged data-loading
3162
3373
  * protocol. This module is intentionally not re-exported from the package
@@ -4251,8 +4462,27 @@ class EnhancedSelect extends HTMLElement {
4251
4462
  filteredIndices: [],
4252
4463
  filteredKeys: [],
4253
4464
  intendedRenderKeys: [],
4465
+ displayIndexByKey: new Map(),
4466
+ sourceIndexByKey: new Map(),
4254
4467
  filteredIndexByKey: new Map(),
4468
+ groupedPresentation: [],
4469
+ };
4470
+ // Presentation policy and membership are snapshotted when the dropdown opens
4471
+ // so selection/config updates cannot reorder an active list.
4472
+ this._selectedOptionsSelectionAtOpen = null;
4473
+ this._selectedOptionsConfigAtOpen = {
4474
+ placement: 'original',
4475
+ groupedPlacement: 'within-group',
4476
+ };
4477
+ this._scrollToSelectedConfigAtOpen = {
4478
+ enabled: true,
4479
+ multiSelectTarget: 'first',
4480
+ onOpen: 'reveal',
4481
+ behavior: 'smooth',
4482
+ block: 'nearest',
4255
4483
  };
4484
+ this._closedOptionsViewportAnchor = null;
4485
+ this._openOptionsViewportAnchor = null;
4256
4486
  this._emptyStateContext = null;
4257
4487
  // Null keeps the public/default renderer on its legacy full path. This
4258
4488
  // private state is only used by guarded virtualization integration.
@@ -4309,7 +4539,7 @@ class EnhancedSelect extends HTMLElement {
4309
4539
  this._boundArrowClick = null;
4310
4540
  this._pendingFirstRenderMark = false;
4311
4541
  this._pendingSearchRenderMark = false;
4312
- this._rangeAnchorIndex = null;
4542
+ this._rangeAnchorKey = null;
4313
4543
  /** Chip identity is tracked independently of dropdown option positions. */
4314
4544
  this._lastRenderedChipKeys = null;
4315
4545
  this._latestChipScrollGeneration = 0;
@@ -4327,6 +4557,9 @@ class EnhancedSelect extends HTMLElement {
4327
4557
  this._lifecycleTimers = new Set();
4328
4558
  this._lifecycleRafs = new Set();
4329
4559
  this._keyboardActiveChangeGeneration = 0;
4560
+ /** Invalidates selected-option positioning scheduled by an earlier opening. */
4561
+ this._openSelectedScrollGeneration = 0;
4562
+ this._openSelectedScrollCleanup = null;
4330
4563
  this._tracking = { events: [], styles: [], limitations: [] };
4331
4564
  this._suppressBlurClose = false;
4332
4565
  this._renderCycleId = 0;
@@ -4504,6 +4737,7 @@ class EnhancedSelect extends HTMLElement {
4504
4737
  this._syncListboxAccessibility();
4505
4738
  }
4506
4739
  disconnectedCallback() {
4740
+ this._cancelOpenSelectedScroll();
4507
4741
  this._cancelLatestChipScroll();
4508
4742
  this._cancelBusyPresentation();
4509
4743
  if (this._dataRequestCoordinator) {
@@ -5090,12 +5324,12 @@ class EnhancedSelect extends HTMLElement {
5090
5324
  duplicateKeyPolicy: this._getDuplicateKeyPolicy(),
5091
5325
  });
5092
5326
  const activeKey = this._engine.state.activeKey;
5093
- const anchorKey = this._rangeAnchorIndex === null ? undefined : this._itemRegistry.indexToKey.get(this._rangeAnchorIndex);
5327
+ const anchorKey = this._rangeAnchorKey;
5094
5328
  this._itemRegistry = registry;
5095
5329
  this._state.loadedItems = items;
5096
5330
  this._registryItemsRef = items;
5097
5331
  const disabledKeys = this._getBlockedDisabledKeys();
5098
- this._rangeAnchorIndex = anchorKey === undefined ? null : registry.keyToIndex.get(anchorKey) ?? null;
5332
+ this._rangeAnchorKey = anchorKey !== null && registry.keyToRecord.has(anchorKey) ? anchorKey : null;
5099
5333
  this._engine.dispatch({
5100
5334
  type: 'ITEMS_REGISTERED',
5101
5335
  keys: registry.records.map((record) => record.key),
@@ -7640,6 +7874,15 @@ class EnhancedSelect extends HTMLElement {
7640
7874
  this._dropdown.removeAttribute('inert');
7641
7875
  this._dropdown.removeAttribute('aria-hidden');
7642
7876
  this._markOpenStart();
7877
+ this._scrollToSelectedConfigAtOpen = { ...this._config.scrollToSelected };
7878
+ this._openOptionsViewportAnchor = this._scrollToSelectedConfigAtOpen.onOpen === 'preserve'
7879
+ ? (this._closedOptionsViewportAnchor ?? this._captureOptionsViewportAnchor())
7880
+ : null;
7881
+ this._closedOptionsViewportAnchor = null;
7882
+ this._selectedOptionsConfigAtOpen = { ...this._config.selectedOptions };
7883
+ this._selectedOptionsSelectionAtOpen = this._config.selectedOptions.placement === 'selected-first'
7884
+ ? new Set(this._engine.state.selectedKeys)
7885
+ : null;
7643
7886
  this.setAttribute('data-open', 'true');
7644
7887
  this._liftStackingAncestors();
7645
7888
  this._dropdown.style.display = 'block';
@@ -7651,28 +7894,17 @@ class EnhancedSelect extends HTMLElement {
7651
7894
  this._emit('open', {});
7652
7895
  this._config.callbacks.onOpen?.();
7653
7896
  this._announce('Options expanded');
7654
- // Scroll to selected if configured
7655
- if (this._config.scrollToSelected.enabled) {
7656
- const keyboardActiveChangeGeneration = this._keyboardActiveChangeGeneration;
7657
- const canRestoreOpenSelection = () => this._state.isOpen
7658
- && this._keyboardActiveChangeGeneration === keyboardActiveChangeGeneration;
7659
- // Use requestAnimationFrame for better timing after render
7660
- this._requestLifecycleFrame(() => {
7661
- if (!canRestoreOpenSelection())
7662
- return;
7663
- // Double RAF to ensure layout is complete
7664
- this._requestLifecycleFrame(() => {
7665
- if (!canRestoreOpenSelection())
7666
- return;
7667
- this._scrollToSelected();
7668
- });
7669
- });
7670
- }
7897
+ this._scheduleOpenSelectedScroll();
7671
7898
  }
7672
7899
  _handleClose(reason = 'programmatic') {
7900
+ if (this._state.isOpen) {
7901
+ this._closedOptionsViewportAnchor = this._captureOptionsViewportAnchor();
7902
+ }
7673
7903
  const effects = this._engine.dispatch({ type: 'CLOSE_REQUEST', reason });
7674
7904
  if (!effects.some((effect) => effect.type === 'POPUP_CLOSED'))
7675
7905
  return;
7906
+ this._cancelOpenSelectedScroll();
7907
+ this._selectedOptionsSelectionAtOpen = null;
7676
7908
  this.removeAttribute('data-open');
7677
7909
  this._restoreLiftedAncestors();
7678
7910
  this._dropdown.setAttribute('data-placement', this._resolvedDropdownPlacement);
@@ -7684,6 +7916,257 @@ class EnhancedSelect extends HTMLElement {
7684
7916
  this._config.callbacks.onClose?.();
7685
7917
  this._announce('Options collapsed');
7686
7918
  }
7919
+ /**
7920
+ * Defer the one automatic selected-option positioning operation until the
7921
+ * dropdown's own entrance geometry has settled. Logical active/ARIA state
7922
+ * remains synchronous in _setInitialActiveOption().
7923
+ */
7924
+ _scheduleOpenSelectedScroll() {
7925
+ this._cancelOpenSelectedScroll();
7926
+ const openingConfig = this._scrollToSelectedConfigAtOpen;
7927
+ if (!openingConfig.enabled)
7928
+ return;
7929
+ const generation = this._openSelectedScrollGeneration;
7930
+ const keyboardGeneration = this._keyboardActiveChangeGeneration;
7931
+ const initialScrollTop = this._optionsContainer.scrollTop;
7932
+ const animations = [];
7933
+ const frameIds = new Set();
7934
+ let timerId = null;
7935
+ let completed = false;
7936
+ const isCurrent = () => generation === this._openSelectedScrollGeneration
7937
+ && this._state.isOpen
7938
+ && this.isConnected
7939
+ && this._config.scrollToSelected.enabled
7940
+ && keyboardGeneration === this._keyboardActiveChangeGeneration;
7941
+ const removeListeners = () => {
7942
+ this._optionsContainer.removeEventListener('wheel', cancelForUserInput);
7943
+ this._optionsContainer.removeEventListener('touchstart', cancelForUserInput);
7944
+ this._optionsContainer.removeEventListener('pointerdown', cancelForUserInput);
7945
+ this._optionsContainer.removeEventListener('scroll', cancelForUserScroll);
7946
+ for (const animation of animations) {
7947
+ animation.removeEventListener('finish', onAnimationStateChange);
7948
+ animation.removeEventListener('cancel', onAnimationStateChange);
7949
+ }
7950
+ };
7951
+ const cleanup = () => {
7952
+ removeListeners();
7953
+ for (const id of frameIds)
7954
+ cancelAnimationFrame(id);
7955
+ frameIds.clear();
7956
+ if (timerId !== null) {
7957
+ clearTimeout(timerId);
7958
+ this._lifecycleTimers.delete(timerId);
7959
+ timerId = null;
7960
+ }
7961
+ if (this._openSelectedScrollCleanup === cleanup) {
7962
+ this._openSelectedScrollCleanup = null;
7963
+ }
7964
+ };
7965
+ const cancelForUserInput = () => this._cancelOpenSelectedScroll();
7966
+ const cancelForUserScroll = () => {
7967
+ if (Math.abs(this._optionsContainer.scrollTop - initialScrollTop) > 1) {
7968
+ this._cancelOpenSelectedScroll();
7969
+ }
7970
+ };
7971
+ const finish = () => {
7972
+ if (completed)
7973
+ return;
7974
+ completed = true;
7975
+ cleanup();
7976
+ if (!isCurrent())
7977
+ return;
7978
+ const frameId = requestAnimationFrame(() => {
7979
+ frameIds.delete(frameId);
7980
+ cleanup();
7981
+ if (!isCurrent())
7982
+ return;
7983
+ if (openingConfig.onOpen === 'preserve') {
7984
+ this._restorePreservedOptionsViewport();
7985
+ }
7986
+ else {
7987
+ this._scrollToSelected({
7988
+ onlyIfNeeded: openingConfig.onOpen === 'reveal',
7989
+ setActive: false,
7990
+ config: openingConfig,
7991
+ });
7992
+ }
7993
+ });
7994
+ frameIds.add(frameId);
7995
+ this._openSelectedScrollCleanup = cleanup;
7996
+ };
7997
+ const onAnimationStateChange = () => {
7998
+ if (animations.every((animation) => animation.playState === 'finished' || animation.playState === 'idle'))
7999
+ finish();
8000
+ };
8001
+ const begin = () => {
8002
+ if (!isCurrent()) {
8003
+ cleanup();
8004
+ return;
8005
+ }
8006
+ const getAnimations = this._dropdown.getAnimations;
8007
+ const reducedMotion = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches ?? false;
8008
+ if (!reducedMotion && typeof getAnimations === 'function') {
8009
+ for (const animation of getAnimations.call(this._dropdown)) {
8010
+ const timing = animation.effect?.getComputedTiming();
8011
+ if (!timing || timing.iterations === Infinity || animation.playState === 'finished'
8012
+ || animation.playState === 'idle')
8013
+ continue;
8014
+ animations.push(animation);
8015
+ }
8016
+ }
8017
+ if (animations.length === 0) {
8018
+ if (!reducedMotion && typeof getAnimations !== 'function') {
8019
+ const fallbackWait = this._getDropdownEntranceFallbackDurationMs();
8020
+ if (fallbackWait > 0) {
8021
+ timerId = window.setTimeout(finish, fallbackWait + 34);
8022
+ this._lifecycleTimers.add(timerId);
8023
+ return;
8024
+ }
8025
+ }
8026
+ finish();
8027
+ return;
8028
+ }
8029
+ for (const animation of animations) {
8030
+ animation.addEventListener('finish', onAnimationStateChange);
8031
+ animation.addEventListener('cancel', onAnimationStateChange);
8032
+ }
8033
+ const remainingMs = Math.max(...animations.map((animation) => {
8034
+ const timing = animation.effect?.getComputedTiming();
8035
+ const endTime = Number(timing?.endTime);
8036
+ const currentTime = Number(animation.currentTime ?? 0);
8037
+ return Number.isFinite(endTime) ? Math.max(0, endTime - currentTime) : 0;
8038
+ }));
8039
+ const boundedWait = Math.min(10000, remainingMs + 50);
8040
+ timerId = window.setTimeout(finish, boundedWait);
8041
+ this._lifecycleTimers.add(timerId);
8042
+ };
8043
+ this._optionsContainer.addEventListener('wheel', cancelForUserInput, { passive: true });
8044
+ this._optionsContainer.addEventListener('touchstart', cancelForUserInput, { passive: true });
8045
+ this._optionsContainer.addEventListener('pointerdown', cancelForUserInput, { passive: true });
8046
+ this._optionsContainer.addEventListener('scroll', cancelForUserScroll, { passive: true });
8047
+ this._openSelectedScrollCleanup = cleanup;
8048
+ const frameId = requestAnimationFrame(() => {
8049
+ frameIds.delete(frameId);
8050
+ begin();
8051
+ });
8052
+ frameIds.add(frameId);
8053
+ }
8054
+ _cancelOpenSelectedScroll() {
8055
+ this._openSelectedScrollGeneration += 1;
8056
+ this._openSelectedScrollCleanup?.();
8057
+ this._openSelectedScrollCleanup = null;
8058
+ }
8059
+ _captureOptionsViewportAnchor() {
8060
+ const scroller = this._optionsContainer;
8061
+ const scrollTop = scroller.scrollTop;
8062
+ const order = this._renderPlan.filteredKeys.slice();
8063
+ const viewportTop = scroller.getBoundingClientRect().top + scroller.clientTop;
8064
+ const viewportBottom = viewportTop + scroller.clientHeight;
8065
+ const visible = Array.from(scroller.querySelectorAll('[data-sm-selectable], [data-selectable]'))
8066
+ .map((option) => ({ option, rect: option.getBoundingClientRect() }))
8067
+ .filter(({ rect }) => rect.height > 0 && rect.bottom > viewportTop && rect.top < viewportBottom)
8068
+ .sort((left, right) => left.rect.top - right.rect.top)[0];
8069
+ if (visible) {
8070
+ const sourceIndex = Number(visible.option.getAttribute('data-sm-index') ?? visible.option.getAttribute('data-index'));
8071
+ const key = Number.isInteger(sourceIndex) ? this._itemRegistry.indexToKey.get(sourceIndex) ?? null : null;
8072
+ if (key !== null) {
8073
+ return { key, offset: visible.rect.top - viewportTop, scrollTop, order };
8074
+ }
8075
+ }
8076
+ if (this._guardedVirtualizer && order.length > 0
8077
+ && typeof this._guardedVirtualizer.computeWindow === 'function') {
8078
+ const viewportHeight = this._resolveGuardedViewportHeight();
8079
+ const index = this._guardedVirtualizer.computeWindow(scrollTop, viewportHeight).startIndex;
8080
+ const key = order[index] ?? null;
8081
+ if (key !== null) {
8082
+ return {
8083
+ key,
8084
+ offset: this._guardedVirtualizer.cumulativeOffset(index) - scrollTop,
8085
+ scrollTop,
8086
+ order,
8087
+ };
8088
+ }
8089
+ }
8090
+ return { key: null, offset: 0, scrollTop, order };
8091
+ }
8092
+ /** Restore the previous visible option only when this opening changed order. */
8093
+ _restorePreservedOptionsViewport() {
8094
+ const anchor = this._openOptionsViewportAnchor;
8095
+ this._openOptionsViewportAnchor = null;
8096
+ if (!anchor)
8097
+ return;
8098
+ const nextOrder = this._renderPlan.filteredKeys;
8099
+ const nextPositionByKey = new Map(nextOrder.map((key, index) => [key, index]));
8100
+ const orderChanged = anchor.order.some((key, oldIndex) => {
8101
+ const nextIndex = nextPositionByKey.get(key);
8102
+ return nextIndex !== undefined && nextIndex !== oldIndex;
8103
+ });
8104
+ if (!orderChanged)
8105
+ return;
8106
+ const scroller = this._optionsContainer;
8107
+ const viewportHeight = this._resolveGuardedViewportHeight() || scroller.clientHeight;
8108
+ let targetScrollTop = null;
8109
+ if (anchor.key !== null) {
8110
+ const displayIndex = this._renderPlan.displayIndexByKey.get(anchor.key);
8111
+ if (displayIndex !== undefined) {
8112
+ const sourceIndex = this._renderPlan.sourceIndexByKey.get(anchor.key);
8113
+ const option = sourceIndex === undefined ? null : this._getOptionElementByIndex(sourceIndex);
8114
+ const viewportTop = scroller.getBoundingClientRect().top + scroller.clientTop;
8115
+ const optionTop = option?.getBoundingClientRect().top;
8116
+ if (option && option.getBoundingClientRect().height > 0 && Number.isFinite(optionTop)) {
8117
+ targetScrollTop = scroller.scrollTop + optionTop - viewportTop - anchor.offset;
8118
+ }
8119
+ else if (this._guardedVirtualizer) {
8120
+ targetScrollTop = this._guardedVirtualizer.cumulativeOffset(displayIndex) - anchor.offset;
8121
+ }
8122
+ }
8123
+ }
8124
+ if (targetScrollTop === null)
8125
+ targetScrollTop = anchor.scrollTop;
8126
+ let maxScrollTop = Number.POSITIVE_INFINITY;
8127
+ if (this._guardedVirtualizer) {
8128
+ maxScrollTop = Math.max(0, this._guardedVirtualizer.cumulativeOffset(nextOrder.length) - viewportHeight);
8129
+ }
8130
+ else if (scroller.scrollHeight > 0 && scroller.clientHeight > 0) {
8131
+ maxScrollTop = Math.max(0, scroller.scrollHeight - scroller.clientHeight);
8132
+ }
8133
+ targetScrollTop = Math.max(0, Math.min(targetScrollTop, maxScrollTop));
8134
+ if (Math.abs(targetScrollTop - scroller.scrollTop) < 1)
8135
+ return;
8136
+ // The coordinator owns this single restoration write. The virtualizer may
8137
+ // update its mounted window in response, but it must not issue a second
8138
+ // physical positioning correction for this transaction.
8139
+ this._guardedVirtualScrollTop = targetScrollTop;
8140
+ scroller.scrollTop = targetScrollTop;
8141
+ }
8142
+ /** Used only when Element.getAnimations() is unavailable. */
8143
+ _getDropdownEntranceFallbackDurationMs() {
8144
+ if (window.matchMedia?.('(prefers-reduced-motion: reduce)').matches)
8145
+ return 0;
8146
+ const style = getComputedStyle(this._dropdown);
8147
+ const parseTime = (value) => {
8148
+ const trimmed = value.trim();
8149
+ const parsed = Number.parseFloat(trimmed);
8150
+ if (!Number.isFinite(parsed))
8151
+ return 0;
8152
+ return trimmed.endsWith('ms') ? parsed : trimmed.endsWith('s') ? parsed * 1000 : 0;
8153
+ };
8154
+ const animationDurations = style.animationDuration.split(',');
8155
+ const animationDelays = style.animationDelay.split(',');
8156
+ const animationIterations = style.animationIterationCount.split(',');
8157
+ const maxAnimation = Math.max(0, ...animationDurations.map((duration, index) => {
8158
+ const count = Number.parseFloat(animationIterations[index % animationIterations.length] ?? '1');
8159
+ if (!Number.isFinite(count))
8160
+ return 0;
8161
+ return parseTime(duration)
8162
+ * Math.max(0, count)
8163
+ + parseTime(animationDelays[index % animationDelays.length] ?? '0s');
8164
+ }));
8165
+ const transitionDurations = style.transitionDuration.split(',');
8166
+ const transitionDelays = style.transitionDelay.split(',');
8167
+ const maxTransition = Math.max(0, ...transitionDurations.map((duration, index) => parseTime(duration) + parseTime(transitionDelays[index % transitionDelays.length] ?? '0s')));
8168
+ return Math.min(10000, Math.max(maxAnimation, maxTransition));
8169
+ }
7687
8170
  /** Stop an outstanding exit before reopening, disconnecting or starting another one. */
7688
8171
  _cancelDropdownExit() {
7689
8172
  if (this._dropdownExitTimer !== null) {
@@ -8038,26 +8521,38 @@ class EnhancedSelect extends HTMLElement {
8038
8521
  case 'Home':
8039
8522
  e.preventDefault();
8040
8523
  if (this._state.isOpen) {
8524
+ if (this._usesSelectedFirstVisualOrder()) {
8525
+ this._moveToVisualBoundary('first', { shiftKey: e.shiftKey, toggleKey: e.ctrlKey || e.metaKey });
8526
+ break;
8527
+ }
8041
8528
  const selectableIndices = this._getSelectableOptionIndices();
8042
8529
  const firstIndex = selectableIndices[0];
8043
8530
  if (firstIndex === undefined)
8044
8531
  break;
8045
8532
  this._setActive(firstIndex);
8046
8533
  if (this._config.selection.mode === 'multi' && e.shiftKey) {
8047
- this._selectRange(this._rangeAnchorIndex ?? firstIndex, firstIndex, { clear: !(e.ctrlKey || e.metaKey) });
8534
+ const targetKey = this._itemRegistry.indexToKey.get(firstIndex);
8535
+ if (targetKey !== undefined)
8536
+ this._selectKeyboardRange(this._rangeAnchorKey ?? targetKey, targetKey, { clear: !(e.ctrlKey || e.metaKey) });
8048
8537
  }
8049
8538
  }
8050
8539
  break;
8051
8540
  case 'End':
8052
8541
  e.preventDefault();
8053
8542
  if (this._state.isOpen) {
8543
+ if (this._usesSelectedFirstVisualOrder()) {
8544
+ this._moveToVisualBoundary('last', { shiftKey: e.shiftKey, toggleKey: e.ctrlKey || e.metaKey });
8545
+ break;
8546
+ }
8054
8547
  const selectableIndices = this._getSelectableOptionIndices();
8055
8548
  const lastIndex = selectableIndices[selectableIndices.length - 1];
8056
8549
  if (lastIndex === undefined)
8057
8550
  break;
8058
8551
  this._setActive(lastIndex);
8059
8552
  if (this._config.selection.mode === 'multi' && e.shiftKey) {
8060
- this._selectRange(this._rangeAnchorIndex ?? lastIndex, lastIndex, { clear: !(e.ctrlKey || e.metaKey) });
8553
+ const targetKey = this._itemRegistry.indexToKey.get(lastIndex);
8554
+ if (targetKey !== undefined)
8555
+ this._selectKeyboardRange(this._rangeAnchorKey ?? targetKey, targetKey, { clear: !(e.ctrlKey || e.metaKey) });
8061
8556
  }
8062
8557
  }
8063
8558
  break;
@@ -8112,6 +8607,26 @@ class EnhancedSelect extends HTMLElement {
8112
8607
  }
8113
8608
  }
8114
8609
  _moveActive(delta, opts) {
8610
+ if (this._usesSelectedFirstVisualOrder()) {
8611
+ const model = this._getVisualNavigationModel();
8612
+ if (model.selectableKeys.length === 0)
8613
+ return;
8614
+ const activeKey = this._engine.state.activeKey;
8615
+ const currentPosition = activeKey === null ? undefined : model.selectablePositionByKey.get(activeKey);
8616
+ // Load-more is only requested after movement reaches the actual visual end.
8617
+ if (delta === 1 && currentPosition === model.selectableKeys.length - 1 && this._requestKeyboardLoadMore())
8618
+ return;
8619
+ const nextKey = resolveVisualMovement(model, activeKey, delta);
8620
+ if (nextKey === null)
8621
+ return;
8622
+ this._setActiveForVisualKey(nextKey);
8623
+ if (this._config.selection.mode === 'multi' && opts?.shiftKey) {
8624
+ const anchorKey = this._rangeAnchorKey ?? activeKey ?? nextKey;
8625
+ this._rangeAnchorKey = anchorKey;
8626
+ this._selectKeyboardRange(anchorKey, nextKey, { clear: !opts.toggleKey });
8627
+ }
8628
+ return;
8629
+ }
8115
8630
  const selectableIndices = this._getSelectableOptionIndices();
8116
8631
  if (selectableIndices.length === 0)
8117
8632
  return;
@@ -8133,13 +8648,89 @@ class EnhancedSelect extends HTMLElement {
8133
8648
  const next = selectableIndices[nextPosition];
8134
8649
  this._setActive(next);
8135
8650
  if (this._config.selection.mode === 'multi' && opts?.shiftKey) {
8136
- const anchor = this._rangeAnchorIndex ?? currentIndex;
8137
- const anchorIndex = anchor >= 0 ? anchor : next;
8138
- if (this._rangeAnchorIndex === null) {
8139
- this._rangeAnchorIndex = anchorIndex;
8140
- }
8141
- this._selectRange(anchorIndex, next, { clear: !opts?.toggleKey });
8651
+ const nextKey = this._itemRegistry.indexToKey.get(next);
8652
+ if (nextKey === undefined)
8653
+ return;
8654
+ const anchorKey = this._rangeAnchorKey ?? (currentIndex >= 0 ? this._itemRegistry.indexToKey.get(currentIndex) : undefined) ?? nextKey;
8655
+ this._rangeAnchorKey = anchorKey;
8656
+ this._selectKeyboardRange(anchorKey, nextKey, { clear: !opts?.toggleKey });
8657
+ }
8658
+ }
8659
+ _usesSelectedFirstVisualOrder() {
8660
+ return this._selectedOptionsConfigAtOpen.placement === 'selected-first';
8661
+ }
8662
+ _getVisualNavigationModel() {
8663
+ this._ensureRegistryCurrent();
8664
+ return createVisualNavigationModel(this._renderPlan.filteredKeys, (key) => {
8665
+ const record = this._itemRegistry.keyToRecord.get(key);
8666
+ if (!record || record.disabled)
8667
+ return false;
8668
+ const option = this._getOptionElementByIndex(record.index);
8669
+ return option?.getAttribute('aria-disabled') !== 'true';
8670
+ });
8671
+ }
8672
+ _setActiveForVisualKey(key, reason = 'keyboard', options = {}) {
8673
+ const sourceIndex = this._renderPlan.sourceIndexByKey.get(key)
8674
+ ?? this._itemRegistry.keyToIndex.get(key);
8675
+ if (sourceIndex === undefined)
8676
+ return;
8677
+ this._setActive(sourceIndex, reason, options);
8678
+ }
8679
+ _moveToVisualBoundary(boundary, opts) {
8680
+ const model = this._getVisualNavigationModel();
8681
+ const targetKey = resolveVisualBoundary(model, boundary);
8682
+ if (targetKey === null)
8683
+ return;
8684
+ const currentKey = this._engine.state.activeKey;
8685
+ this._setActiveForVisualKey(targetKey);
8686
+ if (this._config.selection.mode === 'multi' && opts?.shiftKey) {
8687
+ const anchorKey = this._rangeAnchorKey ?? currentKey ?? targetKey;
8688
+ this._rangeAnchorKey = anchorKey;
8689
+ this._selectKeyboardRange(anchorKey, targetKey, { clear: !opts.toggleKey });
8690
+ }
8691
+ }
8692
+ _selectKeyboardRange(anchorKey, targetKey, opts) {
8693
+ if (this._usesSelectedFirstVisualOrder()) {
8694
+ const model = this._getVisualNavigationModel();
8695
+ const resolvedAnchor = model.selectablePositionByKey.has(anchorKey) ? anchorKey : targetKey;
8696
+ this._rangeAnchorKey = resolvedAnchor;
8697
+ this._selectVisualRange(resolvedAnchor, targetKey, opts);
8698
+ return;
8699
+ }
8700
+ const start = this._itemRegistry.keyToIndex.get(anchorKey);
8701
+ const end = this._itemRegistry.keyToIndex.get(targetKey);
8702
+ if (start !== undefined && end !== undefined)
8703
+ this._selectRange(start, end, opts);
8704
+ }
8705
+ _selectVisualRange(anchorKey, targetKey, opts) {
8706
+ if (this._config.selection.mode !== 'multi')
8707
+ return;
8708
+ this._ensureRegistryCurrent();
8709
+ const model = this._getVisualNavigationModel();
8710
+ const rangeKeys = resolveVisualRange(model, anchorKey, targetKey);
8711
+ if (rangeKeys.length === 0)
8712
+ return;
8713
+ const selectedEntries = this._getSelectedEntries();
8714
+ const entries = opts?.clear
8715
+ ? selectedEntries.filter((entry) => !this._itemRegistry.keyToRecord.has(entry.key))
8716
+ : selectedEntries;
8717
+ for (const key of rangeKeys) {
8718
+ const record = this._itemRegistry.keyToRecord.get(key);
8719
+ if (!record || this._isOptionSelectionBlocked(record.item))
8720
+ continue;
8721
+ entries.push(record);
8142
8722
  }
8723
+ this._requestSelectionReplacement(entries, opts?.reason ?? 'keyboard', 'select visual range');
8724
+ this._renderOptions();
8725
+ this._updateInputDisplay();
8726
+ const target = this._itemRegistry.keyToRecord.get(targetKey);
8727
+ const selectDetail = target ? this._getSelectEventDetail(target) : null;
8728
+ if (selectDetail)
8729
+ this._emit('select', selectDetail);
8730
+ this._emitChange();
8731
+ this._announce(`${this._state.selectedIndices.size} items selected`);
8732
+ if (selectDetail)
8733
+ this._config.callbacks.onSelect?.(selectDetail);
8143
8734
  }
8144
8735
  /** Return true only when boundary navigation is held for an in-flight/new page. */
8145
8736
  _requestKeyboardLoadMore() {
@@ -8168,7 +8759,7 @@ class EnhancedSelect extends HTMLElement {
8168
8759
  this._dispatchAcknowledgedActions(actions);
8169
8760
  return true;
8170
8761
  }
8171
- _setActive(index, reason = 'keyboard') {
8762
+ _setActive(index, reason = 'keyboard', options = {}) {
8172
8763
  this._ensureRegistryCurrent();
8173
8764
  const record = this._getRecordByIndex(index);
8174
8765
  let option = this._getOptionElementByIndex(index);
@@ -8179,8 +8770,10 @@ class EnhancedSelect extends HTMLElement {
8179
8770
  if (!record || record.disabled || !option || option.getAttribute('aria-disabled') === 'true') {
8180
8771
  return;
8181
8772
  }
8182
- if (reason === 'keyboard')
8773
+ if (reason === 'keyboard' || reason === 'search') {
8183
8774
  this._keyboardActiveChangeGeneration += 1;
8775
+ this._cancelOpenSelectedScroll();
8776
+ }
8184
8777
  const previousIndex = this._state.activeIndex;
8185
8778
  this._dispatchActiveKey(record.key, reason, 'set active');
8186
8779
  if (this._state.activeIndex !== index)
@@ -8207,8 +8800,7 @@ class EnhancedSelect extends HTMLElement {
8207
8800
  else {
8208
8801
  this._syncCustomOptionActiveClasses(option, true);
8209
8802
  }
8210
- if (typeof option.scrollIntoView === 'function') {
8211
- // Don't scroll wildly when just opening with pre-selections
8803
+ if (options.scroll !== false && typeof option.scrollIntoView === 'function') {
8212
8804
  option.scrollIntoView({ block: 'nearest', behavior: 'smooth' });
8213
8805
  }
8214
8806
  // Announce position for screen readers
@@ -8264,8 +8856,22 @@ class EnhancedSelect extends HTMLElement {
8264
8856
  this._typeTimeout = window.setTimeout(() => {
8265
8857
  this._typeBuffer = '';
8266
8858
  }, 500);
8267
- // Find first matching option
8859
+ // Type-ahead uses the displayed candidate order when a presentation projection is active.
8268
8860
  const getValue = this._config.serverSide.getLabelFromItem || ((item) => item?.label ?? String(item));
8861
+ if (this._usesSelectedFirstVisualOrder()) {
8862
+ const model = this._getVisualNavigationModel();
8863
+ const matchKey = model.selectableKeys.find((key) => {
8864
+ const record = this._itemRegistry.keyToRecord.get(key);
8865
+ return record !== undefined && getValue(record.item).toLowerCase().startsWith(this._typeBuffer);
8866
+ });
8867
+ if (matchKey !== undefined) {
8868
+ const sourceIndex = this._renderPlan.sourceIndexByKey.get(matchKey)
8869
+ ?? this._itemRegistry.keyToIndex.get(matchKey);
8870
+ if (sourceIndex !== undefined)
8871
+ this._setActive(sourceIndex, 'search');
8872
+ }
8873
+ return;
8874
+ }
8269
8875
  const matchIndex = this._state.loadedItems.findIndex((item) => getValue(item).toLowerCase().startsWith(this._typeBuffer));
8270
8876
  if (matchIndex >= 0) {
8271
8877
  this._setActive(matchIndex, 'search');
@@ -8334,6 +8940,17 @@ class EnhancedSelect extends HTMLElement {
8334
8940
  };
8335
8941
  }
8336
8942
  _setInitialActiveOption() {
8943
+ if (this._usesSelectedFirstVisualOrder()) {
8944
+ const model = this._getVisualNavigationModel();
8945
+ const selectedKey = model.selectableKeys.find((key) => this._engine.state.selectedKeys.has(key));
8946
+ if (selectedKey === undefined) {
8947
+ this._dispatchActiveKey(null, 'open', 'initial active option');
8948
+ return;
8949
+ }
8950
+ // Resolve via stable identity so the open-time projection remains authoritative.
8951
+ this._setActiveForVisualKey(selectedKey, 'open', { scroll: false });
8952
+ return;
8953
+ }
8337
8954
  const selectableIndices = this._getSelectableOptionIndices();
8338
8955
  const selected = Array.from(this._state.selectedIndices).sort((a, b) => a - b);
8339
8956
  // Opening an empty select must not implicitly assign an active descendant.
@@ -8343,7 +8960,9 @@ class EnhancedSelect extends HTMLElement {
8343
8960
  return;
8344
8961
  }
8345
8962
  const target = selected.find((index) => selectableIndices.includes(index)) ?? selectableIndices[0];
8346
- this._setActive(target, 'open');
8963
+ // Set logical active state and ARIA immediately. The open-time coordinator
8964
+ // owns any physical positioning after the dropdown's entrance settles.
8965
+ this._setActive(target, 'open', { scroll: false });
8347
8966
  }
8348
8967
  _announce(message) {
8349
8968
  const effects = computeAccessibilityEffects(deriveAccessibilityState(this._engine.state), {
@@ -8397,9 +9016,10 @@ class EnhancedSelect extends HTMLElement {
8397
9016
  const toggleKey = Boolean(opts?.toggleKey);
8398
9017
  const shiftKey = Boolean(opts?.shiftKey);
8399
9018
  if (shiftKey) {
8400
- const anchor = this._rangeAnchorIndex ?? index;
8401
- this._selectRange(anchor, index, { clear: !toggleKey, reason });
8402
- this._rangeAnchorIndex = anchor;
9019
+ const targetKey = record.key;
9020
+ const anchorKey = this._rangeAnchorKey ?? targetKey;
9021
+ this._selectKeyboardRange(anchorKey, targetKey, { clear: !toggleKey, reason });
9022
+ this._rangeAnchorKey = anchorKey;
8403
9023
  return;
8404
9024
  }
8405
9025
  // Multi select with toggle
@@ -8413,7 +9033,7 @@ class EnhancedSelect extends HTMLElement {
8413
9033
  // Re-render to update styles (safer than trying to find the element in filtered list)
8414
9034
  this._renderOptions();
8415
9035
  }
8416
- this._rangeAnchorIndex = index;
9036
+ this._rangeAnchorKey = record.key;
8417
9037
  this._updateInputDisplay();
8418
9038
  const selectDetail = this._getSelectEventDetail(record);
8419
9039
  this._emit('select', selectDetail);
@@ -8672,58 +9292,71 @@ class EnhancedSelect extends HTMLElement {
8672
9292
  this._optionsContainer.style.transition = 'opacity 0.2s ease-in';
8673
9293
  }, 150);
8674
9294
  }
8675
- _scrollToSelected() {
8676
- if (this._state.selectedIndices.size === 0)
8677
- return;
8678
- const target = this._config.scrollToSelected.multiSelectTarget;
8679
- const indices = Array.from(this._state.selectedIndices).filter((index) => index >= 0).sort((a, b) => a - b);
8680
- if (indices.length === 0)
8681
- return;
8682
- // For multi-select, find the closest selected item to the current scroll position
8683
- let targetIndex;
8684
- if (this._config.selection.mode === 'multi' && indices.length > 1) {
8685
- // Calculate which selected item is closest to the center of the viewport
8686
- const dropdownRect = this._dropdown.getBoundingClientRect();
8687
- const viewportCenter = this._dropdown.scrollTop + (dropdownRect.height / 2);
8688
- // Find the selected item closest to viewport center
8689
- let closestIndex = indices[0];
8690
- let closestDistance = Infinity;
8691
- for (const index of indices) {
8692
- const option = this._getOptionElementByIndex(index);
8693
- if (option) {
8694
- const optionTop = option.offsetTop;
8695
- const distance = Math.abs(optionTop - viewportCenter);
8696
- if (distance < closestDistance) {
8697
- closestDistance = distance;
8698
- closestIndex = index;
8699
- }
8700
- }
8701
- }
8702
- targetIndex = closestIndex;
8703
- }
8704
- else {
8705
- // For single select or only one selected item, use the configured target
8706
- targetIndex = target === 'first' ? indices[0] : indices[indices.length - 1];
8707
- }
8708
- // Find and scroll to the target option
9295
+ _scrollToSelected(options = {}) {
9296
+ const config = options.config ?? this._config.scrollToSelected;
9297
+ if (!config.enabled)
9298
+ return;
9299
+ const targetKey = resolveSelectedTargetKey(this._renderPlan.filteredKeys, this._engine.state.selectedKeys, config.multiSelectTarget);
9300
+ if (targetKey === null)
9301
+ return;
9302
+ const targetIndex = this._renderPlan.sourceIndexByKey.get(targetKey)
9303
+ ?? this._itemRegistry.keyToIndex.get(targetKey);
9304
+ if (targetIndex === undefined)
9305
+ return;
9306
+ // Resolve against the current eligible render plan first. A selected key
9307
+ // outside the filtered projection must never trigger materialization.
8709
9308
  let option = this._getOptionElementByIndex(targetIndex);
8710
9309
  if (!option && this._guardedVirtualizer) {
8711
- const targetKey = this._itemRegistry.indexToKey.get(targetIndex);
8712
- if (targetKey !== undefined) {
8713
- this._materializeGuardedVirtualKey(targetKey);
8714
- option = this._getOptionElementByIndex(targetIndex);
8715
- }
9310
+ this._materializeGuardedVirtualKey(targetKey);
9311
+ option = this._getOptionElementByIndex(targetIndex);
8716
9312
  }
8717
9313
  if (option) {
8718
- // Use smooth scrolling with center alignment for better UX
8719
- if (typeof option.scrollIntoView === 'function') {
8720
- option.scrollIntoView({
8721
- block: this._config.scrollToSelected.block || 'center',
8722
- behavior: 'smooth',
8723
- });
9314
+ const reducedMotion = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches ?? false;
9315
+ this._scrollOptionWithinOptionsContainer(option, config.block || 'nearest', reducedMotion && config.behavior === 'smooth' ? 'auto' : (config.behavior || 'smooth'), options.onlyIfNeeded === true);
9316
+ if (options.setActive !== false) {
9317
+ // Active/ARIA synchronization must not start a second physical scroll.
9318
+ this._setActive(targetIndex, 'programmatic', { scroll: false });
8724
9319
  }
8725
- // Also set it as active for keyboard navigation
8726
- this._setActive(targetIndex, 'programmatic');
9320
+ }
9321
+ }
9322
+ _scrollOptionWithinOptionsContainer(option, block, behavior, onlyIfNeeded) {
9323
+ const scroller = this._optionsContainer;
9324
+ const scrollerRect = scroller.getBoundingClientRect();
9325
+ const viewportTop = scrollerRect.top + scroller.clientTop;
9326
+ const viewportBottom = viewportTop + scroller.clientHeight;
9327
+ const optionRect = option.getBoundingClientRect();
9328
+ if (onlyIfNeeded && optionRect.top >= viewportTop && optionRect.bottom <= viewportBottom)
9329
+ return;
9330
+ if (scroller.clientHeight <= 0 || optionRect.height <= 0)
9331
+ return;
9332
+ let targetScrollTop = scroller.scrollTop;
9333
+ if (block === 'start') {
9334
+ targetScrollTop += optionRect.top - viewportTop;
9335
+ }
9336
+ else if (block === 'center') {
9337
+ targetScrollTop += (optionRect.top + optionRect.bottom - viewportTop - viewportBottom) / 2;
9338
+ }
9339
+ else if (block === 'end') {
9340
+ targetScrollTop += optionRect.bottom - viewportBottom;
9341
+ }
9342
+ else if (optionRect.top < viewportTop) {
9343
+ targetScrollTop += optionRect.top - viewportTop;
9344
+ }
9345
+ else if (optionRect.bottom > viewportBottom) {
9346
+ targetScrollTop += optionRect.bottom - viewportBottom;
9347
+ }
9348
+ else {
9349
+ return;
9350
+ }
9351
+ const maxScrollTop = Math.max(0, scroller.scrollHeight - scroller.clientHeight);
9352
+ targetScrollTop = Math.max(0, Math.min(targetScrollTop, maxScrollTop));
9353
+ if (Math.abs(targetScrollTop - scroller.scrollTop) < 1)
9354
+ return;
9355
+ if (typeof scroller.scrollTo === 'function') {
9356
+ scroller.scrollTo({ top: targetScrollTop, behavior });
9357
+ }
9358
+ else {
9359
+ scroller.scrollTop = targetScrollTop;
8727
9360
  }
8728
9361
  }
8729
9362
  async _loadMoreItems(trigger = 'manual') {
@@ -9209,10 +9842,21 @@ class EnhancedSelect extends HTMLElement {
9209
9842
  this._invalidateGuardedMeasurements();
9210
9843
  const previousMode = this._config.selection.mode;
9211
9844
  const previousEnabled = this._config.enabled;
9845
+ const previousOpenScrollEnabled = this._config.scrollToSelected.enabled;
9212
9846
  const previousDataLoadingConfig = this._dataLoadingConfig;
9213
9847
  let searchEligibilityBecameInactive = false;
9214
- const { dataLoading, callbacks, ...legacyConfig } = config;
9848
+ const { dataLoading, callbacks, selectedOptions, scrollToSelected, ...legacyConfig } = config;
9215
9849
  const legacyUpdate = { ...legacyConfig };
9850
+ if (selectedOptions !== undefined) {
9851
+ const validation = validateSelectedOptionsConfig(selectedOptions);
9852
+ if (validation.valid)
9853
+ legacyUpdate.selectedOptions = validation.value;
9854
+ }
9855
+ if (scrollToSelected !== undefined) {
9856
+ const validation = validateScrollToSelectedConfig(scrollToSelected);
9857
+ if (validation.valid)
9858
+ legacyUpdate.scrollToSelected = validation.value;
9859
+ }
9216
9860
  let configErrorDetail;
9217
9861
  if (callbacks !== undefined && callbacks !== null) {
9218
9862
  const callbackInput = callbacks;
@@ -9232,6 +9876,10 @@ class EnhancedSelect extends HTMLElement {
9232
9876
  legacyUpdate.callbacks = legacyCallbacks;
9233
9877
  }
9234
9878
  this._config = this._mergeConfig(this._config, legacyUpdate);
9879
+ if (previousOpenScrollEnabled && !this._config.scrollToSelected.enabled) {
9880
+ this._openOptionsViewportAnchor = null;
9881
+ this._cancelOpenSelectedScroll();
9882
+ }
9235
9883
  if (dataLoading !== undefined) {
9236
9884
  const dataLoadingPrototype = dataLoading !== null && typeof dataLoading === 'object'
9237
9885
  ? Object.getPrototypeOf(dataLoading)
@@ -9778,19 +10426,39 @@ class EnhancedSelect extends HTMLElement {
9778
10426
  activeKey: this._engine.state.activeKey,
9779
10427
  };
9780
10428
  }
9781
- _createLegacyRenderPlan(filteredIndices) {
9782
- const indices = [...filteredIndices];
9783
- const filteredKeys = indices
9784
- .map((index) => this._itemRegistry.indexToKey.get(index))
9785
- .filter((key) => key !== undefined);
9786
- const filteredIndexByKey = new Map();
9787
- filteredKeys.forEach((key, filteredIndex) => filteredIndexByKey.set(key, filteredIndex));
10429
+ _createLegacyRenderPlan(filteredIndices, groupedPresentation = []) {
10430
+ const sourceIndices = [...filteredIndices];
10431
+ const sourceOrderedKeys = groupedPresentation.length > 0
10432
+ ? groupedPresentation.flatMap((group) => group.orderedKeys)
10433
+ : sourceIndices
10434
+ .map((index) => this._itemRegistry.indexToKey.get(index))
10435
+ .filter((key) => key !== undefined);
10436
+ const shouldProjectSelectedFirst = this._usesSelectedFirstVisualOrder()
10437
+ && groupedPresentation.length === 0;
10438
+ const selectedKeys = this._selectedOptionsSelectionAtOpen ?? this._engine.state.selectedKeys;
10439
+ const filteredKeys = shouldProjectSelectedFirst
10440
+ ? projectSelectedOptionKeys(sourceOrderedKeys, selectedKeys)
10441
+ : sourceOrderedKeys;
10442
+ const indices = filteredKeys
10443
+ .map((key) => this._itemRegistry.keyToIndex.get(key))
10444
+ .filter((index) => index !== undefined);
10445
+ const displayIndexByKey = new Map();
10446
+ const sourceIndexByKey = new Map();
10447
+ filteredKeys.forEach((key, displayIndex) => {
10448
+ displayIndexByKey.set(key, displayIndex);
10449
+ const sourceIndex = this._itemRegistry.keyToIndex.get(key);
10450
+ if (sourceIndex !== undefined)
10451
+ sourceIndexByKey.set(key, sourceIndex);
10452
+ });
9788
10453
  return {
9789
10454
  mode: 'legacy-full',
9790
10455
  filteredIndices: indices,
9791
10456
  filteredKeys,
9792
10457
  intendedRenderKeys: filteredKeys.slice(),
9793
- filteredIndexByKey,
10458
+ displayIndexByKey,
10459
+ sourceIndexByKey,
10460
+ filteredIndexByKey: displayIndexByKey,
10461
+ groupedPresentation,
9794
10462
  };
9795
10463
  }
9796
10464
  _createVirtualRenderPlan(startIndex, endIndex) {
@@ -9799,12 +10467,16 @@ class EnhancedSelect extends HTMLElement {
9799
10467
  const filteredIndices = intendedRenderKeys
9800
10468
  .map((key) => this._itemRegistry.keyToIndex.get(key))
9801
10469
  .filter((index) => index !== undefined);
10470
+ const displayIndexByKey = new Map(this._renderPlan.displayIndexByKey);
9802
10471
  return {
9803
10472
  mode: 'virtual-window',
9804
10473
  filteredIndices,
9805
10474
  filteredKeys,
9806
10475
  intendedRenderKeys,
9807
- filteredIndexByKey: new Map(this._renderPlan.filteredIndexByKey),
10476
+ displayIndexByKey,
10477
+ sourceIndexByKey: new Map(this._renderPlan.sourceIndexByKey),
10478
+ filteredIndexByKey: displayIndexByKey,
10479
+ groupedPresentation: this._renderPlan.groupedPresentation,
9808
10480
  };
9809
10481
  }
9810
10482
  _ensureGuardedVirtualizer(filteredKeys) {
@@ -10758,11 +11430,31 @@ class EnhancedSelect extends HTMLElement {
10758
11430
  // Handle Grouped Items Rendering (when no search query)
10759
11431
  if (this._state.groupedItems.length > 0 && !query) {
10760
11432
  this._destroyGuardedVirtualizer();
10761
- this._renderPlan = this._createLegacyRenderPlan(this._itemRegistry.records.map((record) => record.index));
11433
+ const groupedSource = this._state.groupedItems.map((group, groupIndex) => ({
11434
+ group,
11435
+ groupIndex,
11436
+ orderedKeys: group.options
11437
+ .map((item) => this._state.loadedItems.indexOf(item))
11438
+ .filter((index) => index >= 0)
11439
+ .map((index) => this._itemRegistry.indexToKey.get(index))
11440
+ .filter((key) => key !== undefined),
11441
+ }));
11442
+ const groupedOrder = this._usesSelectedFirstVisualOrder()
11443
+ ? projectSelectedOptionGroups(groupedSource.map(({ groupIndex, orderedKeys }) => ({ groupIdentity: groupIndex, orderedKeys })), this._selectedOptionsSelectionAtOpen ?? this._engine.state.selectedKeys)
11444
+ : groupedSource.map(({ groupIndex, orderedKeys }) => ({ groupIdentity: groupIndex, orderedKeys }));
11445
+ const groupedPresentation = groupedOrder.map(({ groupIdentity, orderedKeys }) => ({
11446
+ group: this._state.groupedItems[groupIdentity],
11447
+ groupIndex: groupIdentity,
11448
+ orderedKeys,
11449
+ }));
11450
+ const groupedIndices = groupedPresentation.flatMap(({ orderedKeys }) => orderedKeys
11451
+ .map((key) => this._itemRegistry.keyToIndex.get(key))
11452
+ .filter((index) => index !== undefined));
11453
+ this._renderPlan = this._createLegacyRenderPlan(groupedIndices, groupedPresentation);
10762
11454
  filteredIndicesForScope = this._renderPlan.filteredIndices;
10763
11455
  this._registerShadowItems(filteredIndicesForScope);
10764
11456
  this._refreshVirtualizationScope(filteredIndicesForScope);
10765
- this._state.groupedItems.forEach((group, groupIndex) => {
11457
+ this._renderPlan.groupedPresentation.forEach(({ group, groupIndex, orderedKeys }) => {
10766
11458
  let header;
10767
11459
  if (this.groupHeaderRenderer) {
10768
11460
  header = this.groupHeaderRenderer(group, groupIndex);
@@ -10788,10 +11480,10 @@ class EnhancedSelect extends HTMLElement {
10788
11480
  }
10789
11481
  header.setAttribute('part', 'group-header');
10790
11482
  this._optionsContainer.appendChild(header);
10791
- group.options.forEach(item => {
10792
- // Find original index for correct ID generation and selection
10793
- const index = this._state.loadedItems.indexOf(item);
10794
- if (index !== -1) {
11483
+ orderedKeys.forEach((key) => {
11484
+ const index = this._itemRegistry.keyToIndex.get(key);
11485
+ if (index !== undefined) {
11486
+ const item = this._state.loadedItems[index];
10795
11487
  this._renderSingleOption(item, index, getValue, getLabel);
10796
11488
  }
10797
11489
  });
@@ -10860,13 +11552,16 @@ class EnhancedSelect extends HTMLElement {
10860
11552
  const chunkSize = 80;
10861
11553
  let cursor = 0;
10862
11554
  let maxRenderTarget = 0;
10863
- if (this._state.selectedIndices.size > 0 && this._config.scrollToSelected.enabled) {
10864
- const indices = Array.from(this._state.selectedIndices).filter((index) => index >= 0).sort((a, b) => a - b);
10865
- const targetIndex = this._config.scrollToSelected.multiSelectTarget === 'first' ? indices[0] : indices[indices.length - 1];
10866
- const filteredPos = filteredIndices.indexOf(targetIndex);
10867
- if (filteredPos !== -1) {
10868
- maxRenderTarget = filteredPos + 20; // Ensure we render up to the selection
10869
- }
11555
+ if (this._state.isOpen
11556
+ && this._config.scrollToSelected.enabled
11557
+ && this._scrollToSelectedConfigAtOpen.enabled
11558
+ && this._scrollToSelectedConfigAtOpen.onOpen !== 'preserve') {
11559
+ const targetKey = resolveSelectedTargetKey(this._renderPlan.filteredKeys, this._engine.state.selectedKeys, this._scrollToSelectedConfigAtOpen.multiSelectTarget);
11560
+ const targetPosition = targetKey === null
11561
+ ? undefined
11562
+ : this._renderPlan.displayIndexByKey.get(targetKey);
11563
+ if (targetPosition !== undefined)
11564
+ maxRenderTarget = targetPosition + 20;
10870
11565
  }
10871
11566
  const renderChunk = () => {
10872
11567
  if (renderCycleId !== this._renderCycleId) {
@@ -12316,5 +13011,5 @@ function warnCSPViolation(feature, fallback) {
12316
13011
  }
12317
13012
  }
12318
13013
 
12319
- export { CSPFeatures, CustomOptionPool, DOMPool, DefaultSelectEffectRunner, EnhancedSelect, FenwickTree, NativeSelectElement, OptionRenderer, PerformanceTelemetry, SelectEngineBridge, SelectOption, Virtualizer, WorkerManager, applyClasses, applyDefaultTheme, applySelectionRequest, arrayIncludesValue, arraysEqualByValue, configureSelect, containsSuspiciousPatterns, createDefaultItemAdapter, createElement, createInitialSelectState, createItemRegistry, createRendererHelpers, createTextNode, defaultTheme, detectEnvironment, escapeAttribute, escapeHTML, getActiveKey, getCustomProperty, getDefaultDuplicateKeyPolicy, getHTMLSanitizer, getSelectedKeys, getTelemetry, getWorkerManager, hasOverflowHiddenAncestor, hasSelection, injectShadowStyles, isDisabled, isFocused, isOpen, isRegisteredKey, isSelected, measureAsync, measureSync, removeCustomProperty, renderTemplate, resetSelectConfig, sanitizeHTML, selectConfig, setCSSProperties, setCustomProperties, setHTMLSanitizer, setTextContent, shadowDOMStyles, toggleClass, transition, validateDataLoadingConfig, validateTemplate, valuesEqual, warnCSPViolation };
13014
+ export { CSPFeatures, CustomOptionPool, DOMPool, DefaultSelectEffectRunner, EnhancedSelect, FenwickTree, NativeSelectElement, OptionRenderer, PerformanceTelemetry, SelectEngineBridge, SelectOption, Virtualizer, WorkerManager, applyClasses, applyDefaultTheme, applySelectionRequest, arrayIncludesValue, arraysEqualByValue, configureSelect, containsSuspiciousPatterns, createDefaultItemAdapter, createElement, createInitialSelectState, createItemRegistry, createRendererHelpers, createTextNode, defaultTheme, detectEnvironment, escapeAttribute, escapeHTML, getActiveKey, getCustomProperty, getDefaultDuplicateKeyPolicy, getHTMLSanitizer, getSelectedKeys, getTelemetry, getWorkerManager, hasOverflowHiddenAncestor, hasSelection, injectShadowStyles, isDisabled, isFocused, isOpen, isRegisteredKey, isSelected, measureAsync, measureSync, removeCustomProperty, renderTemplate, resetSelectConfig, sanitizeHTML, selectConfig, setCSSProperties, setCustomProperties, setHTMLSanitizer, setTextContent, shadowDOMStyles, toggleClass, transition, validateDataLoadingConfig, validateScrollToSelectedConfig, validateSelectedOptionsConfig, validateSelectedOptionsConfigUpdate, validateTemplate, valuesEqual, warnCSPViolation };
12320
13015
  //# sourceMappingURL=index.js.map