@smilodon/core 1.18.0 → 1.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -2074,6 +2074,123 @@ if (!customElements.get("smilodon-select")) {
2074
2074
  customElements.define("smilodon-select", NativeSelectElement);
2075
2075
  }
2076
2076
 
2077
+ const SELECTED_OPTIONS_FIELDS = new Set(['placement', 'groupedPlacement']);
2078
+ const SCROLL_TO_SELECTED_FIELDS = new Set([
2079
+ 'enabled',
2080
+ 'multiSelectTarget',
2081
+ 'onOpen',
2082
+ 'behavior',
2083
+ 'block',
2084
+ ]);
2085
+ const placements = new Set(['original', 'selected-first']);
2086
+ const groupedPlacements = new Set(['within-group']);
2087
+ const scrollTargets = new Set(['first', 'last']);
2088
+ const openPolicies = new Set(['preserve', 'reveal', 'align']);
2089
+ const scrollBehaviors = new Set(['auto', 'instant', 'smooth']);
2090
+ const scrollBlocks = new Set(['start', 'center', 'end', 'nearest']);
2091
+ function asPlainRecord(value) {
2092
+ if (value === null || typeof value !== 'object' || Array.isArray(value))
2093
+ return null;
2094
+ const prototype = Object.getPrototypeOf(value);
2095
+ return prototype === Object.prototype || prototype === null ? value : null;
2096
+ }
2097
+ function unknownFieldIssues(record, allowed) {
2098
+ return Object.keys(record)
2099
+ .filter((key) => !allowed.has(key))
2100
+ .sort()
2101
+ .map((key) => ({
2102
+ path: key,
2103
+ code: 'unknown-field',
2104
+ message: `Unknown configuration field: ${key}.`,
2105
+ }));
2106
+ }
2107
+ function validateEnum(record, field, allowed, issues) {
2108
+ const value = record[field];
2109
+ if (value === undefined)
2110
+ return;
2111
+ if (typeof value !== 'string') {
2112
+ issues.push({ path: field, code: 'invalid-type', message: `${field} must be a string.` });
2113
+ }
2114
+ else if (!allowed.has(value)) {
2115
+ issues.push({ path: field, code: 'invalid-value', message: `${field} has an unsupported value.` });
2116
+ }
2117
+ }
2118
+ /** Validate a partial selected-options configuration update. */
2119
+ function validateSelectedOptionsConfig(candidate) {
2120
+ const record = asPlainRecord(candidate);
2121
+ if (!record) {
2122
+ return {
2123
+ valid: false,
2124
+ issues: [{ path: 'selectedOptions', code: 'invalid-type', message: 'selectedOptions must be a plain object.' }],
2125
+ };
2126
+ }
2127
+ const issues = unknownFieldIssues(record, SELECTED_OPTIONS_FIELDS);
2128
+ validateEnum(record, 'placement', placements, issues);
2129
+ validateEnum(record, 'groupedPlacement', groupedPlacements, issues);
2130
+ if (issues.length > 0)
2131
+ return { valid: false, issues };
2132
+ return {
2133
+ valid: true,
2134
+ value: {
2135
+ ...(record.placement === undefined ? {} : { placement: record.placement }),
2136
+ ...(record.groupedPlacement === undefined
2137
+ ? {}
2138
+ : { groupedPlacement: record.groupedPlacement }),
2139
+ },
2140
+ };
2141
+ }
2142
+ /** Validate a partial scroll-to-selected configuration update. */
2143
+ function validateScrollToSelectedConfig(candidate) {
2144
+ const record = asPlainRecord(candidate);
2145
+ if (!record) {
2146
+ return {
2147
+ valid: false,
2148
+ issues: [{ path: 'scrollToSelected', code: 'invalid-type', message: 'scrollToSelected must be a plain object.' }],
2149
+ };
2150
+ }
2151
+ const issues = unknownFieldIssues(record, SCROLL_TO_SELECTED_FIELDS);
2152
+ if (record.enabled !== undefined && typeof record.enabled !== 'boolean') {
2153
+ issues.push({ path: 'enabled', code: 'invalid-type', message: 'enabled must be a boolean.' });
2154
+ }
2155
+ validateEnum(record, 'multiSelectTarget', scrollTargets, issues);
2156
+ validateEnum(record, 'onOpen', openPolicies, issues);
2157
+ validateEnum(record, 'behavior', scrollBehaviors, issues);
2158
+ validateEnum(record, 'block', scrollBlocks, issues);
2159
+ if (issues.length > 0)
2160
+ return { valid: false, issues };
2161
+ return {
2162
+ valid: true,
2163
+ value: {
2164
+ ...(record.enabled === undefined ? {} : { enabled: record.enabled }),
2165
+ ...(record.multiSelectTarget === undefined
2166
+ ? {}
2167
+ : { multiSelectTarget: record.multiSelectTarget }),
2168
+ ...(record.onOpen === undefined ? {} : { onOpen: record.onOpen }),
2169
+ ...(record.behavior === undefined ? {} : { behavior: record.behavior }),
2170
+ ...(record.block === undefined ? {} : { block: record.block }),
2171
+ },
2172
+ };
2173
+ }
2174
+ /** Validate and copy only the new public configuration sections. */
2175
+ function validateSelectedOptionsConfigUpdate(config) {
2176
+ const result = { ...config };
2177
+ if (config.selectedOptions !== undefined) {
2178
+ const validation = validateSelectedOptionsConfig(config.selectedOptions);
2179
+ if (validation.valid)
2180
+ result.selectedOptions = validation.value;
2181
+ else
2182
+ delete result.selectedOptions;
2183
+ }
2184
+ if (config.scrollToSelected !== undefined) {
2185
+ const validation = validateScrollToSelectedConfig(config.scrollToSelected);
2186
+ if (validation.valid)
2187
+ result.scrollToSelected = validation.value;
2188
+ else
2189
+ delete result.scrollToSelected;
2190
+ }
2191
+ return result;
2192
+ }
2193
+
2077
2194
  /**
2078
2195
  * Global Configuration System for Select Components
2079
2196
  * Allows users to define default behaviors that can be overridden at component level
@@ -2113,9 +2230,14 @@ const defaultConfig = {
2113
2230
  scrollToSelected: {
2114
2231
  enabled: true,
2115
2232
  multiSelectTarget: 'first',
2233
+ onOpen: 'reveal',
2116
2234
  behavior: 'smooth',
2117
2235
  block: 'nearest',
2118
2236
  },
2237
+ selectedOptions: {
2238
+ placement: 'original',
2239
+ groupedPlacement: 'within-group',
2240
+ },
2119
2241
  loadMore: {
2120
2242
  enabled: false,
2121
2243
  itemsPerLoad: 3,
@@ -2198,7 +2320,8 @@ class SelectConfigManager {
2198
2320
  * Update global configuration (deep merge)
2199
2321
  */
2200
2322
  updateConfig(updates) {
2201
- this.config = this.deepMerge(this.config, updates);
2323
+ const acceptedUpdates = validateSelectedOptionsConfigUpdate(updates);
2324
+ this.config = this.deepMerge(this.config, acceptedUpdates);
2202
2325
  }
2203
2326
  /**
2204
2327
  * Reset to default configuration
@@ -2258,6 +2381,7 @@ const DEFAULT_CONFIG = {
2258
2381
  searchMode: 'local',
2259
2382
  paginationMode: 'page',
2260
2383
  firstPage: 1,
2384
+ minSearchCharacters: 0,
2261
2385
  };
2262
2386
  const ALLOWED_FIELDS = new Set([
2263
2387
  'protocol',
@@ -2265,6 +2389,7 @@ const ALLOWED_FIELDS = new Set([
2265
2389
  'paginationMode',
2266
2390
  'firstPage',
2267
2391
  'fetchLimit',
2392
+ 'minSearchCharacters',
2268
2393
  ]);
2269
2394
  function issue(path, code, message) {
2270
2395
  return { path, code, message };
@@ -2287,6 +2412,18 @@ function validatePositiveSafeInteger(candidate, key, issues) {
2287
2412
  issues.push(issue(key, 'invalid-positive-integer', `${key} must be a positive safe integer.`));
2288
2413
  }
2289
2414
  }
2415
+ function validateNonNegativeSafeInteger(candidate, issues) {
2416
+ const value = candidate.minSearchCharacters;
2417
+ if (value === undefined)
2418
+ return;
2419
+ if (typeof value !== 'number') {
2420
+ issues.push(issue('minSearchCharacters', 'invalid-type', 'minSearchCharacters must be a number.'));
2421
+ return;
2422
+ }
2423
+ if (!Number.isSafeInteger(value) || value < 0) {
2424
+ issues.push(issue('minSearchCharacters', 'invalid-value', 'minSearchCharacters must be a non-negative safe integer.'));
2425
+ }
2426
+ }
2290
2427
  /** Validate a complete effective per-instance data-loading configuration. */
