@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.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
@@ -2256,6 +2379,7 @@ const DEFAULT_CONFIG = {
2256
2379
  searchMode: 'local',
2257
2380
  paginationMode: 'page',
2258
2381
  firstPage: 1,
2382
+ minSearchCharacters: 0,
2259
2383
  };
2260
2384
  const ALLOWED_FIELDS = new Set([
2261
2385
  'protocol',
@@ -2263,6 +2387,7 @@ const ALLOWED_FIELDS = new Set([
2263
2387
  'paginationMode',
2264
2388
  'firstPage',
2265
2389
  'fetchLimit',
2390
+ 'minSearchCharacters',
2266
2391
  ]);
2267
2392
  function issue(path, code, message) {
2268
2393
  return { path, code, message };
@@ -2285,6 +2410,18 @@ function validatePositiveSafeInteger(candidate, key, issues) {
2285
2410
  issues.push(issue(key, 'invalid-positive-integer', `${key} must be a positive safe integer.`));
2286
2411
  }
2287
2412
  }
2413
+ function validateNonNegativeSafeInteger(candidate, issues) {
2414
+ const value = candidate.minSearchCharacters;
2415
+ if (value === undefined)
2416
+ return;
2417
+ if (typeof value !== 'number') {
2418
+ issues.push(issue('minSearchCharacters', 'invalid-type', 'minSearchCharacters must be a number.'));
2419
+ return;
2420
+ }
2421
+ if (!Number.isSafeInteger(value) || value < 0) {
2422
+ issues.push(issue('minSearchCharacters', 'invalid-value', 'minSearchCharacters must be a non-negative safe integer.'));
2423
+ }
2424
+ }
2288
2425
  /** Validate a complete effective per-instance data-loading configuration. */
2289
2426
  function validateDataLoadingConfig(candidate) {
2290
2427
  if (!isRecord$1(candidate)) {
@@ -2323,6 +2460,7 @@ function validateDataLoadingConfig(candidate) {
2323
2460
  }
2324
2461
  validatePositiveSafeInteger(candidate, 'firstPage', issues);
2325
2462
  validatePositiveSafeInteger(candidate, 'fetchLimit', issues);
2463
+ validateNonNegativeSafeInteger(candidate, issues);
2326
2464
  if (protocol === 'legacy' && (searchMode === 'remote' || searchMode === 'hybrid')) {
2327
2465
  issues.push(issue('searchMode', 'requires-acknowledged-protocol', 'Remote and hybrid search require the acknowledged protocol.'));
2328
2466
  }
@@ -2336,6 +2474,9 @@ function validateDataLoadingConfig(candidate) {
2336
2474
  searchMode: searchMode,
2337
2475
  paginationMode: paginationMode,
2338
2476
  firstPage: candidate.firstPage === undefined ? DEFAULT_CONFIG.firstPage : candidate.firstPage,
2477
+ minSearchCharacters: candidate.minSearchCharacters === undefined
2478
+ ? DEFAULT_CONFIG.minSearchCharacters
2479
+ : candidate.minSearchCharacters,
2339
2480
  ...(candidate.fetchLimit === undefined ? {} : { fetchLimit: candidate.fetchLimit }),
2340
2481
  };
2341
2482
  return { valid: true, value: resolved };
@@ -3139,6 +3280,94 @@ function arraysEqualByValue(a, b) {
3139
3280
  return true;
3140
3281
  }
3141
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
+
3142
3371
  /**
3143
3372
  * DOM-independent coordinator for the opt-in acknowledged data-loading
3144
3373
  * protocol. This module is intentionally not re-exported from the package
@@ -3234,6 +3463,7 @@ function configInput(config = {}) {
3234
3463
  searchMode: dataLoading.searchMode === undefined ? 'local' : dataLoading.searchMode,
3235
3464
  paginationMode: dataLoading.paginationMode === undefined ? 'page' : dataLoading.paginationMode,
3236
3465
  firstPage: dataLoading.firstPage === undefined ? 1 : dataLoading.firstPage,
3466
+ minSearchCharacters: dataLoading.minSearchCharacters === undefined ? 0 : dataLoading.minSearchCharacters,
3237
3467
  initialPage: infiniteScroll.initialPage === undefined ? 1 : infiniteScroll.initialPage,
3238
3468
  fetchLimit: dataLoading.fetchLimit,
3239
3469
  maxCursorPages: dataLoading.maxCursorPages === undefined
@@ -3272,6 +3502,9 @@ function validateDataCoordinatorConfig(config = {}) {
3272
3502
  if (!isPositiveSafeInteger(input.firstPage)) {
3273
3503
  add('dataLoading.firstPage', 'must be a positive safe integer');
3274
3504
  }
3505
+ if (!isNonNegativeSafeInteger(input.minSearchCharacters)) {
3506
+ add('dataLoading.minSearchCharacters', 'must be a non-negative safe integer');
3507
+ }
3275
3508
  if (!isPositiveSafeInteger(input.initialPage)) {
3276
3509
  add('infiniteScroll.initialPage', 'must be a positive safe integer');
3277
3510
  }
@@ -3311,6 +3544,7 @@ function validateDataCoordinatorConfig(config = {}) {
3311
3544
  searchMode: input.searchMode,
3312
3545
  paginationMode: input.paginationMode,
3313
3546
  firstPage: input.firstPage,
3547
+ minSearchCharacters: input.minSearchCharacters,
3314
3548
  initialPage: input.initialPage,
3315
3549
  fetchLimit: resolvedFetchLimit,
3316
3550
  maxCursorPages: input.maxCursorPages,
@@ -3356,6 +3590,8 @@ class DataRequestCoordinator {
3356
3590
  this.resourceLimit = null;
3357
3591
  this.sentinelBlocked = false;
3358
3592
  this.sentinelIntersecting = false;
3593
+ /** Unfiltered items and continuation are independent from each filtered query. */
3594
+ this.browseState = null;
3359
3595
  const initialConfig = options.config === undefined ? {} : options.config;
3360
3596
  const validation = validateDataCoordinatorConfig(initialConfig);
3361
3597
  if (!validation.valid) {
@@ -3366,12 +3602,24 @@ class DataRequestCoordinator {
3366
3602
  this.query = options.initialQuery ?? '';
3367
3603
  this.items = asFrozenItems(options.initialItems ?? []);
3368
3604
  const remote = this.isRemoteMode();
3369
- this.hasMore = remote ? false : options.hasMore ?? false;
3605
+ const searchEligible = this.isSearchEligible(this.query);
3606
+ this.hasMore = options.hasMore ?? false;
3370
3607
  this.nextEligiblePosition = this.initialPosition();
3371
- this.lastCommittedPage = this.config.paginationMode === 'page' && !remote
3372
- ? this.config.initialPage
3608
+ this.lastCommittedPage = this.config.paginationMode === 'page'
3609
+ ? (remote && searchEligible
3610
+ ? undefined
3611
+ : this.items.length > 0 ? this.config.initialPage : undefined)
3373
3612
  : undefined;
3374
- this.needsInitialRemoteSearch = remote;
3613
+ this.needsInitialRemoteSearch = remote && searchEligible;
3614
+ if (remote && searchEligible) {
3615
+ const browse = this.captureDataState();
3616
+ browse.lastCommittedPage = this.config.paginationMode === 'page' && this.items.length > 0
3617
+ ? this.config.initialPage
3618
+ : undefined;
3619
+ browse.nextEligiblePosition = this.browseInitialPosition();
3620
+ browse.needsInitialRemoteSearch = false;
3621
+ this.browseState = browse;
3622
+ }
3375
3623
  }
3376
3624
  getSnapshot() {
3377
3625
  const activeRequest = this.active?.request ?? null;
@@ -3405,7 +3653,7 @@ class DataRequestCoordinator {
3405
3653
  this.queryGeneration += 1;
3406
3654
  this.connected = true;
3407
3655
  this.hasConnected = true;
3408
- if (this.isRemoteMode() && this.needsInitialRemoteSearch) {
3656
+ if (this.isSearchEligible(this.query) && this.needsInitialRemoteSearch) {
3409
3657
  this.resetPaginationForRemoteQuery(true);
3410
3658
  const request = this.createSearchRequest();
3411
3659
  if (request)
@@ -3428,34 +3676,62 @@ class DataRequestCoordinator {
3428
3676
  setQuery(query) {
3429
3677
  if (typeof query !== 'string' || query === this.query)
3430
3678
  return immutableActions([]);
3679
+ if (!this.isRemoteMode()) {
3680
+ const actions = [];
3681
+ const cancellation = this.invalidateActive('query-changed');
3682
+ if (cancellation)
3683
+ actions.push(cancellation);
3684
+ this.query = query;
3685
+ this.queryGeneration += 1;
3686
+ this.resetQueryMetadata();
3687
+ this.lastCommittedPage = this.config.paginationMode === 'page' && this.items.length > 0
3688
+ ? this.config.initialPage
3689
+ : undefined;
3690
+ this.nextEligiblePosition = this.initialPosition();
3691
+ this.needsInitialRemoteSearch = false;
3692
+ return immutableActions(actions);
3693
+ }
3431
3694
  const actions = [];
3432
- const cancellation = this.invalidateActive('query-changed');
3433
- if (cancellation)
3434
- actions.push(cancellation);
3695
+ const wasSearchEligible = this.isSearchEligible(this.query);
3696
+ const willSearchBeEligible = this.isSearchEligible(query);
3697
+ const activeKind = this.active?.request.kind;
3698
+ // Edits that remain below threshold are presentation-only while browsing.
3699
+ // Do not cancel a legitimate unfiltered loadMore operation for those edits.
3700
+ const preserveBrowseLoad = !wasSearchEligible && !willSearchBeEligible && activeKind === 'loadMore';
3701
+ const enteringSearch = !wasSearchEligible && willSearchBeEligible;
3702
+ if (enteringSearch || !preserveBrowseLoad) {
3703
+ const cancellation = this.invalidateActive('query-changed');
3704
+ if (cancellation)
3705
+ actions.push(cancellation);
3706
+ }
3707
+ if (enteringSearch)
3708
+ this.browseState = this.captureDataState();
3435
3709
  this.query = query;
3436
- this.queryGeneration += 1;
3437
- this.error = null;
3438
- this.status = 'idle';
3439
- this.generationHasAcceptedResult = false;
3440
- this.retryAvailable = false;
3441
- this.retryPosition = undefined;
3442
- this.retryKind = undefined;
3443
- this.committedCursors.clear();
3444
- this.resourceLimit = null;
3445
- this.sentinelBlocked = false;
3446
- if (this.isRemoteMode()) {
3447
- this.resetPaginationForRemoteQuery(true);
3448
- this.needsInitialRemoteSearch = true;
3449
- if (this.connected) {
3450
- const request = this.createSearchRequest();
3451
- if (request)
3452
- actions.push(Object.freeze({ type: 'request', request }));
3453
- }
3710
+ // Below-threshold edits do not change browse request ownership. Keep the
3711
+ // generation stable while an unfiltered loadMore is in flight so its valid
3712
+ // completion is not made stale by presentation-only input.
3713
+ if (!preserveBrowseLoad)
3714
+ this.queryGeneration += 1;
3715
+ if (!wasSearchEligible && !willSearchBeEligible) {
3716
+ this.error = null;
3717
+ if (!this.active)
3718
+ this.status = 'idle';
3719
+ // Current state remains the unfiltered browse state. Keep its pagination
3720
+ // and accepted items intact while the user edits a short query.
3721
+ return immutableActions(actions);
3454
3722
  }
3455
- else {
3456
- this.lastCommittedPage = this.config.paginationMode === 'page' ? this.config.initialPage : undefined;
3457
- this.nextEligiblePosition = this.initialPosition();
3723
+ if (wasSearchEligible && !willSearchBeEligible) {
3724
+ this.restoreBrowseState();
3458
3725
  this.needsInitialRemoteSearch = false;
3726
+ return immutableActions(actions);
3727
+ }
3728
+ this.resetQueryMetadata();
3729
+ this.resetPaginationForRemoteQuery(true);
3730
+ this.needsInitialRemoteSearch = true;
3731
+ if (this.connected) {
3732
+ const request = this.createSearchRequest();
3733
+ if (request)
3734
+ actions.push(Object.freeze({ type: 'request', request }));
3459
3735
  }
3460
3736
  return immutableActions(actions);
3461
3737
  }
@@ -3481,12 +3757,43 @@ class DataRequestCoordinator {
3481
3757
  const protocolChanged = previous.protocol !== next.protocol ||
3482
3758
  previous.searchMode !== next.searchMode ||
3483
3759
  previous.paginationMode !== next.paginationMode;
3760
+ const thresholdChanged = previous.minSearchCharacters !== next.minSearchCharacters;
3484
3761
  this.rawConfig = copyCoordinatorConfig(candidate);
3485
3762
  this.config = next;
3486
- if (!protocolChanged) {
3763
+ if (!protocolChanged && !thresholdChanged) {
3487
3764
  this.refreshCursorDepthLimit();
3488
3765
  return Object.freeze({ status: 'accepted', actions: immutableActions([]) });
3489
3766
  }
3767
+ if (!protocolChanged && thresholdChanged) {
3768
+ const wasEligible = this.isSearchEligible(this.query, previous);
3769
+ const willBeEligible = this.isSearchEligible(this.query, next);
3770
+ if (wasEligible === willBeEligible) {
3771
+ this.refreshCursorDepthLimit();
3772
+ return Object.freeze({ status: 'accepted', actions: immutableActions([]) });
3773
+ }
3774
+ const actions = [];
3775
+ const cancellation = this.invalidateActive('config-changed');
3776
+ if (cancellation)
3777
+ actions.push(cancellation);
3778
+ this.queryGeneration += 1;
3779
+ if (wasEligible && !willBeEligible) {
3780
+ this.resetQueryMetadata();
3781
+ this.restoreBrowseState();
3782
+ this.needsInitialRemoteSearch = false;
3783
+ }
3784
+ else {
3785
+ this.browseState = this.captureDataState();
3786
+ this.resetQueryMetadata();
3787
+ this.resetPaginationForRemoteQuery(true);
3788
+ this.needsInitialRemoteSearch = true;
3789
+ if (this.connected) {
3790
+ const request = this.createSearchRequest();
3791
+ if (request)
3792
+ actions.push(Object.freeze({ type: 'request', request }));
3793
+ }
3794
+ }
3795
+ return Object.freeze({ status: 'accepted', actions: immutableActions(actions) });
3796
+ }
3490
3797
  const actions = [];
3491
3798
  const cancellation = this.invalidateActive('config-changed');
3492
3799
  if (cancellation)
@@ -3502,12 +3809,13 @@ class DataRequestCoordinator {
3502
3809
  this.resourceLimit = null;
3503
3810
  this.sentinelBlocked = false;
3504
3811
  this.hasMore = this.isRemoteMode() ? false : this.hasMore;
3505
- this.lastCommittedPage = this.config.paginationMode === 'page' && !this.isRemoteMode()
3812
+ this.lastCommittedPage = this.config.paginationMode === 'page' && !this.isRemoteMode() && this.items.length > 0
3506
3813
  ? this.config.initialPage
3507
3814
  : undefined;
3508
3815
  this.nextEligiblePosition = this.initialPosition();
3509
3816
  this.needsInitialRemoteSearch = this.isRemoteMode();
3510
- if (this.connected && this.isRemoteMode()) {
3817
+ this.browseState = null;
3818
+ if (this.connected && this.isSearchEligible(this.query)) {
3511
3819
  const request = this.createSearchRequest();
3512
3820
  if (request)
3513
3821
  actions.push(Object.freeze({ type: 'request', request }));
@@ -3698,13 +4006,93 @@ class DataRequestCoordinator {
3698
4006
  isRemoteMode() {
3699
4007
  return this.config.searchMode === 'remote' || this.config.searchMode === 'hybrid';
3700
4008
  }
4009
+ isSearchEligible(query, config = this.config) {
4010
+ if (config.protocol !== 'acknowledged' ||
4011
+ (config.searchMode !== 'remote' && config.searchMode !== 'hybrid'))
4012
+ return true;
4013
+ return Array.from(query.trim()).length >= config.minSearchCharacters;
4014
+ }
4015
+ captureDataState() {
4016
+ return {
4017
+ items: this.items,
4018
+ hasMore: this.hasMore,
4019
+ status: this.status,
4020
+ lastCommittedPage: this.lastCommittedPage,
4021
+ nextEligiblePosition: this.nextEligiblePosition,
4022
+ committedCursors: new Set(this.committedCursors),
4023
+ generationHasAcceptedResult: this.generationHasAcceptedResult,
4024
+ needsInitialRemoteSearch: this.needsInitialRemoteSearch,
4025
+ retryAvailable: this.retryAvailable,
4026
+ retryPosition: this.retryPosition,
4027
+ retryKind: this.retryKind,
4028
+ error: this.error,
4029
+ resourceLimit: this.resourceLimit,
4030
+ sentinelBlocked: this.sentinelBlocked,
4031
+ };
4032
+ }
4033
+ restoreBrowseState() {
4034
+ if (this.browseState) {
4035
+ const state = this.browseState;
4036
+ this.items = state.items;
4037
+ this.hasMore = state.hasMore;
4038
+ this.status = state.status;
4039
+ this.lastCommittedPage = state.lastCommittedPage;
4040
+ this.nextEligiblePosition = state.nextEligiblePosition;
4041
+ this.committedCursors = new Set(state.committedCursors);
4042
+ this.generationHasAcceptedResult = state.generationHasAcceptedResult;
4043
+ this.needsInitialRemoteSearch = state.needsInitialRemoteSearch;
4044
+ this.retryAvailable = state.retryAvailable;
4045
+ this.retryPosition = state.retryPosition;
4046
+ this.retryKind = state.retryKind;
4047
+ this.error = state.error;
4048
+ this.resourceLimit = state.resourceLimit;
4049
+ this.sentinelBlocked = state.sentinelBlocked;
4050
+ this.browseState = null;
4051
+ return;
4052
+ }
4053
+ this.items = asFrozenItems([]);
4054
+ this.hasMore = false;
4055
+ this.status = 'idle';
4056
+ this.lastCommittedPage = undefined;
4057
+ this.nextEligiblePosition = this.browseInitialPosition();
4058
+ this.committedCursors.clear();
4059
+ this.generationHasAcceptedResult = false;
4060
+ this.retryAvailable = false;
4061
+ this.retryPosition = undefined;
4062
+ this.retryKind = undefined;
4063
+ this.error = null;
4064
+ this.resourceLimit = null;
4065
+ this.sentinelBlocked = false;
4066
+ }
4067
+ resetQueryMetadata() {
4068
+ this.error = null;
4069
+ this.status = 'idle';
4070
+ this.generationHasAcceptedResult = false;
4071
+ this.retryAvailable = false;
4072
+ this.retryPosition = undefined;
4073
+ this.retryKind = undefined;
4074
+ this.committedCursors.clear();
4075
+ this.resourceLimit = null;
4076
+ this.sentinelBlocked = false;
4077
+ }
3701
4078
  initialPosition() {
3702
4079
  if (this.config.paginationMode === 'cursor') {
3703
4080
  return Object.freeze({ mode: 'cursor', ordinal: 1 });
3704
4081
  }
3705
- const page = this.isRemoteMode() ? this.config.firstPage : this.config.initialPage + 1;
4082
+ const page = this.isRemoteMode() && this.isSearchEligible(this.query)
4083
+ ? this.config.firstPage
4084
+ : this.items.length > 0 ? this.config.initialPage + 1 : this.config.initialPage;
3706
4085
  return Object.freeze({ mode: 'page', page });
3707
4086
  }
4087
+ browseInitialPosition() {
4088
+ if (this.config.paginationMode === 'cursor') {
4089
+ return Object.freeze({ mode: 'cursor', ordinal: 1 });
4090
+ }
4091
+ return Object.freeze({
4092
+ mode: 'page',
4093
+ page: this.items.length > 0 ? this.config.initialPage + 1 : this.config.initialPage,
4094
+ });
4095
+ }
3708
4096
  resetPaginationForRemoteQuery(clearItems) {
3709
4097
  this.hasMore = false;
3710
4098
  this.lastCommittedPage = undefined;
@@ -3745,7 +4133,10 @@ class DataRequestCoordinator {
3745
4133
  }
3746
4134
  }
3747
4135
  createSearchRequest(position = this.nextEligiblePosition) {
3748
- if (!this.connected || !this.isRemoteMode() || this.config.protocol !== 'acknowledged')
4136
+ if (!this.connected
4137
+ || !this.isRemoteMode()
4138
+ || this.config.protocol !== 'acknowledged'
4139
+ || !this.isSearchEligible(this.query))
3749
4140
  return null;
3750
4141
  const request = this.createRequest({ kind: 'search', mode: this.config.searchMode }, position);
3751
4142
  if (request) {
@@ -3768,12 +4159,17 @@ class DataRequestCoordinator {
3768
4159
  return null;
3769
4160
  this.requestSequence += 1;
3770
4161
  const check = requestIdCheck(this.requestIdSecret, this.instanceId, this.queryGeneration, this.requestSequence);
4162
+ const requestQuery = kind.kind === 'loadMore'
4163
+ && this.isRemoteMode()
4164
+ && !this.isSearchEligible(this.query)
4165
+ ? ''
4166
+ : this.query;
3771
4167
  const requestId = `data-${this.instanceId}-generation-${this.queryGeneration}-request-${this.requestSequence}-${check}`;
3772
4168
  const base = Object.freeze({
3773
4169
  requestId,
3774
4170
  queryGeneration: this.queryGeneration,
3775
- query: this.query,
3776
- normalizedQuery: this.query.trim(),
4171
+ query: requestQuery,
4172
+ normalizedQuery: requestQuery.trim(),
3777
4173
  fetchLimit,
3778
4174
  position: frozenPosition(position),
3779
4175
  });
@@ -3943,8 +4339,11 @@ const LEGACY_DATA_LOADING_CONFIG = {
3943
4339
  searchMode: 'local',
3944
4340
  paginationMode: 'page',
3945
4341
  firstPage: 1,
4342
+ minSearchCharacters: 0,
3946
4343
  };
3947
- const DATA_LOADING_CONFIG_FIELDS = ['protocol', 'searchMode', 'paginationMode', 'firstPage', 'fetchLimit'];
4344
+ const DATA_LOADING_CONFIG_FIELDS = [
4345
+ 'protocol', 'searchMode', 'paginationMode', 'firstPage', 'fetchLimit', 'minSearchCharacters',
4346
+ ];
3948
4347
  const INVALID_OBJECT_VALUE = Object.freeze({ kind: 'object' });
3949
4348
  const INVALID_ARRAY_VALUE = Object.freeze({ kind: 'array' });
3950
4349
  const INVALID_FUNCTION_VALUE = Object.freeze({ kind: 'function' });
@@ -4063,8 +4462,27 @@ class EnhancedSelect extends HTMLElement {
4063
4462
  filteredIndices: [],
4064
4463
  filteredKeys: [],
4065
4464
  intendedRenderKeys: [],
4465
+ displayIndexByKey: new Map(),
4466
+ sourceIndexByKey: new Map(),
4066
4467
  filteredIndexByKey: new Map(),
4468
+ groupedPresentation: [],
4067
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',
4483
+ };
4484
+ this._closedOptionsViewportAnchor = null;
4485
+ this._openOptionsViewportAnchor = null;
4068
4486
  this._emptyStateContext = null;
4069
4487
  // Null keeps the public/default renderer on its legacy full path. This
4070
4488
  // private state is only used by guarded virtualization integration.
@@ -4121,7 +4539,7 @@ class EnhancedSelect extends HTMLElement {
4121
4539
  this._boundArrowClick = null;
4122
4540
  this._pendingFirstRenderMark = false;
4123
4541
  this._pendingSearchRenderMark = false;
4124
- this._rangeAnchorIndex = null;
4542
+ this._rangeAnchorKey = null;
4125
4543
  /** Chip identity is tracked independently of dropdown option positions. */
4126
4544
  this._lastRenderedChipKeys = null;
4127
4545
  this._latestChipScrollGeneration = 0;
@@ -4139,6 +4557,9 @@ class EnhancedSelect extends HTMLElement {
4139
4557
  this._lifecycleTimers = new Set();
4140
4558
  this._lifecycleRafs = new Set();
4141
4559
  this._keyboardActiveChangeGeneration = 0;
4560
+ /** Invalidates selected-option positioning scheduled by an earlier opening. */
4561
+ this._openSelectedScrollGeneration = 0;
4562
+ this._openSelectedScrollCleanup = null;
4142
4563
  this._tracking = { events: [], styles: [], limitations: [] };
4143
4564
  this._suppressBlurClose = false;
4144
4565
  this._renderCycleId = 0;
@@ -4316,6 +4737,7 @@ class EnhancedSelect extends HTMLElement {
4316
4737
  this._syncListboxAccessibility();
4317
4738
  }
4318
4739
  disconnectedCallback() {
4740
+ this._cancelOpenSelectedScroll();
4319
4741
  this._cancelLatestChipScroll();
4320
4742
  this._cancelBusyPresentation();
4321
4743
  if (this._dataRequestCoordinator) {
@@ -4902,12 +5324,12 @@ class EnhancedSelect extends HTMLElement {
4902
5324
  duplicateKeyPolicy: this._getDuplicateKeyPolicy(),
4903
5325
  });
4904
5326
  const activeKey = this._engine.state.activeKey;
4905
- const anchorKey = this._rangeAnchorIndex === null ? undefined : this._itemRegistry.indexToKey.get(this._rangeAnchorIndex);
5327
+ const anchorKey = this._rangeAnchorKey;
4906
5328
  this._itemRegistry = registry;
4907
5329
  this._state.loadedItems = items;
4908
5330
  this._registryItemsRef = items;
4909
5331
  const disabledKeys = this._getBlockedDisabledKeys();
4910
- this._rangeAnchorIndex = anchorKey === undefined ? null : registry.keyToIndex.get(anchorKey) ?? null;
5332
+ this._rangeAnchorKey = anchorKey !== null && registry.keyToRecord.has(anchorKey) ? anchorKey : null;
4911
5333
  this._engine.dispatch({
4912
5334
  type: 'ITEMS_REGISTERED',
4913
5335
  keys: registry.records.map((record) => record.key),
@@ -6156,7 +6578,7 @@ class EnhancedSelect extends HTMLElement {
6156
6578
  ───────────────────────────────────────────────────────────────────────── */
6157
6579
 
6158
6580
  .dropdown-arrow-container {
6159
- position: absolute;
6581
+ position: var(--select-arrow-container-position, absolute);
6160
6582
  top: 0;
6161
6583
  right: 0;
6162
6584
  bottom: 0;
@@ -6465,7 +6887,7 @@ class EnhancedSelect extends HTMLElement {
6465
6887
  font-weight: var(--select-group-header-weight, 600);
6466
6888
  color: var(--select-group-header-color, var(--select-text-muted));
6467
6889
  background: var(--select-group-header-bg, #f3f4f6);
6468
- text-align: var(--select-group-header-text-align, left);
6890
+ text-align: var(--select-group-header-text-align, start);
6469
6891
  font-size: var(--select-group-header-font-size, 0.7333em);
6470
6892
  text-transform: var(--select-group-header-text-transform, uppercase);
6471
6893
  letter-spacing: var(--select-group-header-letter-spacing, 0.08em);
@@ -7452,6 +7874,15 @@ class EnhancedSelect extends HTMLElement {
7452
7874
  this._dropdown.removeAttribute('inert');
7453
7875
  this._dropdown.removeAttribute('aria-hidden');
7454
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;
7455
7886
  this.setAttribute('data-open', 'true');
7456
7887
  this._liftStackingAncestors();
7457
7888
  this._dropdown.style.display = 'block';
@@ -7463,28 +7894,17 @@ class EnhancedSelect extends HTMLElement {
7463
7894
  this._emit('open', {});
7464
7895
  this._config.callbacks.onOpen?.();
7465
7896
  this._announce('Options expanded');
7466
- // Scroll to selected if configured
7467
- if (this._config.scrollToSelected.enabled) {
7468
- const keyboardActiveChangeGeneration = this._keyboardActiveChangeGeneration;
7469
- const canRestoreOpenSelection = () => this._state.isOpen
7470
- && this._keyboardActiveChangeGeneration === keyboardActiveChangeGeneration;
7471
- // Use requestAnimationFrame for better timing after render
7472
- this._requestLifecycleFrame(() => {
7473
- if (!canRestoreOpenSelection())
7474
- return;
7475
- // Double RAF to ensure layout is complete
7476
- this._requestLifecycleFrame(() => {
7477
- if (!canRestoreOpenSelection())
7478
- return;
7479
- this._scrollToSelected();
7480
- });
7481
- });
7482
- }
7897
+ this._scheduleOpenSelectedScroll();
7483
7898
  }
7484
7899
  _handleClose(reason = 'programmatic') {
7900
+ if (this._state.isOpen) {
7901
+ this._closedOptionsViewportAnchor = this._captureOptionsViewportAnchor();
7902
+ }
7485
7903
  const effects = this._engine.dispatch({ type: 'CLOSE_REQUEST', reason });
7486
7904
  if (!effects.some((effect) => effect.type === 'POPUP_CLOSED'))
7487
7905
  return;
7906
+ this._cancelOpenSelectedScroll();
7907
+ this._selectedOptionsSelectionAtOpen = null;
7488
7908
  this.removeAttribute('data-open');
7489
7909
  this._restoreLiftedAncestors();
7490
7910
  this._dropdown.setAttribute('data-placement', this._resolvedDropdownPlacement);
@@ -7496,6 +7916,257 @@ class EnhancedSelect extends HTMLElement {
7496
7916
  this._config.callbacks.onClose?.();
7497
7917
  this._announce('Options collapsed');
7498
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
+ }
7499
8170
  /** Stop an outstanding exit before reopening, disconnecting or starting another one. */
7500
8171
  _cancelDropdownExit() {
7501
8172
  if (this._dropdownExitTimer !== null) {
@@ -7734,16 +8405,40 @@ class EnhancedSelect extends HTMLElement {
7734
8405
  }
7735
8406
  if (this._dataLoadingConfig.protocol === 'acknowledged'
7736
8407
  && (this._dataLoadingConfig.searchMode === 'remote' || this._dataLoadingConfig.searchMode === 'hybrid')) {
8408
+ const wasEligible = Array.from(this._state.searchQuery.trim()).length
8409
+ >= this._dataLoadingConfig.minSearchCharacters;
8410
+ const isEligible = Array.from(query.trim()).length >= this._dataLoadingConfig.minSearchCharacters;
8411
+ if (wasEligible && !isEligible)
8412
+ this._cancelBusyPresentation();
7737
8413
  this._state.searchQuery = query;
7738
8414
  this._syncClearControlState();
7739
8415
  this._state.lastNotifiedQuery = query;
7740
8416
  this._state.lastNotifiedResultCount = 0;
7741
8417
  if (this._dataRequestCoordinator) {
8418
+ const beforeSnapshot = this._dataRequestCoordinator.getSnapshot();
7742
8419
  const actions = this._dataRequestCoordinator.setQuery(query);
7743
8420
  if (this._acknowledgedReady)
7744
8421
  this._dispatchAcknowledgedActions(actions);
7745
- else
8422
+ const startsRequest = actions.some((action) => action.type === 'request');
8423
+ if (this._acknowledgedReady && !startsRequest) {
8424
+ const snapshot = this._dataRequestCoordinator.getSnapshot();
8425
+ const restoredDataChanged = beforeSnapshot.items.length !== snapshot.items.length
8426
+ || beforeSnapshot.items.some((item, index) => item !== snapshot.items[index])
8427
+ || beforeSnapshot.hasMore !== snapshot.hasMore
8428
+ || JSON.stringify(beforeSnapshot.nextEligiblePosition) !== JSON.stringify(snapshot.nextEligiblePosition);
8429
+ this._state.isBusy = snapshot.busy || this._acknowledgedProjectionPending;
8430
+ this._state.isSearching = snapshot.activeRequest?.kind === 'search';
8431
+ this._syncListboxAccessibility();
8432
+ if (actions.some((action) => action.type === 'cancel') || restoredDataChanged) {
8433
+ void this._projectAcknowledgedSnapshot(snapshot, null, false);
8434
+ }
8435
+ else {
8436
+ this._renderOptions();
8437
+ }
8438
+ }
8439
+ else if (!this._acknowledgedReady) {
7746
8440
  this._renderOptions();
8441
+ }
7747
8442
  }
7748
8443
  else if (!this._state.isOpen) {
7749
8444
  this._handleOpen();
@@ -7826,26 +8521,38 @@ class EnhancedSelect extends HTMLElement {
7826
8521
  case 'Home':
7827
8522
  e.preventDefault();
7828
8523
  if (this._state.isOpen) {
8524
+ if (this._usesSelectedFirstVisualOrder()) {
8525
+ this._moveToVisualBoundary('first', { shiftKey: e.shiftKey, toggleKey: e.ctrlKey || e.metaKey });
8526
+ break;
8527
+ }
7829
8528
  const selectableIndices = this._getSelectableOptionIndices();
7830
8529
  const firstIndex = selectableIndices[0];
7831
8530
  if (firstIndex === undefined)
7832
8531
  break;
7833
8532
  this._setActive(firstIndex);
7834
8533
  if (this._config.selection.mode === 'multi' && e.shiftKey) {
7835
- 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) });
7836
8537
  }
7837
8538
  }
7838
8539
  break;
7839
8540
  case 'End':
7840
8541
  e.preventDefault();
7841
8542
  if (this._state.isOpen) {
8543
+ if (this._usesSelectedFirstVisualOrder()) {
8544
+ this._moveToVisualBoundary('last', { shiftKey: e.shiftKey, toggleKey: e.ctrlKey || e.metaKey });
8545
+ break;
8546
+ }
7842
8547
  const selectableIndices = this._getSelectableOptionIndices();
7843
8548
  const lastIndex = selectableIndices[selectableIndices.length - 1];
7844
8549
  if (lastIndex === undefined)
7845
8550
  break;
7846
8551
  this._setActive(lastIndex);
7847
8552
  if (this._config.selection.mode === 'multi' && e.shiftKey) {
7848
- 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) });
7849
8556
  }
7850
8557
  }
7851
8558
  break;
@@ -7900,6 +8607,26 @@ class EnhancedSelect extends HTMLElement {
7900
8607
  }
7901
8608
  }
7902
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
+ }
7903
8630
  const selectableIndices = this._getSelectableOptionIndices();
7904
8631
  if (selectableIndices.length === 0)
7905
8632
  return;
@@ -7921,14 +8648,90 @@ class EnhancedSelect extends HTMLElement {
7921
8648
  const next = selectableIndices[nextPosition];
7922
8649
  this._setActive(next);
7923
8650
  if (this._config.selection.mode === 'multi' && opts?.shiftKey) {
7924
- const anchor = this._rangeAnchorIndex ?? currentIndex;
7925
- const anchorIndex = anchor >= 0 ? anchor : next;
7926
- if (this._rangeAnchorIndex === null) {
7927
- this._rangeAnchorIndex = anchorIndex;
7928
- }
7929
- 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 });
7930
8657
  }
7931
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);
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);
8734
+ }
7932
8735
  /** Return true only when boundary navigation is held for an in-flight/new page. */
7933
8736
  _requestKeyboardLoadMore() {
7934
8737
  if (!this._state.isOpen
@@ -7956,7 +8759,7 @@ class EnhancedSelect extends HTMLElement {
7956
8759
  this._dispatchAcknowledgedActions(actions);
7957
8760
  return true;
7958
8761
  }
7959
- _setActive(index, reason = 'keyboard') {
8762
+ _setActive(index, reason = 'keyboard', options = {}) {
7960
8763
  this._ensureRegistryCurrent();
7961
8764
  const record = this._getRecordByIndex(index);
7962
8765
  let option = this._getOptionElementByIndex(index);
@@ -7967,8 +8770,10 @@ class EnhancedSelect extends HTMLElement {
7967
8770
  if (!record || record.disabled || !option || option.getAttribute('aria-disabled') === 'true') {
7968
8771
  return;
7969
8772
  }
7970
- if (reason === 'keyboard')
8773
+ if (reason === 'keyboard' || reason === 'search') {
7971
8774
  this._keyboardActiveChangeGeneration += 1;
8775
+ this._cancelOpenSelectedScroll();
8776
+ }
7972
8777
  const previousIndex = this._state.activeIndex;
7973
8778
  this._dispatchActiveKey(record.key, reason, 'set active');
7974
8779
  if (this._state.activeIndex !== index)
@@ -7995,8 +8800,7 @@ class EnhancedSelect extends HTMLElement {
7995
8800
  else {
7996
8801
  this._syncCustomOptionActiveClasses(option, true);
7997
8802
  }
7998
- if (typeof option.scrollIntoView === 'function') {
7999
- // Don't scroll wildly when just opening with pre-selections
8803
+ if (options.scroll !== false && typeof option.scrollIntoView === 'function') {
8000
8804
  option.scrollIntoView({ block: 'nearest', behavior: 'smooth' });
8001
8805
  }
8002
8806
  // Announce position for screen readers
@@ -8052,8 +8856,22 @@ class EnhancedSelect extends HTMLElement {
8052
8856
  this._typeTimeout = window.setTimeout(() => {
8053
8857
  this._typeBuffer = '';
8054
8858
  }, 500);
8055
- // Find first matching option
8859
+ // Type-ahead uses the displayed candidate order when a presentation projection is active.
8056
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
+ }
8057
8875
  const matchIndex = this._state.loadedItems.findIndex((item) => getValue(item).toLowerCase().startsWith(this._typeBuffer));
8058
8876
  if (matchIndex >= 0) {
8059
8877
  this._setActive(matchIndex, 'search');
@@ -8122,6 +8940,17 @@ class EnhancedSelect extends HTMLElement {
8122
8940
  };
8123
8941
  }
8124
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
+ }
8125
8954
  const selectableIndices = this._getSelectableOptionIndices();
8126
8955
  const selected = Array.from(this._state.selectedIndices).sort((a, b) => a - b);
8127
8956
  // Opening an empty select must not implicitly assign an active descendant.
@@ -8131,7 +8960,9 @@ class EnhancedSelect extends HTMLElement {
8131
8960
  return;
8132
8961
  }
8133
8962
  const target = selected.find((index) => selectableIndices.includes(index)) ?? selectableIndices[0];
8134
- 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 });
8135
8966
  }
8136
8967
  _announce(message) {
8137
8968
  const effects = computeAccessibilityEffects(deriveAccessibilityState(this._engine.state), {
@@ -8185,9 +9016,10 @@ class EnhancedSelect extends HTMLElement {
8185
9016
  const toggleKey = Boolean(opts?.toggleKey);
8186
9017
  const shiftKey = Boolean(opts?.shiftKey);
8187
9018
  if (shiftKey) {
8188
- const anchor = this._rangeAnchorIndex ?? index;
8189
- this._selectRange(anchor, index, { clear: !toggleKey, reason });
8190
- 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;
8191
9023
  return;
8192
9024
  }
8193
9025
  // Multi select with toggle
@@ -8201,7 +9033,7 @@ class EnhancedSelect extends HTMLElement {
8201
9033
  // Re-render to update styles (safer than trying to find the element in filtered list)
8202
9034
  this._renderOptions();
8203
9035
  }
8204
- this._rangeAnchorIndex = index;
9036
+ this._rangeAnchorKey = record.key;
8205
9037
  this._updateInputDisplay();
8206
9038
  const selectDetail = this._getSelectEventDetail(record);
8207
9039
  this._emit('select', selectDetail);
@@ -8460,58 +9292,71 @@ class EnhancedSelect extends HTMLElement {
8460
9292
  this._optionsContainer.style.transition = 'opacity 0.2s ease-in';
8461
9293
  }, 150);
8462
9294
  }
8463
- _scrollToSelected() {
8464
- if (this._state.selectedIndices.size === 0)
8465
- return;
8466
- const target = this._config.scrollToSelected.multiSelectTarget;
8467
- const indices = Array.from(this._state.selectedIndices).filter((index) => index >= 0).sort((a, b) => a - b);
8468
- if (indices.length === 0)
8469
- return;
8470
- // For multi-select, find the closest selected item to the current scroll position
8471
- let targetIndex;
8472
- if (this._config.selection.mode === 'multi' && indices.length > 1) {
8473
- // Calculate which selected item is closest to the center of the viewport
8474
- const dropdownRect = this._dropdown.getBoundingClientRect();
8475
- const viewportCenter = this._dropdown.scrollTop + (dropdownRect.height / 2);
8476
- // Find the selected item closest to viewport center
8477
- let closestIndex = indices[0];
8478
- let closestDistance = Infinity;
8479
- for (const index of indices) {
8480
- const option = this._getOptionElementByIndex(index);
8481
- if (option) {
8482
- const optionTop = option.offsetTop;
8483
- const distance = Math.abs(optionTop - viewportCenter);
8484
- if (distance < closestDistance) {
8485
- closestDistance = distance;
8486
- closestIndex = index;
8487
- }
8488
- }
8489
- }
8490
- targetIndex = closestIndex;
8491
- }
8492
- else {
8493
- // For single select or only one selected item, use the configured target
8494
- targetIndex = target === 'first' ? indices[0] : indices[indices.length - 1];
8495
- }
8496
- // 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.
8497
9308
  let option = this._getOptionElementByIndex(targetIndex);
8498
9309
  if (!option && this._guardedVirtualizer) {
8499
- const targetKey = this._itemRegistry.indexToKey.get(targetIndex);
8500
- if (targetKey !== undefined) {
8501
- this._materializeGuardedVirtualKey(targetKey);
8502
- option = this._getOptionElementByIndex(targetIndex);
8503
- }
9310
+ this._materializeGuardedVirtualKey(targetKey);
9311
+ option = this._getOptionElementByIndex(targetIndex);
8504
9312
  }
8505
9313
  if (option) {
8506
- // Use smooth scrolling with center alignment for better UX
8507
- if (typeof option.scrollIntoView === 'function') {
8508
- option.scrollIntoView({
8509
- block: this._config.scrollToSelected.block || 'center',
8510
- behavior: 'smooth',
8511
- });
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 });
8512
9319
  }
8513
- // Also set it as active for keyboard navigation
8514
- 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;
8515
9360
  }
8516
9361
  }
8517
9362
  async _loadMoreItems(trigger = 'manual') {
@@ -8961,6 +9806,13 @@ class EnhancedSelect extends HTMLElement {
8961
9806
  * Clear search query and restore full option list
8962
9807
  */
8963
9808
  clearSearch() {
9809
+ if (this._dataLoadingConfig.protocol === 'acknowledged'
9810
+ && (this._dataLoadingConfig.searchMode === 'remote' || this._dataLoadingConfig.searchMode === 'hybrid')
9811
+ && this._dataRequestCoordinator) {
9812
+ this._input.value = '';
9813
+ this._handleSearch('');
9814
+ return;
9815
+ }
8964
9816
  this._state.searchQuery = '';
8965
9817
  if (this._config.searchable) {
8966
9818
  this._input.value = '';
@@ -8990,9 +9842,21 @@ class EnhancedSelect extends HTMLElement {
8990
9842
  this._invalidateGuardedMeasurements();
8991
9843
  const previousMode = this._config.selection.mode;
8992
9844
  const previousEnabled = this._config.enabled;
9845
+ const previousOpenScrollEnabled = this._config.scrollToSelected.enabled;
8993
9846
  const previousDataLoadingConfig = this._dataLoadingConfig;
8994
- const { dataLoading, callbacks, ...legacyConfig } = config;
9847
+ let searchEligibilityBecameInactive = false;
9848
+ const { dataLoading, callbacks, selectedOptions, scrollToSelected, ...legacyConfig } = config;
8995
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
+ }
8996
9860
  let configErrorDetail;
8997
9861
  if (callbacks !== undefined && callbacks !== null) {
8998
9862
  const callbackInput = callbacks;
@@ -9012,6 +9876,10 @@ class EnhancedSelect extends HTMLElement {
9012
9876
  legacyUpdate.callbacks = legacyCallbacks;
9013
9877
  }
9014
9878
  this._config = this._mergeConfig(this._config, legacyUpdate);
9879
+ if (previousOpenScrollEnabled && !this._config.scrollToSelected.enabled) {
9880
+ this._openOptionsViewportAnchor = null;
9881
+ this._cancelOpenSelectedScroll();
9882
+ }
9015
9883
  if (dataLoading !== undefined) {
9016
9884
  const dataLoadingPrototype = dataLoading !== null && typeof dataLoading === 'object'
9017
9885
  ? Object.getPrototypeOf(dataLoading)
@@ -9021,6 +9889,13 @@ class EnhancedSelect extends HTMLElement {
9021
9889
  : dataLoading;
9022
9890
  const validation = validateDataLoadingConfig(candidate);
9023
9891
  if (validation.valid) {
9892
+ const wasRemoteEligible = previousDataLoadingConfig.protocol === 'acknowledged'
9893
+ && (previousDataLoadingConfig.searchMode === 'remote' || previousDataLoadingConfig.searchMode === 'hybrid')
9894
+ && Array.from(this._state.searchQuery.trim()).length >= previousDataLoadingConfig.minSearchCharacters;
9895
+ const becomesRemoteEligible = validation.value.protocol === 'acknowledged'
9896
+ && (validation.value.searchMode === 'remote' || validation.value.searchMode === 'hybrid')
9897
+ && Array.from(this._state.searchQuery.trim()).length >= validation.value.minSearchCharacters;
9898
+ searchEligibilityBecameInactive = wasRemoteEligible && !becomesRemoteEligible;
9024
9899
  this._dataLoadingConfig = validation.value;
9025
9900
  this._hasLastInvalidDataLoadingCandidate = false;
9026
9901
  this._lastInvalidDataLoadingCandidate = undefined;
@@ -9108,6 +9983,8 @@ class EnhancedSelect extends HTMLElement {
9108
9983
  const acknowledgedModeChanged = previousDataLoadingConfig.protocol !== this._dataLoadingConfig.protocol
9109
9984
  || previousDataLoadingConfig.searchMode !== this._dataLoadingConfig.searchMode
9110
9985
  || previousDataLoadingConfig.paginationMode !== this._dataLoadingConfig.paginationMode;
9986
+ if (searchEligibilityBecameInactive)
9987
+ this._cancelBusyPresentation();
9111
9988
  if (coordinator && switchesToLegacy) {
9112
9989
  if (this._acknowledgedReady && !this._acknowledgedProjectionPending && !this._acknowledgedProjectionSettling) {
9113
9990
  const update = coordinator.updateConfig(this._createCoordinatorConfig());
@@ -9142,8 +10019,14 @@ class EnhancedSelect extends HTMLElement {
9142
10019
  this._state.isBusy = snapshot.busy;
9143
10020
  this._state.isSearching = snapshot.activeRequest?.kind === 'search';
9144
10021
  this._syncListboxAccessibility();
9145
- if (update.actions.every((action) => action.type !== 'request'))
9146
- this._renderOptions();
10022
+ if (update.actions.every((action) => action.type !== 'request')) {
10023
+ if (this._acknowledgedSnapshotDiffersFromLoadedItems(snapshot)) {
10024
+ this._reconcileAcknowledgedSnapshot(snapshot);
10025
+ }
10026
+ else {
10027
+ this._renderOptions();
10028
+ }
10029
+ }
9147
10030
  }
9148
10031
  }
9149
10032
  }
@@ -9302,14 +10185,12 @@ class EnhancedSelect extends HTMLElement {
9302
10185
  }
9303
10186
  _ensureDataRequestCoordinator() {
9304
10187
  if (!this._dataRequestCoordinator) {
9305
- const isRemote = this._dataLoadingConfig.searchMode === 'remote'
9306
- || this._dataLoadingConfig.searchMode === 'hybrid';
9307
10188
  try {
9308
10189
  this._dataRequestCoordinator = new DataRequestCoordinator({
9309
10190
  config: this._createCoordinatorConfig(),
9310
10191
  initialQuery: this._state.searchQuery,
9311
10192
  initialItems: this._state.loadedItems,
9312
- hasMore: !isRemote && (this._config.infiniteScroll.enabled || this._config.loadMore.enabled),
10193
+ hasMore: this._config.infiniteScroll.enabled || this._config.loadMore.enabled,
9313
10194
  });
9314
10195
  }
9315
10196
  catch (error) {
@@ -9545,19 +10426,39 @@ class EnhancedSelect extends HTMLElement {
9545
10426
  activeKey: this._engine.state.activeKey,
9546
10427
  };
9547
10428
  }
9548
- _createLegacyRenderPlan(filteredIndices) {
9549
- const indices = [...filteredIndices];
9550
- const filteredKeys = indices
9551
- .map((index) => this._itemRegistry.indexToKey.get(index))
9552
- .filter((key) => key !== undefined);
9553
- const filteredIndexByKey = new Map();
9554
- 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
+ });
9555
10453
  return {
9556
10454
  mode: 'legacy-full',
9557
10455
  filteredIndices: indices,
9558
10456
  filteredKeys,
9559
10457
  intendedRenderKeys: filteredKeys.slice(),
9560
- filteredIndexByKey,
10458
+ displayIndexByKey,
10459
+ sourceIndexByKey,
10460
+ filteredIndexByKey: displayIndexByKey,
10461
+ groupedPresentation,
9561
10462
  };
9562
10463
  }
9563
10464
  _createVirtualRenderPlan(startIndex, endIndex) {
@@ -9566,12 +10467,16 @@ class EnhancedSelect extends HTMLElement {
9566
10467
  const filteredIndices = intendedRenderKeys
9567
10468
  .map((key) => this._itemRegistry.keyToIndex.get(key))
9568
10469
  .filter((index) => index !== undefined);
10470
+ const displayIndexByKey = new Map(this._renderPlan.displayIndexByKey);
9569
10471
  return {
9570
10472
  mode: 'virtual-window',
9571
10473
  filteredIndices,
9572
10474
  filteredKeys,
9573
10475
  intendedRenderKeys,
9574
- filteredIndexByKey: new Map(this._renderPlan.filteredIndexByKey),
10476
+ displayIndexByKey,
10477
+ sourceIndexByKey: new Map(this._renderPlan.sourceIndexByKey),
10478
+ filteredIndexByKey: displayIndexByKey,
10479
+ groupedPresentation: this._renderPlan.groupedPresentation,
9575
10480
  };
9576
10481
  }
9577
10482
  _ensureGuardedVirtualizer(filteredKeys) {
@@ -9719,6 +10624,7 @@ class EnhancedSelect extends HTMLElement {
9719
10624
  searchMode: dataLoading?.searchMode ?? 'local',
9720
10625
  paginationMode: dataLoading?.paginationMode ?? 'page',
9721
10626
  firstPage: dataLoading?.firstPage ?? 1,
10627
+ minSearchCharacters: dataLoading?.minSearchCharacters ?? 0,
9722
10628
  ...(dataLoading?.fetchLimit === undefined ? {} : { fetchLimit: dataLoading.fetchLimit }),
9723
10629
  };
9724
10630
  this._acknowledgedSearchMode = config.dataLoading?.searchMode ?? 'local';
@@ -9773,6 +10679,12 @@ class EnhancedSelect extends HTMLElement {
9773
10679
  for (const action of actions) {
9774
10680
  if (action.type === 'cancel') {
9775
10681
  this._cancelBusyPresentation();
10682
+ const snapshot = this._dataRequestCoordinator?.getSnapshot();
10683
+ if (snapshot) {
10684
+ this._state.isBusy = snapshot.busy || this._acknowledgedProjectionPending;
10685
+ this._state.isSearching = snapshot.activeRequest?.kind === 'search';
10686
+ this._syncListboxAccessibility();
10687
+ }
9776
10688
  this._dispatchAcknowledgedEvent('dataRequestCancel', action.notification);
9777
10689
  try {
9778
10690
  this._dataRequestCancelCallback?.(action.notification);
@@ -9858,6 +10770,34 @@ class EnhancedSelect extends HTMLElement {
9858
10770
  return Promise.resolve();
9859
10771
  return this._projectAcknowledgedSnapshot(this._dataRequestCoordinator.getSnapshot(), this._acknowledgedProjectionRequest ?? this._acknowledgedLastRequest, this._acknowledgedProjectionCommitsPosition);
9860
10772
  }
10773
+ _acknowledgedSnapshotDiffersFromLoadedItems(snapshot) {
10774
+ const loadedItems = this._state.loadedItems;
10775
+ return loadedItems.length !== snapshot.items.length
10776
+ || loadedItems.some((item, index) => item !== snapshot.items[index]);
10777
+ }
10778
+ _reconcileAcknowledgedSnapshot(snapshot) {
10779
+ if (!this._acknowledgedSnapshotDiffersFromLoadedItems(snapshot))
10780
+ return;
10781
+ const activeProjection = this._acknowledgedProjectionTask;
10782
+ if (this._acknowledgedProjectionRunning && activeProjection) {
10783
+ // Deferred config is reconciled from inside the current projection's
10784
+ // settlement callback. Wait until that task releases its running guard,
10785
+ // then project the coordinator's latest accepted snapshot.
10786
+ void activeProjection.then(() => {
10787
+ if (!this.isConnected)
10788
+ return;
10789
+ const latestSnapshot = this._dataRequestCoordinator?.getSnapshot() ?? snapshot;
10790
+ if (this._acknowledgedSnapshotDiffersFromLoadedItems(latestSnapshot)) {
10791
+ void this._projectAcknowledgedSnapshot(latestSnapshot, null, false);
10792
+ }
10793
+ else {
10794
+ this._dispatchPendingAcknowledgedSearchIntent();
10795
+ }
10796
+ });
10797
+ return;
10798
+ }
10799
+ void this._projectAcknowledgedSnapshot(snapshot, null, false);
10800
+ }
9861
10801
  _projectAcknowledgedSnapshot(snapshot, request, commitPosition) {
9862
10802
  if (this._acknowledgedProjectionRunning) {
9863
10803
  return this._acknowledgedProjectionTask ?? Promise.resolve();
@@ -9914,7 +10854,10 @@ class EnhancedSelect extends HTMLElement {
9914
10854
  }
9915
10855
  if (!this._state.searchQuery
9916
10856
  && this._acknowledgedPendingSearchQuery === null
9917
- && !this._isActivelyEditingSearchInput()) {
10857
+ && !this._isActivelyEditingSearchInput()
10858
+ && !(this._dataLoadingConfig.protocol === 'acknowledged'
10859
+ && (this._dataLoadingConfig.searchMode === 'remote' || this._dataLoadingConfig.searchMode === 'hybrid')
10860
+ && this._dataLoadingConfig.minSearchCharacters > 0)) {
9918
10861
  this._updateInputDisplay();
9919
10862
  }
9920
10863
  this._syncListboxAccessibility();
@@ -10077,6 +11020,11 @@ class EnhancedSelect extends HTMLElement {
10077
11020
  this._state.isBusy = state.busy;
10078
11021
  this._state.isSearching = state.activeRequest?.kind === 'search';
10079
11022
  this._syncListboxAccessibility();
11023
+ if (update.actions.every((action) => action.type !== 'request')
11024
+ && this._acknowledgedSnapshotDiffersFromLoadedItems(state)) {
11025
+ this._reconcileAcknowledgedSnapshot(state);
11026
+ return;
11027
+ }
10080
11028
  }
10081
11029
  this._dispatchPendingAcknowledgedSearchIntent();
10082
11030
  }
@@ -10482,11 +11430,31 @@ class EnhancedSelect extends HTMLElement {
10482
11430
  // Handle Grouped Items Rendering (when no search query)
10483
11431
  if (this._state.groupedItems.length > 0 && !query) {
10484
11432
  this._destroyGuardedVirtualizer();
10485
- 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);
10486
11454
  filteredIndicesForScope = this._renderPlan.filteredIndices;
10487
11455
  this._registerShadowItems(filteredIndicesForScope);
10488
11456
  this._refreshVirtualizationScope(filteredIndicesForScope);
10489
- this._state.groupedItems.forEach((group, groupIndex) => {
11457
+ this._renderPlan.groupedPresentation.forEach(({ group, groupIndex, orderedKeys }) => {
10490
11458
  let header;
10491
11459
  if (this.groupHeaderRenderer) {
10492
11460
  header = this.groupHeaderRenderer(group, groupIndex);
@@ -10512,10 +11480,10 @@ class EnhancedSelect extends HTMLElement {
10512
11480
  }
10513
11481
  header.setAttribute('part', 'group-header');
10514
11482
  this._optionsContainer.appendChild(header);
10515
- group.options.forEach(item => {
10516
- // Find original index for correct ID generation and selection
10517
- const index = this._state.loadedItems.indexOf(item);
10518
- 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];
10519
11487
  this._renderSingleOption(item, index, getValue, getLabel);
10520
11488
  }
10521
11489
  });
@@ -10584,13 +11552,16 @@ class EnhancedSelect extends HTMLElement {
10584
11552
  const chunkSize = 80;
10585
11553
  let cursor = 0;
10586
11554
  let maxRenderTarget = 0;
10587
- if (this._state.selectedIndices.size > 0 && this._config.scrollToSelected.enabled) {
10588
- const indices = Array.from(this._state.selectedIndices).filter((index) => index >= 0).sort((a, b) => a - b);
10589
- const targetIndex = this._config.scrollToSelected.multiSelectTarget === 'first' ? indices[0] : indices[indices.length - 1];
10590
- const filteredPos = filteredIndices.indexOf(targetIndex);
10591
- if (filteredPos !== -1) {
10592
- maxRenderTarget = filteredPos + 20; // Ensure we render up to the selection
10593
- }
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;
10594
11565
  }
10595
11566
  const renderChunk = () => {
10596
11567
  if (renderCycleId !== this._renderCycleId) {
@@ -12040,5 +13011,5 @@ function warnCSPViolation(feature, fallback) {
12040
13011
  }
12041
13012
  }
12042
13013
 
12043
- 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 };
12044
13015
  //# sourceMappingURL=index.js.map