2291
2428
  function validateDataLoadingConfig(candidate) {
2292
2429
  if (!isRecord$1(candidate)) {
@@ -2325,6 +2462,7 @@ function validateDataLoadingConfig(candidate) {
2325
2462
  }
2326
2463
  validatePositiveSafeInteger(candidate, 'firstPage', issues);
2327
2464
  validatePositiveSafeInteger(candidate, 'fetchLimit', issues);
2465
+ validateNonNegativeSafeInteger(candidate, issues);
2328
2466
  if (protocol === 'legacy' && (searchMode === 'remote' || searchMode === 'hybrid')) {
2329
2467
  issues.push(issue('searchMode', 'requires-acknowledged-protocol', 'Remote and hybrid search require the acknowledged protocol.'));
2330
2468
  }
@@ -2338,6 +2476,9 @@ function validateDataLoadingConfig(candidate) {
2338
2476
  searchMode: searchMode,
2339
2477
  paginationMode: paginationMode,
2340
2478
  firstPage: candidate.firstPage === undefined ? DEFAULT_CONFIG.firstPage : candidate.firstPage,
2479
+ minSearchCharacters: candidate.minSearchCharacters === undefined
2480
+ ? DEFAULT_CONFIG.minSearchCharacters
2481
+ : candidate.minSearchCharacters,
2341
2482
  ...(candidate.fetchLimit === undefined ? {} : { fetchLimit: candidate.fetchLimit }),
2342
2483
  };
2343
2484
  return { valid: true, value: resolved };
@@ -3141,6 +3282,94 @@ function arraysEqualByValue(a, b) {
3141
3282
  return true;
3142
3283
  }
3143
3284
 
3285
+ function createVisualNavigationModel(orderedKeys, isSelectable) {
3286
+ const ordered = [...orderedKeys];
3287
+ const selectableKeys = [];
3288
+ const positionByKey = new Map();
3289
+ const selectablePositionByKey = new Map();
3290
+ ordered.forEach((key, position) => {
3291
+ positionByKey.set(key, position);
3292
+ if (isSelectable(key)) {
3293
+ selectablePositionByKey.set(key, selectableKeys.length);
3294
+ selectableKeys.push(key);
3295
+ }
3296
+ });
3297
+ return { orderedKeys: ordered, selectableKeys, positionByKey, selectablePositionByKey };
3298
+ }
3299
+ /** Resolve a clamped keyboard movement in visual order. */
3300
+ function resolveVisualMovement(model, currentKey, delta) {
3301
+ const { selectableKeys, selectablePositionByKey } = model;
3302
+ if (selectableKeys.length === 0)
3303
+ return null;
3304
+ const currentPosition = currentKey === null ? undefined : selectablePositionByKey.get(currentKey);
3305
+ const basePosition = currentPosition ?? (delta >= 0 ? -1 : selectableKeys.length);
3306
+ const nextPosition = Math.max(0, Math.min(selectableKeys.length - 1, basePosition + delta));
3307
+ return selectableKeys[nextPosition] ?? null;
3308
+ }
3309
+ function resolveVisualBoundary(model, boundary) {
3310
+ return boundary === 'first'
3311
+ ? model.selectableKeys[0] ?? null
3312
+ : model.selectableKeys[model.selectableKeys.length - 1] ?? null;
3313
+ }
3314
+ /** Return selectable keys in the inclusive visual interval between two keys. */
3315
+ function resolveVisualRange(model, startKey, endKey) {
3316
+ const startPosition = model.positionByKey.get(startKey);
3317
+ const endPosition = model.positionByKey.get(endKey);
3318
+ if (startPosition === undefined || endPosition === undefined)
3319
+ return [];
3320
+ const low = Math.min(startPosition, endPosition);
3321
+ const high = Math.max(startPosition, endPosition);
3322
+ const selectable = new Set(model.selectableKeys);
3323
+ return model.orderedKeys.slice(low, high + 1).filter((key) => selectable.has(key));
3324
+ }
3325
+
3326
+ /**
3327
+ * Return a presentation-only ordering for option keys.
3328
+ *
3329
+ * The source array and selection set are never mutated. Callers remain
3330
+ * responsible for retaining the returned order as the displayed ordering for
3331
+ * the relevant render/open transaction.
3332
+ */
3333
+ function projectSelectedOptionKeys(orderedKeys, selectedKeys, placement) {
3334
+ const selected = [];
3335
+ const unselected = [];
3336
+ for (const key of orderedKeys) {
3337
+ (selectedKeys.has(key) ? selected : unselected).push(key);
3338
+ }
3339
+ return [...selected, ...unselected];
3340
+ }
3341
+ /**
3342
+ * Stably partitions selected keys to the front of each group independently.
3343
+ * Group order, identity, membership, and the source arrays are preserved.
3344
+ */
3345
+ function projectSelectedOptionGroups(groups, selectedKeys) {
3346
+ return groups.map(({ groupIdentity, orderedKeys }) => {
3347
+ const selected = [];
3348
+ const unselected = [];
3349
+ for (const key of orderedKeys) {
3350
+ (selectedKeys.has(key) ? selected : unselected).push(key);
3351
+ }
3352
+ return { groupIdentity, orderedKeys: [...selected, ...unselected] };
3353
+ });
3354
+ }
3355
+
3356
+ /** Resolve the selected key at an edge of the displayed eligible ordering. */
3357
+ function resolveSelectedTargetKey(orderedKeys, selectedKeys, target) {
3358
+ if (target === 'first') {
3359
+ for (const key of orderedKeys) {
3360
+ if (selectedKeys.has(key))
3361
+ return key;
3362
+ }
3363
+ return null;
3364
+ }
3365
+ for (let index = orderedKeys.length - 1; index >= 0; index -= 1) {
3366
+ const key = orderedKeys[index];
3367
+ if (selectedKeys.has(key))
3368
+ return key;
3369
+ }
3370
+ return null;
3371
+ }
3372
+
3144
3373
  /**
3145
3374
  * DOM-independent coordinator for the opt-in acknowledged data-loading
3146
3375
  * protocol. This module is intentionally not re-exported from the package
@@ -3236,6 +3465,7 @@ function configInput(config = {}) {
3236
3465
  searchMode: dataLoading.searchMode === undefined ? 'local' : dataLoading.searchMode,
3237
3466
  paginationMode: dataLoading.paginationMode === undefined ? 'page' : dataLoading.paginationMode,
3238
3467
  firstPage: dataLoading.firstPage === undefined ? 1 : dataLoading.firstPage,
3468
+ minSearchCharacters: dataLoading.minSearchCharacters === undefined ? 0 : dataLoading.minSearchCharacters,
3239
3469
  initialPage: infiniteScroll.initialPage === undefined ? 1 : infiniteScroll.initialPage,
3240
3470
  fetchLimit: dataLoading.fetchLimit,
3241
3471
  maxCursorPages: dataLoading.maxCursorPages === undefined
@@ -3274,6 +3504,9 @@ function validateDataCoordinatorConfig(config = {}) {
3274
3504
  if (!isPositiveSafeInteger(input.firstPage)) {
3275
3505
  add('dataLoading.firstPage', 'must be a positive safe integer');
3276
3506
  }
3507
+ if (!isNonNegativeSafeInteger(input.minSearchCharacters)) {
3508
+ add('dataLoading.minSearchCharacters', 'must be a non-negative safe integer');
3509
+ }
3277
3510
  if (!isPositiveSafeInteger(input.initialPage)) {
3278
3511
  add('infiniteScroll.initialPage', 'must be a positive safe integer');
3279
3512
  }
@@ -3313,6 +3546,7 @@ function validateDataCoordinatorConfig(config = {}) {
3313
3546
  searchMode: input.searchMode,
3314
3547
  paginationMode: input.paginationMode,
3315
3548
  firstPage: input.firstPage,
3549
+ minSearchCharacters: input.minSearchCharacters,
3316
3550
  initialPage: input.initialPage,
3317
3551
  fetchLimit: resolvedFetchLimit,
3318
3552
  maxCursorPages: input.maxCursorPages,
@@ -3358,6 +3592,8 @@ class DataRequestCoordinator {
3358
3592
  this.resourceLimit = null;
3359
3593
  this.sentinelBlocked = false;
3360
3594
  this.sentinelIntersecting = false;
3595
+ /** Unfiltered items and continuation are independent from each filtered query. */
3596
+ this.browseState = null;
3361
3597
  const initialConfig = options.config === undefined ? {} : options.config;
3362
3598
  const validation = validateDataCoordinatorConfig(initialConfig);
3363
3599
  if (!validation.valid) {
@@ -3368,12 +3604,24 @@ class DataRequestCoordinator {
3368
3604
  this.query = options.initialQuery ?? '';
3369
3605
  this.items = asFrozenItems(options.initialItems ?? []);
3370
3606
  const remote = this.isRemoteMode();
3371
- this.hasMore = remote ? false : options.hasMore ?? false;
3607
+ const searchEligible = this.isSearchEligible(this.query);
3608
+ this.hasMore = options.hasMore ?? false;
3372
3609
  this.nextEligiblePosition = this.initialPosition();
3373
- this.lastCommittedPage = this.config.paginationMode === 'page' && !remote
3374
- ? this.config.initialPage
3610
+ this.lastCommittedPage = this.config.paginationMode === 'page'
3611
+ ? (remote && searchEligible
3612
+ ? undefined
3613
+ : this.items.length > 0 ? this.config.initialPage : undefined)
3375
3614
  : undefined;
3376
- this.needsInitialRemoteSearch = remote;
3615
+ this.needsInitialRemoteSearch = remote && searchEligible;
3616
+ if (remote && searchEligible) {
3617
+ const browse = this.captureDataState();
3618
+ browse.lastCommittedPage = this.config.paginationMode === 'page' && this.items.length > 0
3619
+ ? this.config.initialPage
3620
+ : undefined;
3621
+ browse.nextEligiblePosition = this.browseInitialPosition();
3622
+ browse.needsInitialRemoteSearch = false;
3623
+ this.browseState = browse;
3624
+ }
3377
3625
  }
3378
3626
  getSnapshot() {
3379
3627
  const activeRequest = this.active?.request ?? null;
@@ -3407,7 +3655,7 @@ class DataRequestCoordinator {
3407
3655
  this.queryGeneration += 1;
3408
3656
  this.connected = true;
3409
3657
  this.hasConnected = true;
3410
- if (this.isRemoteMode() && this.needsInitialRemoteSearch) {
3658
+ if (this.isSearchEligible(this.query) && this.needsInitialRemoteSearch) {
3411
3659
  this.resetPaginationForRemoteQuery(true);
3412
3660
  const request = this.createSearchRequest();
3413
3661
  if (request)
@@ -3430,34 +3678,62 @@ class DataRequestCoordinator {
3430
3678
  setQuery(query) {
3431
3679
  if (typeof query !== 'string' || query === this.query)
3432
3680
  return immutableActions([]);
3681
+ if (!this.isRemoteMode()) {
3682
+ const actions = [];
3683
+ const cancellation = this.invalidateActive('query-changed');
3684
+ if (cancellation)
3685
+ actions.push(cancellation);
3686
+ this.query = query;
3687
+ this.queryGeneration += 1;
3688
+ this.resetQueryMetadata();
3689
+ this.lastCommittedPage = this.config.paginationMode === 'page' && this.items.length > 0
3690
+ ? this.config.initialPage
3691
+ : undefined;
3692
+ this.nextEligiblePosition = this.initialPosition();
3693
+ this.needsInitialRemoteSearch = false;
3694
+ return immutableActions(actions);
3695
+ }
3433
3696
  const actions = [];
3434
- const cancellation = this.invalidateActive('query-changed');
3435
- if (cancellation)
3436
- actions.push(cancellation);
3697
+ const wasSearchEligible = this.isSearchEligible(this.query);
3698
+ const willSearchBeEligible = this.isSearchEligible(query);
3699
+ const activeKind = this.active?.request.kind;
3700
+ // Edits that remain below threshold are presentation-only while browsing.
3701
+ // Do not cancel a legitimate unfiltered loadMore operation for those edits.
3702
+ const preserveBrowseLoad = !wasSearchEligible && !willSearchBeEligible && activeKind === 'loadMore';
3703
+ const enteringSearch = !wasSearchEligible && willSearchBeEligible;
3704
+ if (enteringSearch || !preserveBrowseLoad) {
3705
+ const cancellation = this.invalidateActive('query-changed');
3706
+ if (cancellation)
3707
+ actions.push(cancellation);
3708
+ }
3709
+ if (enteringSearch)
3710
+ this.browseState = this.captureDataState();
3437
3711
  this.query = query;
3438
- this.queryGeneration += 1;
3439
- this.error = null;
3440
- this.status = 'idle';
3441
- this.generationHasAcceptedResult = false;
3442
- this.retryAvailable = false;
3443
- this.retryPosition = undefined;
3444
- this.retryKind = undefined;
3445
- this.committedCursors.clear();
3446
- this.resourceLimit = null;
3447
- this.sentinelBlocked = false;
3448
- if (this.isRemoteMode()) {
3449
- this.resetPaginationForRemoteQuery(true);
3450
- this.needsInitialRemoteSearch = true;
3451
- if (this.connected) {
3452
- const request = this.createSearchRequest();
3453
- if (request)
3454
- actions.push(Object.freeze({ type: 'request', request }));
3455
- }
3712
+ // Below-threshold edits do not change browse request ownership. Keep the
3713
+ // generation stable while an unfiltered loadMore is in flight so its valid
3714
+ // completion is not made stale by presentation-only input.
3715
+ if (!preserveBrowseLoad)
3716
+ this.queryGeneration += 1;
3717
+ if (!wasSearchEligible && !willSearchBeEligible) {
3718
+ this.error = null;
3719
+ if (!this.active)
3720
+ this.status = 'idle';
3721
+ // Current state remains the unfiltered browse state. Keep its pagination
3722
+ // and accepted items intact while the user edits a short query.
3723
+ return immutableActions(actions);
3456
3724
  }
3457
- else {
3458
- this.lastCommittedPage = this.config.paginationMode === 'page' ? this.config.initialPage : undefined;
3459
- this.nextEligiblePosition = this.initialPosition();
3725
+ if (wasSearchEligible && !willSearchBeEligible) {
3726
+ this.restoreBrowseState();
3460
3727
  this.needsInitialRemoteSearch = false;
3728
+ return immutableActions(actions);
3729
+ }
3730
+ this.resetQueryMetadata();
3731
+ this.resetPaginationForRemoteQuery(true);
3732
+ this.needsInitialRemoteSearch = true;
3733
+ if (this.connected) {
3734
+ const request = this.createSearchRequest();
3735
+ if (request)
3736
+ actions.push(Object.freeze({ type: 'request', request }));
3461
3737
  }
3462
3738
  return immutableActions(actions);
3463
3739
  }
@@ -3483,12 +3759,43 @@ class DataRequestCoordinator {
3483
3759
  const protocolChanged = previous.protocol !== next.protocol ||
3484
3760
  previous.searchMode !== next.searchMode ||
3485
3761
  previous.paginationMode !== next.paginationMode;
3762
+ const thresholdChanged = previous.minSearchCharacters !== next.minSearchCharacters;
3486
3763
  this.rawConfig = copyCoordinatorConfig(candidate);
3487
3764
  this.config = next;
3488
- if (!protocolChanged) {
3765
+ if (!protocolChanged && !thresholdChanged) {
3489
3766
  this.refreshCursorDepthLimit();
3490
3767
  return Object.freeze({ status: 'accepted', actions: immutableActions([]) });
3491
3768
  }
3769
+ if (!protocolChanged && thresholdChanged) {
3770
+ const wasEligible = this.isSearchEligible(this.query, previous);
3771
+ const willBeEligible = this.isSearchEligible(this.query, next);
3772
+ if (wasEligible === willBeEligible) {
3773
+ this.refreshCursorDepthLimit();
3774
+ return Object.freeze({ status: 'accepted', actions: immutableActions([]) });
3775
+ }
3776
+ const actions = [];
3777
+ const cancellation = this.invalidateActive('config-changed');
3778
+ if (cancellation)
3779
+ actions.push(cancellation);
3780
+ this.queryGeneration += 1;
3781
+ if (wasEligible && !willBeEligible) {
3782
+ this.resetQueryMetadata();
3783
+ this.restoreBrowseState();
3784
+ this.needsInitialRemoteSearch = false;
3785
+ }
3786
+ else {
3787
+ this.browseState = this.captureDataState();
3788
+ this.resetQueryMetadata();
3789
+ this.resetPaginationForRemoteQuery(true);
3790
+ this.needsInitialRemoteSearch = true;
3791
+ if (this.connected) {
3792
+ const request = this.createSearchRequest();
3793
+ if (request)
3794
+ actions.push(Object.freeze({ type: 'request', request }));
3795
+ }
3796
+ }
3797
+ return Object.freeze({ status: 'accepted', actions: immutableActions(actions) });
3798
+ }
3492
3799
  const actions = [];
3493
3800
  const cancellation = this.invalidateActive('config-changed');
3494
3801
  if (cancellation)
@@ -3504,12 +3811,13 @@ class DataRequestCoordinator {
3504
3811
  this.resourceLimit = null;
3505
3812
  this.sentinelBlocked = false;
3506
3813
  this.hasMore = this.isRemoteMode() ? false : this.hasMore;
3507
- this.lastCommittedPage = this.config.paginationMode === 'page' && !this.isRemoteMode()
3814
+ this.lastCommittedPage = this.config.paginationMode === 'page' && !this.isRemoteMode() && this.items.length > 0
3508
3815
  ? this.config.initialPage
3509
3816
  : undefined;
3510
3817
  this.nextEligiblePosition = this.initialPosition();
3511
3818
  this.needsInitialRemoteSearch = this.isRemoteMode();
3512
- if (this.connected && this.isRemoteMode()) {
3819
+ this.browseState = null;
3820
+ if (this.connected && this.isSearchEligible(this.query)) {
3513
3821
  const request = this.createSearchRequest();
3514
3822
  if (request)
3515
3823
  actions.push(Object.freeze({ type: 'request', request }));
@@ -3700,13 +4008,93 @@ class DataRequestCoordinator {
3700
4008
  isRemoteMode() {
3701
4009
  return this.config.searchMode === 'remote' || this.config.searchMode === 'hybrid';
3702
4010
  }
4011
+ isSearchEligible(query, config = this.config) {
4012
+ if (config.protocol !== 'acknowledged' ||
4013
+ (config.searchMode !== 'remote' && config.searchMode !== 'hybrid'))
4014
+ return true;
4015
+ return Array.from(query.trim()).length >= config.minSearchCharacters;
4016
+ }
4017
+ captureDataState() {
4018
+ return {
4019
+ items: this.items,
4020
+ hasMore: this.hasMore,
4021
+ status: this.status,
4022
+ lastCommittedPage: this.lastCommittedPage,
4023
+ nextEligiblePosition: this.nextEligiblePosition,
4024
+ committedCursors: new Set(this.committedCursors),
4025
+ generationHasAcceptedResult: this.generationHasAcceptedResult,
4026
+ needsInitialRemoteSearch: this.needsInitialRemoteSearch,
4027
+ retryAvailable: this.retryAvailable,
4028
+ retryPosition: this.retryPosition,
4029
+ retryKind: this.retryKind,
4030
+ error: this.error,
4031
+ resourceLimit: this.resourceLimit,
4032
+ sentinelBlocked: this.sentinelBlocked,
4033
+ };
4034
+ }
4035
+ restoreBrowseState() {
4036
+ if (this.browseState) {
4037
+ const state = this.browseState;
4038
+ this.items = state.items;
4039
+ this.hasMore = state.hasMore;
4040
+ this.status = state.status;
4041
+ this.lastCommittedPage = state.lastCommittedPage;
4042
+ this.nextEligiblePosition = state.nextEligiblePosition;
4043
+ this.committedCursors = new Set(state.committedCursors);
4044
+ this.generationHasAcceptedResult = state.generationHasAcceptedResult;
4045
+ this.needsInitialRemoteSearch = state.needsInitialRemoteSearch;
4046
+ this.retryAvailable = state.retryAvailable;
4047
+ this.retryPosition = state.retryPosition;
4048
+ this.retryKind = state.retryKind;
4049
+ this.error = state.error;
4050
+ this.resourceLimit = state.resourceLimit;
4051
+ this.sentinelBlocked = state.sentinelBlocked;
4052
+ this.browseState = null;
4053
+ return;
4054
+ }
4055
+ this.items = asFrozenItems([]);
4056
+ this.hasMore = false;
4057
+ this.status = 'idle';
4058
+ this.lastCommittedPage = undefined;
4059
+ this.nextEligiblePosition = this.browseInitialPosition();
4060
+ this.committedCursors.clear();
4061
+ this.generationHasAcceptedResult = false;
4062
+ this.retryAvailable = false;
4063
+ this.retryPosition = undefined;
4064
+ this.retryKind = undefined;
4065
+ this.error = null;
4066
+ this.resourceLimit = null;
4067
+ this.sentinelBlocked = false;
4068
+ }
4069
+ resetQueryMetadata() {
4070
+ this.error = null;
4071
+ this.status = 'idle';
4072
+ this.generationHasAcceptedResult = false;
4073
+ this.retryAvailable = false;
4074
+ this.retryPosition = undefined;
4075
+ this.retryKind = undefined;
4076
+ this.committedCursors.clear();
4077
+ this.resourceLimit = null;
4078
+ this.sentinelBlocked = false;
4079
+ }
3703
4080
  initialPosition() {
3704
4081
  if (this.config.paginationMode === 'cursor') {
3705
4082
  return Object.freeze({ mode: 'cursor', ordinal: 1 });
3706
4083
  }
3707
- const page = this.isRemoteMode() ? this.config.firstPage : this.config.initialPage + 1;
4084
+ const page = this.isRemoteMode() && this.isSearchEligible(this.query)
4085
+ ? this.config.firstPage
4086
+ : this.items.length > 0 ? this.config.initialPage + 1 : this.config.initialPage;
3708
4087
  return Object.freeze({ mode: 'page', page });
3709
4088
  }
4089
+ browseInitialPosition() {
4090
+ if (this.config.paginationMode === 'cursor') {
4091
+ return Object.freeze({ mode: 'cursor', ordinal: 1 });
4092
+ }
4093
+ return Object.freeze({
4094
+ mode: 'page',
4095
+ page: this.items.length > 0 ? this.config.initialPage + 1 : this.config.initialPage,
4096
+ });
4097
+ }
3710
4098
  resetPaginationForRemoteQuery(clearItems) {
3711
4099
  this.hasMore = false;
3712
4100
  this.lastCommittedPage = undefined;
@@ -3747,7 +4135,10 @@ class DataRequestCoordinator {
3747
4135
  }
3748
4136
  }
3749
4137
  createSearchRequest(position = this.nextEligiblePosition) {
3750
- if (!this.connected || !this.isRemoteMode() || this.config.protocol !== 'acknowledged')
4138
+ if (!this.connected
4139
+ || !this.isRemoteMode()
4140
+ || this.config.protocol !== 'acknowledged'
4141
+ || !this.isSearchEligible(this.query))
3751
4142
  return null;
3752
4143
  const request = this.createRequest({ kind: 'search', mode: this.config.searchMode }, position);
3753
4144
  if (request) {
@@ -3770,12 +4161,17 @@ class DataRequestCoordinator {
3770
4161
  return null;
3771
4162
  this.requestSequence += 1;
3772
4163
  const check = requestIdCheck(this.requestIdSecret, this.instanceId, this.queryGeneration, this.requestSequence);
4164
+ const requestQuery = kind.kind === 'loadMore'
4165
+ && this.isRemoteMode()
4166
+ && !this.isSearchEligible(this.query)
4167
+ ? ''
4168
+ : this.query;
3773
4169
  const requestId = `data-${this.instanceId}-generation-${this.queryGeneration}-request-${this.requestSequence}-${check}`;
3774
4170
  const base = Object.freeze({
3775
4171
  requestId,
3776
4172
  queryGeneration: this.queryGeneration,
3777
- query: this.query,
3778
- normalizedQuery: this.query.trim(),
4173
+ query: requestQuery,
4174
+ normalizedQuery: requestQuery.trim(),
3779
4175
  fetchLimit,
3780
4176
  position: frozenPosition(position),
3781
4177
  });
@@ -3945,8 +4341,11 @@ const LEGACY_DATA_LOADING_CONFIG = {
3945
4341
  searchMode: 'local',
3946
4342
  paginationMode: 'page',
3947
4343
  firstPage: 1,
4344
+ minSearchCharacters: 0,
3948
4345
  };
3949
- const DATA_LOADING_CONFIG_FIELDS = ['protocol', 'searchMode', 'paginationMode', 'firstPage', 'fetchLimit'];
4346
+ const DATA_LOADING_CONFIG_FIELDS = [
4347
+ 'protocol', 'searchMode', 'paginationMode', 'firstPage', 'fetchLimit', 'minSearchCharacters',
4348
+ ];
3950
4349
  const INVALID_OBJECT_VALUE = Object.freeze({ kind: 'object' });
3951
4350
  const INVALID_ARRAY_VALUE = Object.freeze({ kind: 'array' });
3952
4351
  const INVALID_FUNCTION_VALUE = Object.freeze({ kind: 'function' });
@@ -4065,8 +4464,27 @@ class EnhancedSelect extends HTMLElement {
4065
4464
  filteredIndices: [],
4066
4465
  filteredKeys: [],
4067
4466
  intendedRenderKeys: [],
4467
+ displayIndexByKey: new Map(),
4468
+ sourceIndexByKey: new Map(),
4068
4469
  filteredIndexByKey: new Map(),
4470
+ groupedPresentation: [],
4069
4471
  };
4472
+ // Presentation policy and membership are snapshotted when the dropdown opens
4473
+ // so selection/config updates cannot reorder an active list.
4474
+ this._selectedOptionsSelectionAtOpen = null;
4475
+ this._selectedOptionsConfigAtOpen = {
4476
+ placement: 'original',
4477
+ groupedPlacement: 'within-group',
4478
+ };
4479
+ this._scrollToSelectedConfigAtOpen = {
4480
+ enabled: true,
4481
+ multiSelectTarget: 'first',
4482
+ onOpen: 'reveal',
4483
+ behavior: 'smooth',
4484
+ block: 'nearest',
4485
+ };
4486
+ this._closedOptionsViewportAnchor = null;
4487
+ this._openOptionsViewportAnchor = null;
4070
4488
  this._emptyStateContext = null;
4071
4489
  // Null keeps the public/default renderer on its legacy full path. This
4072
4490
  // private state is only used by guarded virtualization integration.
@@ -4123,7 +4541,7 @@ class EnhancedSelect extends HTMLElement {
4123
4541
  this._boundArrowClick = null;
4124
4542
  this._pendingFirstRenderMark = false;
4125
4543
  this._pendingSearchRenderMark = false;
4126
- this._rangeAnchorIndex = null;
4544
+ this._rangeAnchorKey = null;
4127
4545
  /** Chip identity is tracked independently of dropdown option positions. */
4128
4546
  this._lastRenderedChipKeys = null;
4129
4547
  this._latestChipScrollGeneration = 0;
@@ -4141,6 +4559,9 @@ class EnhancedSelect extends HTMLElement {
4141
4559
  this._lifecycleTimers = new Set();
4142
4560
  this._lifecycleRafs = new Set();
4143
4561
  this._keyboardActiveChangeGeneration = 0;
4562
+ /** Invalidates selected-option positioning scheduled by an earlier opening. */
4563
+ this._openSelectedScrollGeneration = 0;
4564
+ this._openSelectedScrollCleanup = null;
4144
4565
  this._tracking = { events: [], styles: [], limitations: [] };
4145
4566
  this._suppressBlurClose = false;
4146
4567
  this._renderCycleId = 0;
@@ -4318,6 +4739,7 @@ class EnhancedSelect extends HTMLElement {
4318
4739
  this._syncListboxAccessibility();
4319
4740
  }
4320
4741
  disconnectedCallback() {
4742
+ this._cancelOpenSelectedScroll();
4321
4743
  this._cancelLatestChipScroll();
4322
4744
  this._cancelBusyPresentation();
4323
4745
  if (this._dataRequestCoordinator) {
@@ -4904,12 +5326,12 @@ class EnhancedSelect extends HTMLElement {
4904
5326
  duplicateKeyPolicy: this._getDuplicateKeyPolicy(),
4905
5327
  });
4906
5328
  const activeKey = this._engine.state.activeKey;
4907
- const anchorKey = this._rangeAnchorIndex === null ? undefined : this._itemRegistry.indexToKey.get(this._rangeAnchorIndex);
5329
+ const anchorKey = this._rangeAnchorKey;
4908
5330
  this._itemRegistry = registry;
4909
5331
  this._state.loadedItems = items;
4910
5332
  this._registryItemsRef = items;
4911
5333
  const disabledKeys = this._getBlockedDisabledKeys();
4912
- this._rangeAnchorIndex = anchorKey === undefined ? null : registry.keyToIndex.get(anchorKey) ?? null;
5334
+ this._rangeAnchorKey = anchorKey !== null && registry.keyToRecord.has(anchorKey) ? anchorKey : null;
4913
5335
  this._engine.dispatch({
4914
5336
  type: 'ITEMS_REGISTERED',
4915
5337
  keys: registry.records.map((record) => record.key),
@@ -6158,7 +6580,7 @@ class EnhancedSelect extends HTMLElement {
6158
6580
  ───────────────────────────────────────────────────────────────────────── */
6159
6581
 
6160
6582
  .dropdown-arrow-container {
6161
- position: absolute;
6583
+ position: var(--select-arrow-container-position, absolute);
6162
6584
  top: 0;
6163
6585
  right: 0;
6164
6586
  bottom: 0;
@@ -6467,7 +6889,7 @@ class EnhancedSelect extends HTMLElement {
6467
6889
  font-weight: var(--select-group-header-weight, 600);
6468
6890
  color: var(--select-group-header-color, var(--select-text-muted));
6469
6891
  background: var(--select-group-header-bg, #f3f4f6);
6470
- text-align: var(--select-group-header-text-align, left);
6892
+ text-align: var(--select-group-header-text-align, start);
6471
6893
  font-size: var(--select-group-header-font-size, 0.7333em);
6472
6894
  text-transform: var(--select-group-header-text-transform, uppercase);
6473
6895
  letter-spacing: var(--select-group-header-letter-spacing, 0.08em);
@@ -7454,6 +7876,15 @@ class EnhancedSelect extends HTMLElement {
7454
7876
  this._dropdown.removeAttribute('inert');
7455
7877
  this._dropdown.removeAttribute('aria-hidden');
7456
7878
  this._markOpenStart();
7879
+ this._scrollToSelectedConfigAtOpen = { ...this._config.scrollToSelected };
7880
+ this._openOptionsViewportAnchor = this._scrollToSelectedConfigAtOpen.onOpen === 'preserve'
7881
+ ? (this._closedOptionsViewportAnchor ?? this._captureOptionsViewportAnchor())
7882
+ : null;
7883
+ this._closedOptionsViewportAnchor = null;
7884
+ this._selectedOptionsConfigAtOpen = { ...this._config.selectedOptions };
7885
+ this._selectedOptionsSelectionAtOpen = this._config.selectedOptions.placement === 'selected-first'
7886
+ ? new Set(this._engine.state.selectedKeys)
7887
+ : null;
7457
7888
  this.setAttribute('data-open', 'true');
7458
7889
  this._liftStackingAncestors();
7459
7890
  this._dropdown.style.display = 'block';
@@ -7465,28 +7896,17 @@ class EnhancedSelect extends HTMLElement {
7465
7896
  this._emit('open', {});
7466
7897
  this._config.callbacks.onOpen?.();
7467
7898
  this._announce('Options expanded');
7468
- // Scroll to selected if configured
7469
- if (this._config.scrollToSelected.enabled) {
7470
- const keyboardActiveChangeGeneration = this._keyboardActiveChangeGeneration;
7471
- const canRestoreOpenSelection = () => this._state.isOpen
7472
- && this._keyboardActiveChangeGeneration === keyboardActiveChangeGeneration;
7473
- // Use requestAnimationFrame for better timing after render
7474
- this._requestLifecycleFrame(() => {
7475
- if (!canRestoreOpenSelection())
7476
- return;
7477
- // Double RAF to ensure layout is complete
7478
- this._requestLifecycleFrame(() => {
7479
- if (!canRestoreOpenSelection())
7480
- return;
7481
- this._scrollToSelected();
7482
- });
7483
- });
7484
- }
7899
+ this._scheduleOpenSelectedScroll();
7485
7900
  }
7486
7901
  _handleClose(reason = 'programmatic') {
7902
+ if (this._state.isOpen) {
7903
+ this._closedOptionsViewportAnchor = this._captureOptionsViewportAnchor();
7904
+ }
7487
7905
  const effects = this._engine.dispatch({ type: 'CLOSE_REQUEST', reason });
7488
7906
  if (!effects.some((effect) => effect.type === 'POPUP_CLOSED'))
7489
7907
  return;
7908
+ this._cancelOpenSelectedScroll();
7909
+ this._selectedOptionsSelectionAtOpen = null;
7490
7910
  this.removeAttribute('data-open');
7491
7911
  this._restoreLiftedAncestors();
7492
7912
  this._dropdown.setAttribute('data-placement', this._resolvedDropdownPlacement);
@@ -7498,6 +7918,257 @@ class EnhancedSelect extends HTMLElement {
7498
7918
  this._config.callbacks.onClose?.();
7499
7919
  this._announce('Options collapsed');
7500
7920
  }
7921
+ /**
7922
+ * Defer the one automatic selected-option positioning operation until the
7923
+ * dropdown's own entrance geometry has settled. Logical active/ARIA state
7924
+ * remains synchronous in _setInitialActiveOption().
7925
+ */
7926
+ _scheduleOpenSelectedScroll() {
7927
+ this._cancelOpenSelectedScroll();
7928
+ const openingConfig = this._scrollToSelectedConfigAtOpen;
7929
+ if (!openingConfig.enabled)
7930
+ return;
7931
+ const generation = this._openSelectedScrollGeneration;
7932
+ const keyboardGeneration = this._keyboardActiveChangeGeneration;
7933
+ const initialScrollTop = this._optionsContainer.scrollTop;
7934
+ const animations = [];
7935
+ const frameIds = new Set();
7936
+ let timerId = null;
7937
+ let completed = false;
7938
+ const isCurrent = () => generation === this._openSelectedScrollGeneration
7939
+ && this._state.isOpen
7940
+ && this.isConnected
7941
+ && this._config.scrollToSelected.enabled
7942
+ && keyboardGeneration === this._keyboardActiveChangeGeneration;
7943
+ const removeListeners = () => {
7944
+ this._optionsContainer.removeEventListener('wheel', cancelForUserInput);
7945
+ this._optionsContainer.removeEventListener('touchstart', cancelForUserInput);
7946
+ this._optionsContainer.removeEventListener('pointerdown', cancelForUserInput);
7947
+ this._optionsContainer.removeEventListener('scroll', cancelForUserScroll);
7948
+ for (const animation of animations) {
7949
+ animation.removeEventListener('finish', onAnimationStateChange);
7950
+ animation.removeEventListener('cancel', onAnimationStateChange);
7951
+ }
7952
+ };
7953
+ const cleanup = () => {
7954
+ removeListeners();
7955
+ for (const id of frameIds)
7956
+ cancelAnimationFrame(id);
7957
+ frameIds.clear();
7958
+ if (timerId !== null) {
7959
+ clearTimeout(timerId);
7960
+ this._lifecycleTimers.delete(timerId);
7961
+ timerId = null;
7962
+ }
7963
+ if (this._openSelectedScrollCleanup === cleanup) {
7964
+ this._openSelectedScrollCleanup = null;
7965
+ }
7966
+ };
7967
+ const cancelForUserInput = () => this._cancelOpenSelectedScroll();
7968
+ const cancelForUserScroll = () => {
7969
+ if (Math.abs(this._optionsContainer.scrollTop - initialScrollTop) > 1) {
7970
+ this._cancelOpenSelectedScroll();
7971
+ }
7972
+ };
7973
+ const finish = () => {
7974
+ if (completed)
7975
+ return;
7976
+ completed = true;
7977
+ cleanup();
7978
+ if (!isCurrent())
7979
+ return;
7980
+ const frameId = requestAnimationFrame(() => {
7981
+ frameIds.delete(frameId);
7982
+ cleanup();
7983
+ if (!isCurrent())
7984
+ return;
7985
+ if (openingConfig.onOpen === 'preserve') {
7986
+ this._restorePreservedOptionsViewport();
7987
+ }
7988
+ else {
7989
+ this._scrollToSelected({
7990
+ onlyIfNeeded: openingConfig.onOpen === 'reveal',
7991
+ setActive: false,
7992
+ config: openingConfig,
7993
+ });
7994
+ }
7995
+ });
7996
+ frameIds.add(frameId);
7997
+ this._openSelectedScrollCleanup = cleanup;
7998
+ };
7999
+ const onAnimationStateChange = () => {
8000
+ if (animations.every((animation) => animation.playState === 'finished' || animation.playState === 'idle'))
8001
+ finish();
8002
+ };
8003
+ const begin = () => {
8004
+ if (!isCurrent()) {
8005
+ cleanup();
8006
+ return;
8007
+ }
8008
+ const getAnimations = this._dropdown.getAnimations;
8009
+ const reducedMotion = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches ?? false;
8010
+ if (!reducedMotion && typeof getAnimations === 'function') {
8011
+ for (const animation of getAnimations.call(this._dropdown)) {
8012
+ const timing = animation.effect?.getComputedTiming();
8013
+ if (!timing || timing.iterations === Infinity || animation.playState === 'finished'
8014
+ || animation.playState === 'idle')
8015
+ continue;
8016
+ animations.push(animation);
8017
+ }
8018
+ }
8019
+ if (animations.length === 0) {
8020
+ if (!reducedMotion && typeof getAnimations !== 'function') {
8021
+ const fallbackWait = this._getDropdownEntranceFallbackDurationMs();
8022
+ if (fallbackWait > 0) {
8023
+ timerId = window.setTimeout(finish, fallbackWait + 34);
8024
+ this._lifecycleTimers.add(timerId);
8025
+ return;
8026
+ }
8027
+ }
8028
+ finish();
8029
+ return;
8030
+ }
8031
+ for (const animation of animations) {
8032
+ animation.addEventListener('finish', onAnimationStateChange);
8033
+ animation.addEventListener('cancel', onAnimationStateChange);
8034
+ }
8035
+ const remainingMs = Math.max(...animations.map((animation) => {
8036
+ const timing = animation.effect?.getComputedTiming();
8037
+ const endTime = Number(timing?.endTime);
8038
+ const currentTime = Number(animation.currentTime ?? 0);
8039
+ return Number.isFinite(endTime) ? Math.max(0, endTime - currentTime) : 0;
8040
+ }));
8041
+ const boundedWait = Math.min(10000, remainingMs + 50);
8042
+ timerId = window.setTimeout(finish, boundedWait);
8043
+ this._lifecycleTimers.add(timerId);
8044
+ };
8045
+ this._optionsContainer.addEventListener('wheel', cancelForUserInput, { passive: true });
8046
+ this._optionsContainer.addEventListener('touchstart', cancelForUserInput, { passive: true });
8047
+ this._optionsContainer.addEventListener('pointerdown', cancelForUserInput, { passive: true });
8048
+ this._optionsContainer.addEventListener('scroll', cancelForUserScroll, { passive: true });
8049
+ this._openSelectedScrollCleanup = cleanup;
8050
+ const frameId = requestAnimationFrame(() => {
8051
+ frameIds.delete(frameId);
8052
+ begin();
8053
+ });
8054
+ frameIds.add(frameId);
8055
+ }
8056
+ _cancelOpenSelectedScroll() {
8057
+ this._openSelectedScrollGeneration += 1;
8058
+ this._openSelectedScrollCleanup?.();
8059
+ this._openSelectedScrollCleanup = null;
8060
+ }
8061
+ _captureOptionsViewportAnchor() {
8062
+ const scroller = this._optionsContainer;
8063
+ const scrollTop = scroller.scrollTop;
8064
+ const order = this._renderPlan.filteredKeys.slice();
8065
+ const viewportTop = scroller.getBoundingClientRect().top + scroller.clientTop;
8066
+ const viewportBottom = viewportTop + scroller.clientHeight;
8067
+ const visible = Array.from(scroller.querySelectorAll('[data-sm-selectable], [data-selectable]'))
8068
+ .map((option) => ({ option, rect: option.getBoundingClientRect() }))
8069
+ .filter(({ rect }) => rect.height > 0 && rect.bottom > viewportTop && rect.top < viewportBottom)
8070
+ .sort((left, right) => left.rect.top - right.rect.top)[0];
8071
+ if (visible) {
8072
+ const sourceIndex = Number(visible.option.getAttribute('data-sm-index') ?? visible.option.getAttribute('data-index'));
8073
+ const key = Number.isInteger(sourceIndex) ? this._itemRegistry.indexToKey.get(sourceIndex) ?? null : null;
8074
+ if (key !== null) {
8075
+ return { key, offset: visible.rect.top - viewportTop, scrollTop, order };
8076
+ }
8077
+ }
8078
+ if (this._guardedVirtualizer && order.length > 0
8079
+ && typeof this._guardedVirtualizer.computeWindow === 'function') {
8080
+ const viewportHeight = this._resolveGuardedViewportHeight();
8081
+ const index = this._guardedVirtualizer.computeWindow(scrollTop, viewportHeight).startIndex;
8082
+ const key = order[index] ?? null;
8083
+ if (key !== null) {
8084
+ return {
8085
+ key,
8086
+ offset: this._guardedVirtualizer.cumulativeOffset(index) - scrollTop,
8087
+ scrollTop,
8088
+ order,
8089
+ };
8090
+ }
8091
+ }
8092
+ return { key: null, offset: 0, scrollTop, order };
8093
+ }
8094
+ /** Restore the previous visible option only when this opening changed order. */
8095
+ _restorePreservedOptionsViewport() {
8096
+ const anchor = this._openOptionsViewportAnchor;
8097
+ this._openOptionsViewportAnchor = null;
8098
+ if (!anchor)
8099
+ return;
8100
+ const nextOrder = this._renderPlan.filteredKeys;
8101
+ const nextPositionByKey = new Map(nextOrder.map((key, index) => [key, index]));
8102
+ const orderChanged = anchor.order.some((key, oldIndex) => {
8103
+ const nextIndex = nextPositionByKey.get(key);
8104
+ return nextIndex !== undefined && nextIndex !== oldIndex;
8105
+ });
8106
+ if (!orderChanged)
8107
+ return;
8108
+ const scroller = this._optionsContainer;
8109
+ const viewportHeight = this._resolveGuardedViewportHeight() || scroller.clientHeight;
8110
+ let targetScrollTop = null;
8111
+ if (anchor.key !== null) {
8112
+ const displayIndex = this._renderPlan.displayIndexByKey.get(anchor.key);
8113
+ if (displayIndex !== undefined) {
8114
+ const sourceIndex = this._renderPlan.sourceIndexByKey.get(anchor.key);
8115
+ const option = sourceIndex === undefined ? null : this._getOptionElementByIndex(sourceIndex);
8116
+ const viewportTop = scroller.getBoundingClientRect().top + scroller.clientTop;
8117
+ const optionTop = option?.getBoundingClientRect().top;
8118
+ if (option && option.getBoundingClientRect().height > 0 && Number.isFinite(optionTop)) {
8119
+ targetScrollTop = scroller.scrollTop + optionTop - viewportTop - anchor.offset;
8120
+ }
8121
+ else if (this._guardedVirtualizer) {
8122
+ targetScrollTop = this._guardedVirtualizer.cumulativeOffset(displayIndex) - anchor.offset;
8123
+ }
8124
+ }
8125
+ }
8126
+ if (targetScrollTop === null)
8127
+ targetScrollTop = anchor.scrollTop;
8128
+ let maxScrollTop = Number.POSITIVE_INFINITY;
8129
+ if (this._guardedVirtualizer) {
8130
+ maxScrollTop = Math.max(0, this._guardedVirtualizer.cumulativeOffset(nextOrder.length) - viewportHeight);
8131
+ }
8132
+ else if (scroller.scrollHeight > 0 && scroller.clientHeight > 0) {
8133
+ maxScrollTop = Math.max(0, scroller.scrollHeight - scroller.clientHeight);
8134
+ }
8135
+ targetScrollTop = Math.max(0, Math.min(targetScrollTop, maxScrollTop));
8136
+ if (Math.abs(targetScrollTop - scroller.scrollTop) < 1)
8137
+ return;
8138
+ // The coordinator owns this single restoration write. The virtualizer may
8139
+ // update its mounted window in response, but it must not issue a second
8140
+ // physical positioning correction for this transaction.
8141
+ this._guardedVirtualScrollTop = targetScrollTop;
8142
+ scroller.scrollTop = targetScrollTop;
8143
+ }
8144
+ /** Used only when Element.getAnimations() is unavailable. */
8145
+ _getDropdownEntranceFallbackDurationMs() {
8146
+ if (window.matchMedia?.('(prefers-reduced-motion: reduce)').matches)
8147
+ return 0;
8148
+ const style = getComputedStyle(this._dropdown);
8149
+ const parseTime = (value) => {
8150
+ const trimmed = value.trim();
8151
+ const parsed = Number.parseFloat(trimmed);
8152
+ if (!Number.isFinite(parsed))
8153
+ return 0;
8154
+ return trimmed.endsWith('ms') ? parsed : trimmed.endsWith('s') ? parsed * 1000 : 0;
8155
+ };
8156
+ const animationDurations = style.animationDuration.split(',');
8157
+ const animationDelays = style.animationDelay.split(',');
8158
+ const animationIterations = style.animationIterationCount.split(',');
8159
+ const maxAnimation = Math.max(0, ...animationDurations.map((duration, index) => {
8160
+ const count = Number.parseFloat(animationIterations[index % animationIterations.length] ?? '1');
8161
+ if (!Number.isFinite(count))
8162
+ return 0;
8163
+ return parseTime(duration)
8164
+ * Math.max(0, count)
8165
+ + parseTime(animationDelays[index % animationDelays.length] ?? '0s');
8166
+ }));
8167
+ const transitionDurations = style.transitionDuration.split(',');
8168
+ const transitionDelays = style.transitionDelay.split(',');
8169
+ const maxTransition = Math.max(0, ...transitionDurations.map((duration, index) => parseTime(duration) + parseTime(transitionDelays[index % transitionDelays.length] ?? '0s')));
8170
+ return Math.min(10000, Math.max(maxAnimation, maxTransition));
8171
+ }
7501
8172
  /** Stop an outstanding exit before reopening, disconnecting or starting another one. */
7502
8173
  _cancelDropdownExit() {
7503
8174
  if (this._dropdownExitTimer !== null) {
@@ -7736,16 +8407,40 @@ class EnhancedSelect extends HTMLElement {
7736
8407
  }
7737
8408
  if (this._dataLoadingConfig.protocol === 'acknowledged'
7738
8409
  && (this._dataLoadingConfig.searchMode === 'remote' || this._dataLoadingConfig.searchMode === 'hybrid')) {
8410
+ const wasEligible = Array.from(this._state.searchQuery.trim()).length
8411
+ >= this._dataLoadingConfig.minSearchCharacters;
8412
+ const isEligible = Array.from(query.trim()).length >= this._dataLoadingConfig.minSearchCharacters;
8413
+ if (wasEligible && !isEligible)
8414
+ this._cancelBusyPresentation();
7739
8415
  this._state.searchQuery = query;
7740
8416
  this._syncClearControlState();
7741
8417
  this._state.lastNotifiedQuery = query;
7742
8418
  this._state.lastNotifiedResultCount = 0;
7743
8419
  if (this._dataRequestCoordinator) {
8420
+ const beforeSnapshot = this._dataRequestCoordinator.getSnapshot();
7744
8421
  const actions = this._dataRequestCoordinator.setQuery(query);
7745
8422
  if (this._acknowledgedReady)
7746
8423
  this._dispatchAcknowledgedActions(actions);
7747
- else
8424
+ const startsRequest = actions.some((action) => action.type === 'request');
8425
+ if (this._acknowledgedReady && !startsRequest) {
8426
+ const snapshot = this._dataRequestCoordinator.getSnapshot();
8427
+ const restoredDataChanged = beforeSnapshot.items.length !== snapshot.items.length
8428
+ || beforeSnapshot.items.some((item, index) => item !== snapshot.items[index])
8429
+ || beforeSnapshot.hasMore !== snapshot.hasMore
8430
+ || JSON.stringify(beforeSnapshot.nextEligiblePosition) !== JSON.stringify(snapshot.nextEligiblePosition);
8431
+ this._state.isBusy = snapshot.busy || this._acknowledgedProjectionPending;
8432
+ this._state.isSearching = snapshot.activeRequest?.kind === 'search';
8433
+ this._syncListboxAccessibility();
8434
+ if (actions.some((action) => action.type === 'cancel') || restoredDataChanged) {
8435
+ void this._projectAcknowledgedSnapshot(snapshot, null, false);
8436
+ }
8437
+ else {
8438
+ this._renderOptions();
8439
+ }
8440
+ }
8441
+ else if (!this._acknowledgedReady) {
7748
8442
  this._renderOptions();
8443
+ }
7749
8444
  }
7750
8445
  else if (!this._state.isOpen) {
7751
8446
  this._handleOpen();
@@ -7828,26 +8523,38 @@ class EnhancedSelect extends HTMLElement {
7828
8523
  case 'Home':
7829
8524
  e.preventDefault();
7830
8525
  if (this._state.isOpen) {
8526
+ if (this._usesSelectedFirstVisualOrder()) {
8527
+ this._moveToVisualBoundary('first', { shiftKey: e.shiftKey, toggleKey: e.ctrlKey || e.metaKey });
8528
+ break;
8529
+ }
7831
8530
  const selectableIndices = this._getSelectableOptionIndices();
7832
8531
  const firstIndex = selectableIndices[0];
7833
8532
  if (firstIndex === undefined)
7834
8533
  break;
7835
8534
  this._setActive(firstIndex);
7836
8535
  if (this._config.selection.mode === 'multi' && e.shiftKey) {
7837
- this._selectRange(this._rangeAnchorIndex ?? firstIndex, firstIndex, { clear: !(e.ctrlKey || e.metaKey) });
8536
+ const targetKey = this._itemRegistry.indexToKey.get(firstIndex);
8537
+ if (targetKey !== undefined)
8538
+ this._selectKeyboardRange(this._rangeAnchorKey ?? targetKey, targetKey, { clear: !(e.ctrlKey || e.metaKey) });
7838
8539
  }
7839
8540
  }
7840
8541
  break;
7841
8542
  case 'End':
7842
8543
  e.preventDefault();
7843
8544
  if (this._state.isOpen) {
8545
+ if (this._usesSelectedFirstVisualOrder()) {
8546
+ this._moveToVisualBoundary('last', { shiftKey: e.shiftKey, toggleKey: e.ctrlKey || e.metaKey });
8547
+ break;
8548
+ }
7844
8549
  const selectableIndices = this._getSelectableOptionIndices();
7845
8550
  const lastIndex = selectableIndices[selectableIndices.length - 1];
7846
8551
  if (lastIndex === undefined)
7847
8552
  break;
7848
8553
  this._setActive(lastIndex);
7849
8554
  if (this._config.selection.mode === 'multi' && e.shiftKey) {
7850
- this._selectRange(this._rangeAnchorIndex ?? lastIndex, lastIndex, { clear: !(e.ctrlKey || e.metaKey) });
8555
+ const targetKey = this._itemRegistry.indexToKey.get(lastIndex);
8556
+ if (targetKey !== undefined)
8557
+ this._selectKeyboardRange(this._rangeAnchorKey ?? targetKey, targetKey, { clear: !(e.ctrlKey || e.metaKey) });
7851
8558
  }
7852
8559
  }
7853
8560
  break;
@@ -7902,6 +8609,26 @@ class EnhancedSelect extends HTMLElement {
7902
8609
  }
7903
8610
  }
7904
8611
  _moveActive(delta, opts) {
8612
+ if (this._usesSelectedFirstVisualOrder()) {
8613
+ const model = this._getVisualNavigationModel();
8614
+ if (model.selectableKeys.length === 0)
8615
+ return;
8616
+ const activeKey = this._engine.state.activeKey;
8617
+ const currentPosition = activeKey === null ? undefined : model.selectablePositionByKey.get(activeKey);
8618
+ // Load-more is only requested after movement reaches the actual visual end.
8619
+ if (delta === 1 && currentPosition === model.selectableKeys.length - 1 && this._requestKeyboardLoadMore())
8620
+ return;
8621
+ const nextKey = resolveVisualMovement(model, activeKey, delta);
8622
+ if (nextKey === null)
8623
+ return;
8624
+ this._setActiveForVisualKey(nextKey);
8625
+ if (this._config.selection.mode === 'multi' && opts?.shiftKey) {
8626
+ const anchorKey = this._rangeAnchorKey ?? activeKey ?? nextKey;
8627
+ this._rangeAnchorKey = anchorKey;
8628
+ this._selectKeyboardRange(anchorKey, nextKey, { clear: !opts.toggleKey });
8629
+ }
8630
+ return;
8631
+ }
7905
8632
  const selectableIndices = this._getSelectableOptionIndices();
7906
8633
  if (selectableIndices.length === 0)
7907
8634
  return;
@@ -7923,14 +8650,90 @@ class EnhancedSelect extends HTMLElement {
7923
8650
  const next = selectableIndices[nextPosition];
7924
8651
  this._setActive(next);
7925
8652
  if (this._config.selection.mode === 'multi' && opts?.shiftKey) {
7926
- const anchor = this._rangeAnchorIndex ?? currentIndex;
7927
- const anchorIndex = anchor >= 0 ? anchor : next;
7928
- if (this._rangeAnchorIndex === null) {
7929
- this._rangeAnchorIndex = anchorIndex;
7930
- }
7931
- this._selectRange(anchorIndex, next, { clear: !opts?.toggleKey });
8653
+ const nextKey = this._itemRegistry.indexToKey.get(next);
8654
+ if (nextKey === undefined)
8655
+ return;
8656
+ const anchorKey = this._rangeAnchorKey ?? (currentIndex >= 0 ? this._itemRegistry.indexToKey.get(currentIndex) : undefined) ?? nextKey;
8657
+ this._rangeAnchorKey = anchorKey;
8658
+ this._selectKeyboardRange(anchorKey, nextKey, { clear: !opts?.toggleKey });
7932
8659
  }
7933
8660
  }
8661
+ _usesSelectedFirstVisualOrder() {
8662
+ return this._selectedOptionsConfigAtOpen.placement === 'selected-first';
8663
+ }
8664
+ _getVisualNavigationModel() {
8665
+ this._ensureRegistryCurrent();
8666
+ return createVisualNavigationModel(this._renderPlan.filteredKeys, (key) => {
8667
+ const record = this._itemRegistry.keyToRecord.get(key);
8668
+ if (!record || record.disabled)
8669
+ return false;
8670
+ const option = this._getOptionElementByIndex(record.index);
8671
+ return option?.getAttribute('aria-disabled') !== 'true';
8672
+ });
8673
+ }
8674
+ _setActiveForVisualKey(key, reason = 'keyboard', options = {}) {
8675
+ const sourceIndex = this._renderPlan.sourceIndexByKey.get(key)
8676
+ ?? this._itemRegistry.keyToIndex.get(key);
8677
+ if (sourceIndex === undefined)
8678
+ return;
8679
+ this._setActive(sourceIndex, reason, options);
8680
+ }
8681
+ _moveToVisualBoundary(boundary, opts) {
8682
+ const model = this._getVisualNavigationModel();
8683
+ const targetKey = resolveVisualBoundary(model, boundary);
8684
+ if (targetKey === null)
8685
+ return;
8686
+ const currentKey = this._engine.state.activeKey;
8687
+ this._setActiveForVisualKey(targetKey);
8688
+ if (this._config.selection.mode === 'multi' && opts?.shiftKey) {
8689
+ const anchorKey = this._rangeAnchorKey ?? currentKey ?? targetKey;
8690
+ this._rangeAnchorKey = anchorKey;
8691
+ this._selectKeyboardRange(anchorKey, targetKey, { clear: !opts.toggleKey });
8692
+ }
8693
+ }
8694
+ _selectKeyboardRange(anchorKey, targetKey, opts) {
8695
+ if (this._usesSelectedFirstVisualOrder()) {
8696
+ const model = this._getVisualNavigationModel();
8697
+ const resolvedAnchor = model.selectablePositionByKey.has(anchorKey) ? anchorKey : targetKey;
8698
+ this._rangeAnchorKey = resolvedAnchor;
8699
+ this._selectVisualRange(resolvedAnchor, targetKey, opts);
8700
+ return;
8701
+ }
8702
+ const start = this._itemRegistry.keyToIndex.get(anchorKey);
8703
+ const end = this._itemRegistry.keyToIndex.get(targetKey);
8704
+ if (start !== undefined && end !== undefined)
8705
+ this._selectRange(start, end, opts);
8706
+ }
8707
+ _selectVisualRange(anchorKey, targetKey, opts) {
8708
+ if (this._config.selection.mode !== 'multi')
8709
+ return;
8710
+ this._ensureRegistryCurrent();
8711
+ const model = this._getVisualNavigationModel();
8712
+ const rangeKeys = resolveVisualRange(model, anchorKey, targetKey);
8713
+ if (rangeKeys.length === 0)
8714
+ return;
8715
+ const selectedEntries = this._getSelectedEntries();
8716
+ const entries = opts?.clear
8717
+ ? selectedEntries.filter((entry) => !this._itemRegistry.keyToRecord.has(entry.key))
8718
+ : selectedEntries;
8719
+ for (const key of rangeKeys) {
8720
+ const record = this._itemRegistry.keyToRecord.get(key);
8721
+ if (!record || this._isOptionSelectionBlocked(record.item))
8722
+ continue;
8723
+ entries.push(record);
8724
+ }
8725
+ this._requestSelectionReplacement(entries, opts?.reason ?? 'keyboard', 'select visual range');
8726
+ this._renderOptions();
8727
+ this._updateInputDisplay();
8728
+ const target = this._itemRegistry.keyToRecord.get(targetKey);
8729
+ const selectDetail = target ? this._getSelectEventDetail(target) : null;
8730
+ if (selectDetail)
8731
+ this._emit('select', selectDetail);
8732
+ this._emitChange();
8733
+ this._announce(`${this._state.selectedIndices.size} items selected`);
8734
+ if (selectDetail)
8735
+ this._config.callbacks.onSelect?.(selectDetail);
8736
+ }
7934
8737
  /** Return true only when boundary navigation is held for an in-flight/new page. */
7935
8738
  _requestKeyboardLoadMore() {
7936
8739
  if (!this._state.isOpen
@@ -7958,7 +8761,7 @@ class EnhancedSelect extends HTMLElement {
7958
8761
  this._dispatchAcknowledgedActions(actions);
7959
8762
  return true;
7960
8763
  }
7961
- _setActive(index, reason = 'keyboard') {
8764
+ _setActive(index, reason = 'keyboard', options = {}) {
7962
8765
  this._ensureRegistryCurrent();
7963
8766
  const record = this._getRecordByIndex(index);
7964
8767
  let option = this._getOptionElementByIndex(index);
@@ -7969,8 +8772,10 @@ class EnhancedSelect extends HTMLElement {
7969
8772
  if (!record || record.disabled || !option || option.getAttribute('aria-disabled') === 'true') {
7970
8773
  return;
7971
8774
  }
7972
- if (reason === 'keyboard')
8775
+ if (reason === 'keyboard' || reason === 'search') {
7973
8776
  this._keyboardActiveChangeGeneration += 1;
8777
+ this._cancelOpenSelectedScroll();
8778
+ }
7974
8779
  const previousIndex = this._state.activeIndex;
7975
8780
  this._dispatchActiveKey(record.key, reason, 'set active');
7976
8781
  if (this._state.activeIndex !== index)
@@ -7997,8 +8802,7 @@ class EnhancedSelect extends HTMLElement {
7997
8802
  else {
7998
8803
  this._syncCustomOptionActiveClasses(option, true);
7999
8804
  }
8000
- if (typeof option.scrollIntoView === 'function') {
8001
- // Don't scroll wildly when just opening with pre-selections
8805
+ if (options.scroll !== false && typeof option.scrollIntoView === 'function') {
8002
8806
  option.scrollIntoView({ block: 'nearest', behavior: 'smooth' });
8003
8807
  }
8004
8808
  // Announce position for screen readers
@@ -8054,8 +8858,22 @@ class EnhancedSelect extends HTMLElement {
8054
8858
  this._typeTimeout = window.setTimeout(() => {
8055
8859
  this._typeBuffer = '';
8056
8860
  }, 500);
8057
- // Find first matching option
8861
+ // Type-ahead uses the displayed candidate order when a presentation projection is active.
8058
8862
  const getValue = this._config.serverSide.getLabelFromItem || ((item) => item?.label ?? String(item));
8863
+ if (this._usesSelectedFirstVisualOrder()) {
8864
+ const model = this._getVisualNavigationModel();
8865
+ const matchKey = model.selectableKeys.find((key) => {
8866
+ const record = this._itemRegistry.keyToRecord.get(key);
8867
+ return record !== undefined && getValue(record.item).toLowerCase().startsWith(this._typeBuffer);
8868
+ });
8869
+ if (matchKey !== undefined) {
8870
+ const sourceIndex = this._renderPlan.sourceIndexByKey.get(matchKey)
8871
+ ?? this._itemRegistry.keyToIndex.get(matchKey);
8872
+ if (sourceIndex !== undefined)
8873
+ this._setActive(sourceIndex, 'search');
8874
+ }
8875
+ return;
8876
+ }
8059
8877
  const matchIndex = this._state.loadedItems.findIndex((item) => getValue(item).toLowerCase().startsWith(this._typeBuffer));
8060
8878
  if (matchIndex >= 0) {
8061
8879
  this._setActive(matchIndex, 'search');
@@ -8124,6 +8942,17 @@ class EnhancedSelect extends HTMLElement {
8124
8942
  };
8125
8943
  }
8126
8944
  _setInitialActiveOption() {
8945
+ if (this._usesSelectedFirstVisualOrder()) {
8946
+ const model = this._getVisualNavigationModel();
8947
+ const selectedKey = model.selectableKeys.find((key) => this._engine.state.selectedKeys.has(key));
8948
+ if (selectedKey === undefined) {
8949
+ this._dispatchActiveKey(null, 'open', 'initial active option');
8950
+ return;
8951
+ }
8952
+ // Resolve via stable identity so the open-time projection remains authoritative.
8953
+ this._setActiveForVisualKey(selectedKey, 'open', { scroll: false });
8954
+ return;
8955
+ }
8127
8956
  const selectableIndices = this._getSelectableOptionIndices();
8128
8957
  const selected = Array.from(this._state.selectedIndices).sort((a, b) => a - b);
8129
8958
  // Opening an empty select must not implicitly assign an active descendant.
@@ -8133,7 +8962,9 @@ class EnhancedSelect extends HTMLElement {
8133
8962
  return;
8134
8963
  }
8135
8964
  const target = selected.find((index) => selectableIndices.includes(index)) ?? selectableIndices[0];
8136
- this._setActive(target, 'open');
8965
+ // Set logical active state and ARIA immediately. The open-time coordinator
8966
+ // owns any physical positioning after the dropdown's entrance settles.
8967
+ this._setActive(target, 'open', { scroll: false });
8137
8968
  }
8138
8969
  _announce(message) {
8139
8970
  const effects = computeAccessibilityEffects(deriveAccessibilityState(this._engine.state), {
@@ -8187,9 +9018,10 @@ class EnhancedSelect extends HTMLElement {
8187
9018
  const toggleKey = Boolean(opts?.toggleKey);
8188
9019
  const shiftKey = Boolean(opts?.shiftKey);
8189
9020
  if (shiftKey) {
8190
- const anchor = this._rangeAnchorIndex ?? index;
8191
- this._selectRange(anchor, index, { clear: !toggleKey, reason });
8192
- this._rangeAnchorIndex = anchor;
9021
+ const targetKey = record.key;
9022
+ const anchorKey = this._rangeAnchorKey ?? targetKey;
9023
+ this._selectKeyboardRange(anchorKey, targetKey, { clear: !toggleKey, reason });
9024
+ this._rangeAnchorKey = anchorKey;
8193
9025
  return;
8194
9026
  }
8195
9027
  // Multi select with toggle
@@ -8203,7 +9035,7 @@ class EnhancedSelect extends HTMLElement {
8203
9035
  // Re-render to update styles (safer than trying to find the element in filtered list)
8204
9036
  this._renderOptions();
8205
9037
  }
8206
- this._rangeAnchorIndex = index;
9038
+ this._rangeAnchorKey = record.key;
8207
9039
  this._updateInputDisplay();
8208
9040
  const selectDetail = this._getSelectEventDetail(record);
8209
9041
  this._emit('select', selectDetail);
@@ -8462,58 +9294,71 @@ class EnhancedSelect extends HTMLElement {
8462
9294
  this._optionsContainer.style.transition = 'opacity 0.2s ease-in';
8463
9295
  }, 150);
8464
9296
  }
8465
- _scrollToSelected() {
8466
- if (this._state.selectedIndices.size === 0)
8467
- return;
8468
- const target = this._config.scrollToSelected.multiSelectTarget;
8469
- const indices = Array.from(this._state.selectedIndices).filter((index) => index >= 0).sort((a, b) => a - b);
8470
- if (indices.length === 0)
8471
- return;
8472
- // For multi-select, find the closest selected item to the current scroll position
8473
- let targetIndex;
8474
- if (this._config.selection.mode === 'multi' && indices.length > 1) {
8475
- // Calculate which selected item is closest to the center of the viewport
8476
- const dropdownRect = this._dropdown.getBoundingClientRect();
8477
- const viewportCenter = this._dropdown.scrollTop + (dropdownRect.height / 2);
8478
- // Find the selected item closest to viewport center
8479
- let closestIndex = indices[0];
8480
- let closestDistance = Infinity;
8481
- for (const index of indices) {
8482
- const option = this._getOptionElementByIndex(index);
8483
- if (option) {
8484
- const optionTop = option.offsetTop;
8485
- const distance = Math.abs(optionTop - viewportCenter);
8486
- if (distance < closestDistance) {
8487
- closestDistance = distance;
8488
- closestIndex = index;
8489
- }
8490
- }
8491
- }
8492
- targetIndex = closestIndex;
8493
- }
8494
- else {
8495
- // For single select or only one selected item, use the configured target
8496
- targetIndex = target === 'first' ? indices[0] : indices[indices.length - 1];
8497
- }
8498
- // Find and scroll to the target option
9297
+ _scrollToSelected(options = {}) {
9298
+ const config = options.config ?? this._config.scrollToSelected;
9299
+ if (!config.enabled)
9300
+ return;
9301
+ const targetKey = resolveSelectedTargetKey(this._renderPlan.filteredKeys, this._engine.state.selectedKeys, config.multiSelectTarget);
9302
+ if (targetKey === null)
9303
+ return;
9304
+ const targetIndex = this._renderPlan.sourceIndexByKey.get(targetKey)
9305
+ ?? this._itemRegistry.keyToIndex.get(targetKey);
9306
+ if (targetIndex === undefined)
9307
+ return;
9308
+ // Resolve against the current eligible render plan first. A selected key
9309
+ // outside the filtered projection must never trigger materialization.
8499
9310
  let option = this._getOptionElementByIndex(targetIndex);
8500
9311
  if (!option && this._guardedVirtualizer) {
8501
- const targetKey = this._itemRegistry.indexToKey.get(targetIndex);
8502
- if (targetKey !== undefined) {
8503
- this._materializeGuardedVirtualKey(targetKey);
8504
- option = this._getOptionElementByIndex(targetIndex);
8505
- }
9312
+ this._materializeGuardedVirtualKey(targetKey);
9313
+ option = this._getOptionElementByIndex(targetIndex);
8506
9314
  }
8507
9315
  if (option) {
8508
- // Use smooth scrolling with center alignment for better UX
8509
- if (typeof option.scrollIntoView === 'function') {
8510
- option.scrollIntoView({
8511
- block: this._config.scrollToSelected.block || 'center',
8512
- behavior: 'smooth',
8513
- });
9316
+ const reducedMotion = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches ?? false;
9317
+ this._scrollOptionWithinOptionsContainer(option, config.block || 'nearest', reducedMotion && config.behavior === 'smooth' ? 'auto' : (config.behavior || 'smooth'), options.onlyIfNeeded === true);
9318
+ if (options.setActive !== false) {
9319
+ // Active/ARIA synchronization must not start a second physical scroll.
9320
+ this._setActive(targetIndex, 'programmatic', { scroll: false });
8514
9321
  }
8515
- // Also set it as active for keyboard navigation
8516
- this._setActive(targetIndex, 'programmatic');
9322
+ }
9323
+ }
9324
+ _scrollOptionWithinOptionsContainer(option, block, behavior, onlyIfNeeded) {
9325
+ const scroller = this._optionsContainer;
9326
+ const scrollerRect = scroller.getBoundingClientRect();
9327
+ const viewportTop = scrollerRect.top + scroller.clientTop;
9328
+ const viewportBottom = viewportTop + scroller.clientHeight;
9329
+ const optionRect = option.getBoundingClientRect();
9330
+ if (onlyIfNeeded && optionRect.top >= viewportTop && optionRect.bottom <= viewportBottom)
9331
+ return;
9332
+ if (scroller.clientHeight <= 0 || optionRect.height <= 0)
9333
+ return;
9334
+ let targetScrollTop = scroller.scrollTop;
9335
+ if (block === 'start') {
9336
+ targetScrollTop += optionRect.top - viewportTop;
9337
+ }
9338
+ else if (block === 'center') {
9339
+ targetScrollTop += (optionRect.top + optionRect.bottom - viewportTop - viewportBottom) / 2;
9340
+ }
9341
+ else if (block === 'end') {
9342
+ targetScrollTop += optionRect.bottom - viewportBottom;
9343
+ }
9344
+ else if (optionRect.top < viewportTop) {
9345
+ targetScrollTop += optionRect.top - viewportTop;
9346
+ }
9347
+ else if (optionRect.bottom > viewportBottom) {
9348
+ targetScrollTop += optionRect.bottom - viewportBottom;
9349
+ }
9350
+ else {
9351
+ return;
9352
+ }
9353
+ const maxScrollTop = Math.max(0, scroller.scrollHeight - scroller.clientHeight);
9354
+ targetScrollTop = Math.max(0, Math.min(targetScrollTop, maxScrollTop));
9355
+ if (Math.abs(targetScrollTop - scroller.scrollTop) < 1)
9356
+ return;
9357
+ if (typeof scroller.scrollTo === 'function') {
9358
+ scroller.scrollTo({ top: targetScrollTop, behavior });
9359
+ }
9360
+ else {
9361
+ scroller.scrollTop = targetScrollTop;
8517
9362
  }
8518
9363
  }
8519
9364
  async _loadMoreItems(trigger = 'manual') {
@@ -8963,6 +9808,13 @@ class EnhancedSelect extends HTMLElement {
8963
9808
  * Clear search query and restore full option list
8964
9809
  */
8965
9810
  clearSearch() {
9811
+ if (this._dataLoadingConfig.protocol === 'acknowledged'
9812
+ && (this._dataLoadingConfig.searchMode === 'remote' || this._dataLoadingConfig.searchMode === 'hybrid')
9813
+ && this._dataRequestCoordinator) {
9814
+ this._input.value = '';
9815
+ this._handleSearch('');
9816
+ return;
9817
+ }
8966
9818
  this._state.searchQuery = '';
8967
9819
  if (this._config.searchable) {
8968
9820
  this._input.value = '';
@@ -8992,9 +9844,21 @@ class EnhancedSelect extends HTMLElement {
8992
9844
  this._invalidateGuardedMeasurements();
8993
9845
  const previousMode = this._config.selection.mode;
8994
9846
  const previousEnabled = this._config.enabled;
9847
+ const previousOpenScrollEnabled = this._config.scrollToSelected.enabled;
8995
9848
  const previousDataLoadingConfig = this._dataLoadingConfig;
8996
- const { dataLoading, callbacks, ...legacyConfig } = config;
9849
+ let searchEligibilityBecameInactive = false;
9850
+ const { dataLoading, callbacks, selectedOptions, scrollToSelected, ...legacyConfig } = config;
8997
9851
  const legacyUpdate = { ...legacyConfig };
9852
+ if (selectedOptions !== undefined) {
9853
+ const validation = validateSelectedOptionsConfig(selectedOptions);
9854
+ if (validation.valid)
9855
+ legacyUpdate.selectedOptions = validation.value;
9856
+ }
9857
+ if (scrollToSelected !== undefined) {
9858
+ const validation = validateScrollToSelectedConfig(scrollToSelected);
9859
+ if (validation.valid)
9860
+ legacyUpdate.scrollToSelected = validation.value;
9861
+ }
8998
9862
  let configErrorDetail;
8999
9863
  if (callbacks !== undefined && callbacks !== null) {
9000
9864
  const callbackInput = callbacks;
@@ -9014,6 +9878,10 @@ class EnhancedSelect extends HTMLElement {
9014
9878
  legacyUpdate.callbacks = legacyCallbacks;
9015
9879
  }
9016
9880
  this._config = this._mergeConfig(this._config, legacyUpdate);
9881
+ if (previousOpenScrollEnabled && !this._config.scrollToSelected.enabled) {
9882
+ this._openOptionsViewportAnchor = null;
9883
+ this._cancelOpenSelectedScroll();
9884
+ }
9017
9885
  if (dataLoading !== undefined) {
9018
9886
  const dataLoadingPrototype = dataLoading !== null && typeof dataLoading === 'object'
9019
9887
  ? Object.getPrototypeOf(dataLoading)
@@ -9023,6 +9891,13 @@ class EnhancedSelect extends HTMLElement {
9023
9891
  : dataLoading;
9024
9892
  const validation = validateDataLoadingConfig(candidate);
9025
9893
  if (validation.valid) {
9894
+ const wasRemoteEligible = previousDataLoadingConfig.protocol === 'acknowledged'
9895
+ && (previousDataLoadingConfig.searchMode === 'remote' || previousDataLoadingConfig.searchMode === 'hybrid')
9896
+ && Array.from(this._state.searchQuery.trim()).length >= previousDataLoadingConfig.minSearchCharacters;
9897
+ const becomesRemoteEligible = validation.value.protocol === 'acknowledged'
9898
+ && (validation.value.searchMode === 'remote' || validation.value.searchMode === 'hybrid')
9899
+ && Array.from(this._state.searchQuery.trim()).length >= validation.value.minSearchCharacters;
9900
+ searchEligibilityBecameInactive = wasRemoteEligible && !becomesRemoteEligible;
9026
9901
  this._dataLoadingConfig = validation.value;
9027
9902
  this._hasLastInvalidDataLoadingCandidate = false;
9028
9903
  this._lastInvalidDataLoadingCandidate = undefined;
@@ -9110,6 +9985,8 @@ class EnhancedSelect extends HTMLElement {
9110
9985
  const acknowledgedModeChanged = previousDataLoadingConfig.protocol !== this._dataLoadingConfig.protocol
9111
9986
  || previousDataLoadingConfig.searchMode !== this._dataLoadingConfig.searchMode
9112
9987
  || previousDataLoadingConfig.paginationMode !== this._dataLoadingConfig.paginationMode;
9988
+ if (searchEligibilityBecameInactive)
9989
+ this._cancelBusyPresentation();
9113
9990
  if (coordinator && switchesToLegacy) {
9114
9991
  if (this._acknowledgedReady && !this._acknowledgedProjectionPending && !this._acknowledgedProjectionSettling) {
9115
9992
  const update = coordinator.updateConfig(this._createCoordinatorConfig());
@@ -9144,8 +10021,14 @@ class EnhancedSelect extends HTMLElement {
9144
10021
  this._state.isBusy = snapshot.busy;
9145
10022
  this._state.isSearching = snapshot.activeRequest?.kind === 'search';
9146
10023
  this._syncListboxAccessibility();
9147
- if (update.actions.every((action) => action.type !== 'request'))
9148
- this._renderOptions();
10024
+ if (update.actions.every((action) => action.type !== 'request')) {
10025
+ if (this._acknowledgedSnapshotDiffersFromLoadedItems(snapshot)) {
10026
+ this._reconcileAcknowledgedSnapshot(snapshot);
10027
+ }
10028
+ else {
10029
+ this._renderOptions();
10030
+ }
10031
+ }
9149
10032
  }
9150
10033
  }
9151
10034
  }
@@ -9304,14 +10187,12 @@ class EnhancedSelect extends HTMLElement {
9304
10187
  }
9305
10188
  _ensureDataRequestCoordinator() {
9306
10189
  if (!this._dataRequestCoordinator) {
9307
- const isRemote = this._dataLoadingConfig.searchMode === 'remote'
9308
- || this._dataLoadingConfig.searchMode === 'hybrid';
9309
10190
  try {
9310
10191
  this._dataRequestCoordinator = new DataRequestCoordinator({
9311
10192
  config: this._createCoordinatorConfig(),
9312
10193
  initialQuery: this._state.searchQuery,
9313
10194
  initialItems: this._state.loadedItems,
9314
- hasMore: !isRemote && (this._config.infiniteScroll.enabled || this._config.loadMore.enabled),
10195
+ hasMore: this._config.infiniteScroll.enabled || this._config.loadMore.enabled,
9315
10196
  });
9316
10197
  }
9317
10198
  catch (error) {
@@ -9547,19 +10428,39 @@ class EnhancedSelect extends HTMLElement {
9547
10428
  activeKey: this._engine.state.activeKey,
9548
10429
  };
9549
10430
  }
9550
- _createLegacyRenderPlan(filteredIndices) {
9551
- const indices = [...filteredIndices];
9552
- const filteredKeys = indices
9553
- .map((index) => this._itemRegistry.indexToKey.get(index))
9554
- .filter((key) => key !== undefined);
9555
- const filteredIndexByKey = new Map();
9556
- filteredKeys.forEach((key, filteredIndex) => filteredIndexByKey.set(key, filteredIndex));
10431
+ _createLegacyRenderPlan(filteredIndices, groupedPresentation = []) {
10432
+ const sourceIndices = [...filteredIndices];
10433
+ const sourceOrderedKeys = groupedPresentation.length > 0
10434
+ ? groupedPresentation.flatMap((group) => group.orderedKeys)
10435
+ : sourceIndices
10436
+ .map((index) => this._itemRegistry.indexToKey.get(index))
10437
+ .filter((key) => key !== undefined);
10438
+ const shouldProjectSelectedFirst = this._usesSelectedFirstVisualOrder()
10439
+ && groupedPresentation.length === 0;
10440
+ const selectedKeys = this._selectedOptionsSelectionAtOpen ?? this._engine.state.selectedKeys;
10441
+ const filteredKeys = shouldProjectSelectedFirst
10442
+ ? projectSelectedOptionKeys(sourceOrderedKeys, selectedKeys)
10443
+ : sourceOrderedKeys;
10444
+ const indices = filteredKeys
10445
+ .map((key) => this._itemRegistry.keyToIndex.get(key))
10446
+ .filter((index) => index !== undefined);
10447
+ const displayIndexByKey = new Map();
10448
+ const sourceIndexByKey = new Map();
10449
+ filteredKeys.forEach((key, displayIndex) => {
10450
+ displayIndexByKey.set(key, displayIndex);
10451
+ const sourceIndex = this._itemRegistry.keyToIndex.get(key);
10452
+ if (sourceIndex !== undefined)
10453
+ sourceIndexByKey.set(key, sourceIndex);
10454
+ });
9557
10455
  return {
9558
10456
  mode: 'legacy-full',
9559
10457
  filteredIndices: indices,
9560
10458
  filteredKeys,
9561
10459
  intendedRenderKeys: filteredKeys.slice(),
9562
- filteredIndexByKey,
10460
+ displayIndexByKey,
10461
+ sourceIndexByKey,
10462
+ filteredIndexByKey: displayIndexByKey,
10463
+ groupedPresentation,
9563
10464
  };
9564
10465
  }
9565
10466
  _createVirtualRenderPlan(startIndex, endIndex) {
@@ -9568,12 +10469,16 @@ class EnhancedSelect extends HTMLElement {
9568
10469
  const filteredIndices = intendedRenderKeys
9569
10470
  .map((key) => this._itemRegistry.keyToIndex.get(key))
9570
10471
  .filter((index) => index !== undefined);
10472
+ const displayIndexByKey = new Map(this._renderPlan.displayIndexByKey);
9571
10473
  return {
9572
10474
  mode: 'virtual-window',
9573
10475
  filteredIndices,
9574
10476
  filteredKeys,
9575
10477
  intendedRenderKeys,
9576
- filteredIndexByKey: new Map(this._renderPlan.filteredIndexByKey),
10478
+ displayIndexByKey,
10479
+ sourceIndexByKey: new Map(this._renderPlan.sourceIndexByKey),
10480
+ filteredIndexByKey: displayIndexByKey,
10481
+ groupedPresentation: this._renderPlan.groupedPresentation,
9577
10482
  };
9578
10483
  }
9579
10484
  _ensureGuardedVirtualizer(filteredKeys) {
@@ -9721,6 +10626,7 @@ class EnhancedSelect extends HTMLElement {
9721
10626
  searchMode: dataLoading?.searchMode ?? 'local',
9722
10627
  paginationMode: dataLoading?.paginationMode ?? 'page',
9723
10628
  firstPage: dataLoading?.firstPage ?? 1,
10629
+ minSearchCharacters: dataLoading?.minSearchCharacters ?? 0,
9724
10630
  ...(dataLoading?.fetchLimit === undefined ? {} : { fetchLimit: dataLoading.fetchLimit }),
9725
10631
  };
9726
10632
  this._acknowledgedSearchMode = config.dataLoading?.searchMode ?? 'local';
@@ -9775,6 +10681,12 @@ class EnhancedSelect extends HTMLElement {
9775
10681
  for (const action of actions) {
9776
10682
  if (action.type === 'cancel') {
9777
10683
  this._cancelBusyPresentation();
10684
+ const snapshot = this._dataRequestCoordinator?.getSnapshot();
10685
+ if (snapshot) {
10686
+ this._state.isBusy = snapshot.busy || this._acknowledgedProjectionPending;
10687
+ this._state.isSearching = snapshot.activeRequest?.kind === 'search';
10688
+ this._syncListboxAccessibility();
10689
+ }
9778
10690
  this._dispatchAcknowledgedEvent('dataRequestCancel', action.notification);
9779
10691
  try {
9780
10692
  this._dataRequestCancelCallback?.(action.notification);
@@ -9860,6 +10772,34 @@ class EnhancedSelect extends HTMLElement {
9860
10772
  return Promise.resolve();
9861
10773
  return this._projectAcknowledgedSnapshot(this._dataRequestCoordinator.getSnapshot(), this._acknowledgedProjectionRequest ?? this._acknowledgedLastRequest, this._acknowledgedProjectionCommitsPosition);
9862
10774
  }
10775
+ _acknowledgedSnapshotDiffersFromLoadedItems(snapshot) {
10776
+ const loadedItems = this._state.loadedItems;
10777
+ return loadedItems.length !== snapshot.items.length
10778
+ || loadedItems.some((item, index) => item !== snapshot.items[index]);
10779
+ }
10780
+ _reconcileAcknowledgedSnapshot(snapshot) {
10781
+ if (!this._acknowledgedSnapshotDiffersFromLoadedItems(snapshot))
10782
+ return;
10783
+ const activeProjection = this._acknowledgedProjectionTask;
10784
+ if (this._acknowledgedProjectionRunning && activeProjection) {
10785
+ // Deferred config is reconciled from inside the current projection's
10786
+ // settlement callback. Wait until that task releases its running guard,
10787
+ // then project the coordinator's latest accepted snapshot.
10788
+ void activeProjection.then(() => {
10789
+ if (!this.isConnected)
10790
+ return;
10791
+ const latestSnapshot = this._dataRequestCoordinator?.getSnapshot() ?? snapshot;
10792
+ if (this._acknowledgedSnapshotDiffersFromLoadedItems(latestSnapshot)) {
10793
+ void this._projectAcknowledgedSnapshot(latestSnapshot, null, false);
10794
+ }
10795
+ else {
10796
+ this._dispatchPendingAcknowledgedSearchIntent();
10797
+ }
10798
+ });
10799
+ return;
10800
+ }
10801
+ void this._projectAcknowledgedSnapshot(snapshot, null, false);
10802
+ }
9863
10803
  _projectAcknowledgedSnapshot(snapshot, request, commitPosition) {
9864
10804
  if (this._acknowledgedProjectionRunning) {
9865
10805
  return this._acknowledgedProjectionTask ?? Promise.resolve();
@@ -9916,7 +10856,10 @@ class EnhancedSelect extends HTMLElement {
9916
10856
  }
9917
10857
  if (!this._state.searchQuery
9918
10858
  && this._acknowledgedPendingSearchQuery === null
9919
- && !this._isActivelyEditingSearchInput()) {
10859
+ && !this._isActivelyEditingSearchInput()
10860
+ && !(this._dataLoadingConfig.protocol === 'acknowledged'
10861
+ && (this._dataLoadingConfig.searchMode === 'remote' || this._dataLoadingConfig.searchMode === 'hybrid')
10862
+ && this._dataLoadingConfig.minSearchCharacters > 0)) {
9920
10863
  this._updateInputDisplay();
9921
10864
  }
9922
10865
  this._syncListboxAccessibility();
@@ -10079,6 +11022,11 @@ class EnhancedSelect extends HTMLElement {
10079
11022
  this._state.isBusy = state.busy;
10080
11023
  this._state.isSearching = state.activeRequest?.kind === 'search';
10081
11024
  this._syncListboxAccessibility();
11025
+ if (update.actions.every((action) => action.type !== 'request')
11026
+ && this._acknowledgedSnapshotDiffersFromLoadedItems(state)) {
11027
+ this._reconcileAcknowledgedSnapshot(state);
11028
+ return;
11029
+ }
10082
11030
  }
10083
11031
  this._dispatchPendingAcknowledgedSearchIntent();
10084
11032
  }
@@ -10484,11 +11432,31 @@ class EnhancedSelect extends HTMLElement {
10484
11432
  // Handle Grouped Items Rendering (when no search query)
10485
11433
  if (this._state.groupedItems.length > 0 && !query) {
10486
11434
  this._destroyGuardedVirtualizer();
10487
- this._renderPlan = this._createLegacyRenderPlan(this._itemRegistry.records.map((record) => record.index));
11435
+ const groupedSource = this._state.groupedItems.map((group, groupIndex) => ({
11436
+ group,
11437
+ groupIndex,
11438
+ orderedKeys: group.options
11439
+ .map((item) => this._state.loadedItems.indexOf(item))
11440
+ .filter((index) => index >= 0)
11441
+ .map((index) => this._itemRegistry.indexToKey.get(index))
11442
+ .filter((key) => key !== undefined),
11443
+ }));
11444
+ const groupedOrder = this._usesSelectedFirstVisualOrder()
11445
+ ? projectSelectedOptionGroups(groupedSource.map(({ groupIndex, orderedKeys }) => ({ groupIdentity: groupIndex, orderedKeys })), this._selectedOptionsSelectionAtOpen ?? this._engine.state.selectedKeys)
11446
+ : groupedSource.map(({ groupIndex, orderedKeys }) => ({ groupIdentity: groupIndex, orderedKeys }));
11447
+ const groupedPresentation = groupedOrder.map(({ groupIdentity, orderedKeys }) => ({
11448
+ group: this._state.groupedItems[groupIdentity],
11449
+ groupIndex: groupIdentity,
11450
+ orderedKeys,
11451
+ }));
11452
+ const groupedIndices = groupedPresentation.flatMap(({ orderedKeys }) => orderedKeys
11453
+ .map((key) => this._itemRegistry.keyToIndex.get(key))
11454
+ .filter((index) => index !== undefined));
11455
+ this._renderPlan = this._createLegacyRenderPlan(groupedIndices, groupedPresentation);
10488
11456
  filteredIndicesForScope = this._renderPlan.filteredIndices;
10489
11457
  this._registerShadowItems(filteredIndicesForScope);
10490
11458
  this._refreshVirtualizationScope(filteredIndicesForScope);
10491
- this._state.groupedItems.forEach((group, groupIndex) => {
11459
+ this._renderPlan.groupedPresentation.forEach(({ group, groupIndex, orderedKeys }) => {
10492
11460
  let header;
10493
11461
  if (this.groupHeaderRenderer) {
10494
11462
  header = this.groupHeaderRenderer(group, groupIndex);
@@ -10514,10 +11482,10 @@ class EnhancedSelect extends HTMLElement {
10514
11482
  }
10515
11483
  header.setAttribute('part', 'group-header');
10516
11484
  this._optionsContainer.appendChild(header);
10517
- group.options.forEach(item => {
10518
- // Find original index for correct ID generation and selection
10519
- const index = this._state.loadedItems.indexOf(item);
10520
- if (index !== -1) {
11485
+ orderedKeys.forEach((key) => {
11486
+ const index = this._itemRegistry.keyToIndex.get(key);
11487
+ if (index !== undefined) {
11488
+ const item = this._state.loadedItems[index];
10521
11489
  this._renderSingleOption(item, index, getValue, getLabel);
10522
11490
  }
10523
11491
  });
@@ -10586,13 +11554,16 @@ class EnhancedSelect extends HTMLElement {
10586
11554
  const chunkSize = 80;
10587
11555
  let cursor = 0;
10588
11556
  let maxRenderTarget = 0;
10589
- if (this._state.selectedIndices.size > 0 && this._config.scrollToSelected.enabled) {
10590
- const indices = Array.from(this._state.selectedIndices).filter((index) => index >= 0).sort((a, b) => a - b);
10591
- const targetIndex = this._config.scrollToSelected.multiSelectTarget === 'first' ? indices[0] : indices[indices.length - 1];
10592
- const filteredPos = filteredIndices.indexOf(targetIndex);
10593
- if (filteredPos !== -1) {
10594
- maxRenderTarget = filteredPos + 20; // Ensure we render up to the selection
10595
- }
11557
+ if (this._state.isOpen
11558
+ && this._config.scrollToSelected.enabled
11559
+ && this._scrollToSelectedConfigAtOpen.enabled
11560
+ && this._scrollToSelectedConfigAtOpen.onOpen !== 'preserve') {
11561
+ const targetKey = resolveSelectedTargetKey(this._renderPlan.filteredKeys, this._engine.state.selectedKeys, this._scrollToSelectedConfigAtOpen.multiSelectTarget);
11562
+ const targetPosition = targetKey === null
11563
+ ? undefined
11564
+ : this._renderPlan.displayIndexByKey.get(targetKey);
11565
+ if (targetPosition !== undefined)
11566
+ maxRenderTarget = targetPosition + 20;
10596
11567
  }
10597
11568
  const renderChunk = () => {
10598
11569
  if (renderCycleId !== this._renderCycleId) {
@@ -12102,6 +13073,9 @@ exports.shadowDOMStyles = shadowDOMStyles;
12102
13073
  exports.toggleClass = toggleClass;
12103
13074
  exports.transition = transition;
12104
13075
  exports.validateDataLoadingConfig = validateDataLoadingConfig;
13076
+ exports.validateScrollToSelectedConfig = validateScrollToSelectedConfig;
13077
+ exports.validateSelectedOptionsConfig = validateSelectedOptionsConfig;
13078
+ exports.validateSelectedOptionsConfigUpdate = validateSelectedOptionsConfigUpdate;
12105
13079
  exports.validateTemplate = validateTemplate;
12106
13080
  exports.valuesEqual = valuesEqual;
12107
13081
  exports.warnCSPViolation = warnCSPViolation;