@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.umd.js CHANGED
@@ -2078,6 +2078,123 @@
2078
2078
  customElements.define("smilodon-select", NativeSelectElement);
2079
2079
  }
2080
2080
 
2081
+ const SELECTED_OPTIONS_FIELDS = new Set(['placement', 'groupedPlacement']);
2082
+ const SCROLL_TO_SELECTED_FIELDS = new Set([
2083
+ 'enabled',
2084
+ 'multiSelectTarget',
2085
+ 'onOpen',
2086
+ 'behavior',
2087
+ 'block',
2088
+ ]);
2089
+ const placements = new Set(['original', 'selected-first']);
2090
+ const groupedPlacements = new Set(['within-group']);
2091
+ const scrollTargets = new Set(['first', 'last']);
2092
+ const openPolicies = new Set(['preserve', 'reveal', 'align']);
2093
+ const scrollBehaviors = new Set(['auto', 'instant', 'smooth']);
2094
+ const scrollBlocks = new Set(['start', 'center', 'end', 'nearest']);
2095
+ function asPlainRecord(value) {
2096
+ if (value === null || typeof value !== 'object' || Array.isArray(value))
2097
+ return null;
2098
+ const prototype = Object.getPrototypeOf(value);
2099
+ return prototype === Object.prototype || prototype === null ? value : null;
2100
+ }
2101
+ function unknownFieldIssues(record, allowed) {
2102
+ return Object.keys(record)
2103
+ .filter((key) => !allowed.has(key))
2104
+ .sort()
2105
+ .map((key) => ({
2106
+ path: key,
2107
+ code: 'unknown-field',
2108
+ message: `Unknown configuration field: ${key}.`,
2109
+ }));
2110
+ }
2111
+ function validateEnum(record, field, allowed, issues) {
2112
+ const value = record[field];
2113
+ if (value === undefined)
2114
+ return;
2115
+ if (typeof value !== 'string') {
2116
+ issues.push({ path: field, code: 'invalid-type', message: `${field} must be a string.` });
2117
+ }
2118
+ else if (!allowed.has(value)) {
2119
+ issues.push({ path: field, code: 'invalid-value', message: `${field} has an unsupported value.` });
2120
+ }
2121
+ }
2122
+ /** Validate a partial selected-options configuration update. */
2123
+ function validateSelectedOptionsConfig(candidate) {
2124
+ const record = asPlainRecord(candidate);
2125
+ if (!record) {
2126
+ return {
2127
+ valid: false,
2128
+ issues: [{ path: 'selectedOptions', code: 'invalid-type', message: 'selectedOptions must be a plain object.' }],
2129
+ };
2130
+ }
2131
+ const issues = unknownFieldIssues(record, SELECTED_OPTIONS_FIELDS);
2132
+ validateEnum(record, 'placement', placements, issues);
2133
+ validateEnum(record, 'groupedPlacement', groupedPlacements, issues);
2134
+ if (issues.length > 0)
2135
+ return { valid: false, issues };
2136
+ return {
2137
+ valid: true,
2138
+ value: {
2139
+ ...(record.placement === undefined ? {} : { placement: record.placement }),
2140
+ ...(record.groupedPlacement === undefined
2141
+ ? {}
2142
+ : { groupedPlacement: record.groupedPlacement }),
2143
+ },
2144
+ };
2145
+ }
2146
+ /** Validate a partial scroll-to-selected configuration update. */
2147
+ function validateScrollToSelectedConfig(candidate) {
2148
+ const record = asPlainRecord(candidate);
2149
+ if (!record) {
2150
+ return {
2151
+ valid: false,
2152
+ issues: [{ path: 'scrollToSelected', code: 'invalid-type', message: 'scrollToSelected must be a plain object.' }],
2153
+ };
2154
+ }
2155
+ const issues = unknownFieldIssues(record, SCROLL_TO_SELECTED_FIELDS);
2156
+ if (record.enabled !== undefined && typeof record.enabled !== 'boolean') {
2157
+ issues.push({ path: 'enabled', code: 'invalid-type', message: 'enabled must be a boolean.' });
2158
+ }
2159
+ validateEnum(record, 'multiSelectTarget', scrollTargets, issues);
2160
+ validateEnum(record, 'onOpen', openPolicies, issues);
2161
+ validateEnum(record, 'behavior', scrollBehaviors, issues);
2162
+ validateEnum(record, 'block', scrollBlocks, issues);
2163
+ if (issues.length > 0)
2164
+ return { valid: false, issues };
2165
+ return {
2166
+ valid: true,
2167
+ value: {
2168
+ ...(record.enabled === undefined ? {} : { enabled: record.enabled }),
2169
+ ...(record.multiSelectTarget === undefined
2170
+ ? {}
2171
+ : { multiSelectTarget: record.multiSelectTarget }),
2172
+ ...(record.onOpen === undefined ? {} : { onOpen: record.onOpen }),
2173
+ ...(record.behavior === undefined ? {} : { behavior: record.behavior }),
2174
+ ...(record.block === undefined ? {} : { block: record.block }),
2175
+ },
2176
+ };
2177
+ }
2178
+ /** Validate and copy only the new public configuration sections. */
2179
+ function validateSelectedOptionsConfigUpdate(config) {
2180
+ const result = { ...config };
2181
+ if (config.selectedOptions !== undefined) {
2182
+ const validation = validateSelectedOptionsConfig(config.selectedOptions);
2183
+ if (validation.valid)
2184
+ result.selectedOptions = validation.value;
2185
+ else
2186
+ delete result.selectedOptions;
2187
+ }
2188
+ if (config.scrollToSelected !== undefined) {
2189
+ const validation = validateScrollToSelectedConfig(config.scrollToSelected);
2190
+ if (validation.valid)
2191
+ result.scrollToSelected = validation.value;
2192
+ else
2193
+ delete result.scrollToSelected;
2194
+ }
2195
+ return result;
2196
+ }
2197
+
2081
2198
  /**
2082
2199
  * Global Configuration System for Select Components
2083
2200
  * Allows users to define default behaviors that can be overridden at component level
@@ -2117,9 +2234,14 @@
2117
2234
  scrollToSelected: {
2118
2235
  enabled: true,
2119
2236
  multiSelectTarget: 'first',
2237
+ onOpen: 'reveal',
2120
2238
  behavior: 'smooth',
2121
2239
  block: 'nearest',
2122
2240
  },
2241
+ selectedOptions: {
2242
+ placement: 'original',
2243
+ groupedPlacement: 'within-group',
2244
+ },
2123
2245
  loadMore: {
2124
2246
  enabled: false,
2125
2247
  itemsPerLoad: 3,
@@ -2202,7 +2324,8 @@
2202
2324
  * Update global configuration (deep merge)
2203
2325
  */
2204
2326
  updateConfig(updates) {
2205
- this.config = this.deepMerge(this.config, updates);
2327
+ const acceptedUpdates = validateSelectedOptionsConfigUpdate(updates);
2328
+ this.config = this.deepMerge(this.config, acceptedUpdates);
2206
2329
  }
2207
2330
  /**
2208
2331
  * Reset to default configuration
@@ -2262,6 +2385,7 @@
2262
2385
  searchMode: 'local',
2263
2386
  paginationMode: 'page',
2264
2387
  firstPage: 1,
2388
+ minSearchCharacters: 0,
2265
2389
  };
2266
2390
  const ALLOWED_FIELDS = new Set([
2267
2391
  'protocol',
@@ -2269,6 +2393,7 @@
2269
2393
  'paginationMode',
2270
2394
  'firstPage',
2271
2395
  'fetchLimit',
2396
+ 'minSearchCharacters',
2272
2397
  ]);
2273
2398
  function issue(path, code, message) {
2274
2399
  return { path, code, message };
@@ -2291,6 +2416,18 @@
2291
2416
  issues.push(issue(key, 'invalid-positive-integer', `${key} must be a positive safe integer.`));
2292
2417
  }
2293
2418
  }
2419
+ function validateNonNegativeSafeInteger(candidate, issues) {
2420
+ const value = candidate.minSearchCharacters;
2421
+ if (value === undefined)
2422
+ return;
2423
+ if (typeof value !== 'number') {
2424
+ issues.push(issue('minSearchCharacters', 'invalid-type', 'minSearchCharacters must be a number.'));
2425
+ return;
2426
+ }
2427
+ if (!Number.isSafeInteger(value) || value < 0) {
2428
+ issues.push(issue('minSearchCharacters', 'invalid-value', 'minSearchCharacters must be a non-negative safe integer.'));
2429
+ }
2430
+ }
2294
2431
  /** Validate a complete effective per-instance data-loading configuration. */
2295
2432
  function validateDataLoadingConfig(candidate) {
2296
2433
  if (!isRecord$1(candidate)) {
@@ -2329,6 +2466,7 @@
2329
2466
  }
2330
2467
  validatePositiveSafeInteger(candidate, 'firstPage', issues);
2331
2468
  validatePositiveSafeInteger(candidate, 'fetchLimit', issues);
2469
+ validateNonNegativeSafeInteger(candidate, issues);
2332
2470
  if (protocol === 'legacy' && (searchMode === 'remote' || searchMode === 'hybrid')) {
2333
2471
  issues.push(issue('searchMode', 'requires-acknowledged-protocol', 'Remote and hybrid search require the acknowledged protocol.'));
2334
2472
  }
@@ -2342,6 +2480,9 @@
2342
2480
  searchMode: searchMode,
2343
2481
  paginationMode: paginationMode,
2344
2482
  firstPage: candidate.firstPage === undefined ? DEFAULT_CONFIG.firstPage : candidate.firstPage,
2483
+ minSearchCharacters: candidate.minSearchCharacters === undefined
2484
+ ? DEFAULT_CONFIG.minSearchCharacters
2485
+ : candidate.minSearchCharacters,
2345
2486
  ...(candidate.fetchLimit === undefined ? {} : { fetchLimit: candidate.fetchLimit }),
2346
2487
  };
2347
2488
  return { valid: true, value: resolved };
@@ -3145,6 +3286,94 @@
3145
3286
  return true;
3146
3287
  }
3147
3288
 
3289
+ function createVisualNavigationModel(orderedKeys, isSelectable) {
3290
+ const ordered = [...orderedKeys];
3291
+ const selectableKeys = [];
3292
+ const positionByKey = new Map();
3293
+ const selectablePositionByKey = new Map();
3294
+ ordered.forEach((key, position) => {
3295
+ positionByKey.set(key, position);
3296
+ if (isSelectable(key)) {
3297
+ selectablePositionByKey.set(key, selectableKeys.length);
3298
+ selectableKeys.push(key);
3299
+ }
3300
+ });
3301
+ return { orderedKeys: ordered, selectableKeys, positionByKey, selectablePositionByKey };
3302
+ }
3303
+ /** Resolve a clamped keyboard movement in visual order. */
3304
+ function resolveVisualMovement(model, currentKey, delta) {
3305
+ const { selectableKeys, selectablePositionByKey } = model;
3306
+ if (selectableKeys.length === 0)
3307
+ return null;
3308
+ const currentPosition = currentKey === null ? undefined : selectablePositionByKey.get(currentKey);
3309
+ const basePosition = currentPosition ?? (delta >= 0 ? -1 : selectableKeys.length);
3310
+ const nextPosition = Math.max(0, Math.min(selectableKeys.length - 1, basePosition + delta));
3311
+ return selectableKeys[nextPosition] ?? null;
3312
+ }
3313
+ function resolveVisualBoundary(model, boundary) {
3314
+ return boundary === 'first'
3315
+ ? model.selectableKeys[0] ?? null
3316
+ : model.selectableKeys[model.selectableKeys.length - 1] ?? null;
3317
+ }
3318
+ /** Return selectable keys in the inclusive visual interval between two keys. */
3319
+ function resolveVisualRange(model, startKey, endKey) {
3320
+ const startPosition = model.positionByKey.get(startKey);
3321
+ const endPosition = model.positionByKey.get(endKey);
3322
+ if (startPosition === undefined || endPosition === undefined)
3323
+ return [];
3324
+ const low = Math.min(startPosition, endPosition);
3325
+ const high = Math.max(startPosition, endPosition);
3326
+ const selectable = new Set(model.selectableKeys);
3327
+ return model.orderedKeys.slice(low, high + 1).filter((key) => selectable.has(key));
3328
+ }
3329
+
3330
+ /**
3331
+ * Return a presentation-only ordering for option keys.
3332
+ *
3333
+ * The source array and selection set are never mutated. Callers remain
3334
+ * responsible for retaining the returned order as the displayed ordering for
3335
+ * the relevant render/open transaction.
3336
+ */
3337
+ function projectSelectedOptionKeys(orderedKeys, selectedKeys, placement) {
3338
+ const selected = [];
3339
+ const unselected = [];
3340
+ for (const key of orderedKeys) {
3341
+ (selectedKeys.has(key) ? selected : unselected).push(key);
3342
+ }
3343
+ return [...selected, ...unselected];
3344
+ }
3345
+ /**
3346
+ * Stably partitions selected keys to the front of each group independently.
3347
+ * Group order, identity, membership, and the source arrays are preserved.
3348
+ */
3349
+ function projectSelectedOptionGroups(groups, selectedKeys) {
3350
+ return groups.map(({ groupIdentity, orderedKeys }) => {
3351
+ const selected = [];
3352
+ const unselected = [];
3353
+ for (const key of orderedKeys) {
3354
+ (selectedKeys.has(key) ? selected : unselected).push(key);
3355
+ }
3356
+ return { groupIdentity, orderedKeys: [...selected, ...unselected] };
3357
+ });
3358
+ }
3359
+
3360
+ /** Resolve the selected key at an edge of the displayed eligible ordering. */
3361
+ function resolveSelectedTargetKey(orderedKeys, selectedKeys, target) {
3362
+ if (target === 'first') {
3363
+ for (const key of orderedKeys) {
3364
+ if (selectedKeys.has(key))
3365
+ return key;
3366
+ }
3367
+ return null;
3368
+ }
3369
+ for (let index = orderedKeys.length - 1; index >= 0; index -= 1) {
3370
+ const key = orderedKeys[index];
3371
+ if (selectedKeys.has(key))
3372
+ return key;
3373
+ }
3374
+ return null;
3375
+ }
3376
+
3148
3377
  /**
3149
3378
  * DOM-independent coordinator for the opt-in acknowledged data-loading
3150
3379
  * protocol. This module is intentionally not re-exported from the package
@@ -3240,6 +3469,7 @@
3240
3469
  searchMode: dataLoading.searchMode === undefined ? 'local' : dataLoading.searchMode,
3241
3470
  paginationMode: dataLoading.paginationMode === undefined ? 'page' : dataLoading.paginationMode,
3242
3471
  firstPage: dataLoading.firstPage === undefined ? 1 : dataLoading.firstPage,
3472
+ minSearchCharacters: dataLoading.minSearchCharacters === undefined ? 0 : dataLoading.minSearchCharacters,
3243
3473
  initialPage: infiniteScroll.initialPage === undefined ? 1 : infiniteScroll.initialPage,
3244
3474
  fetchLimit: dataLoading.fetchLimit,
3245
3475
  maxCursorPages: dataLoading.maxCursorPages === undefined
@@ -3278,6 +3508,9 @@
3278
3508
  if (!isPositiveSafeInteger(input.firstPage)) {
3279
3509
  add('dataLoading.firstPage', 'must be a positive safe integer');
3280
3510
  }
3511
+ if (!isNonNegativeSafeInteger(input.minSearchCharacters)) {
3512
+ add('dataLoading.minSearchCharacters', 'must be a non-negative safe integer');
3513
+ }
3281
3514
  if (!isPositiveSafeInteger(input.initialPage)) {
3282
3515
  add('infiniteScroll.initialPage', 'must be a positive safe integer');
3283
3516
  }
@@ -3317,6 +3550,7 @@
3317
3550
  searchMode: input.searchMode,
3318
3551
  paginationMode: input.paginationMode,
3319
3552
  firstPage: input.firstPage,
3553
+ minSearchCharacters: input.minSearchCharacters,
3320
3554
  initialPage: input.initialPage,
3321
3555
  fetchLimit: resolvedFetchLimit,
3322
3556
  maxCursorPages: input.maxCursorPages,
@@ -3362,6 +3596,8 @@
3362
3596
  this.resourceLimit = null;
3363
3597
  this.sentinelBlocked = false;
3364
3598
  this.sentinelIntersecting = false;
3599
+ /** Unfiltered items and continuation are independent from each filtered query. */
3600
+ this.browseState = null;
3365
3601
  const initialConfig = options.config === undefined ? {} : options.config;
3366
3602
  const validation = validateDataCoordinatorConfig(initialConfig);
3367
3603
  if (!validation.valid) {
@@ -3372,12 +3608,24 @@
3372
3608
  this.query = options.initialQuery ?? '';
3373
3609
  this.items = asFrozenItems(options.initialItems ?? []);
3374
3610
  const remote = this.isRemoteMode();
3375
- this.hasMore = remote ? false : options.hasMore ?? false;
3611
+ const searchEligible = this.isSearchEligible(this.query);
3612
+ this.hasMore = options.hasMore ?? false;
3376
3613
  this.nextEligiblePosition = this.initialPosition();
3377
- this.lastCommittedPage = this.config.paginationMode === 'page' && !remote
3378
- ? this.config.initialPage
3614
+ this.lastCommittedPage = this.config.paginationMode === 'page'
3615
+ ? (remote && searchEligible
3616
+ ? undefined
3617
+ : this.items.length > 0 ? this.config.initialPage : undefined)
3379
3618
  : undefined;
3380
- this.needsInitialRemoteSearch = remote;
3619
+ this.needsInitialRemoteSearch = remote && searchEligible;
3620
+ if (remote && searchEligible) {
3621
+ const browse = this.captureDataState();
3622
+ browse.lastCommittedPage = this.config.paginationMode === 'page' && this.items.length > 0
3623
+ ? this.config.initialPage
3624
+ : undefined;
3625
+ browse.nextEligiblePosition = this.browseInitialPosition();
3626
+ browse.needsInitialRemoteSearch = false;
3627
+ this.browseState = browse;
3628
+ }
3381
3629
  }
3382
3630
  getSnapshot() {
3383
3631
  const activeRequest = this.active?.request ?? null;
@@ -3411,7 +3659,7 @@
3411
3659
  this.queryGeneration += 1;
3412
3660
  this.connected = true;
3413
3661
  this.hasConnected = true;
3414
- if (this.isRemoteMode() && this.needsInitialRemoteSearch) {
3662
+ if (this.isSearchEligible(this.query) && this.needsInitialRemoteSearch) {
3415
3663
  this.resetPaginationForRemoteQuery(true);
3416
3664
  const request = this.createSearchRequest();
3417
3665
  if (request)
@@ -3434,34 +3682,62 @@
3434
3682
  setQuery(query) {
3435
3683
  if (typeof query !== 'string' || query === this.query)
3436
3684
  return immutableActions([]);
3685
+ if (!this.isRemoteMode()) {
3686
+ const actions = [];
3687
+ const cancellation = this.invalidateActive('query-changed');
3688
+ if (cancellation)
3689
+ actions.push(cancellation);
3690
+ this.query = query;
3691
+ this.queryGeneration += 1;
3692
+ this.resetQueryMetadata();
3693
+ this.lastCommittedPage = this.config.paginationMode === 'page' && this.items.length > 0
3694
+ ? this.config.initialPage
3695
+ : undefined;
3696
+ this.nextEligiblePosition = this.initialPosition();
3697
+ this.needsInitialRemoteSearch = false;
3698
+ return immutableActions(actions);
3699
+ }
3437
3700
  const actions = [];
3438
- const cancellation = this.invalidateActive('query-changed');
3439
- if (cancellation)
3440
- actions.push(cancellation);
3701
+ const wasSearchEligible = this.isSearchEligible(this.query);
3702
+ const willSearchBeEligible = this.isSearchEligible(query);
3703
+ const activeKind = this.active?.request.kind;
3704
+ // Edits that remain below threshold are presentation-only while browsing.
3705
+ // Do not cancel a legitimate unfiltered loadMore operation for those edits.
3706
+ const preserveBrowseLoad = !wasSearchEligible && !willSearchBeEligible && activeKind === 'loadMore';
3707
+ const enteringSearch = !wasSearchEligible && willSearchBeEligible;
3708
+ if (enteringSearch || !preserveBrowseLoad) {
3709
+ const cancellation = this.invalidateActive('query-changed');
3710
+ if (cancellation)
3711
+ actions.push(cancellation);
3712
+ }
3713
+ if (enteringSearch)
3714
+ this.browseState = this.captureDataState();
3441
3715
  this.query = query;
3442
- this.queryGeneration += 1;
3443
- this.error = null;
3444
- this.status = 'idle';
3445
- this.generationHasAcceptedResult = false;
3446
- this.retryAvailable = false;
3447
- this.retryPosition = undefined;
3448
- this.retryKind = undefined;
3449
- this.committedCursors.clear();
3450
- this.resourceLimit = null;
3451
- this.sentinelBlocked = false;
3452
- if (this.isRemoteMode()) {
3453
- this.resetPaginationForRemoteQuery(true);
3454
- this.needsInitialRemoteSearch = true;
3455
- if (this.connected) {
3456
- const request = this.createSearchRequest();
3457
- if (request)
3458
- actions.push(Object.freeze({ type: 'request', request }));
3459
- }
3716
+ // Below-threshold edits do not change browse request ownership. Keep the
3717
+ // generation stable while an unfiltered loadMore is in flight so its valid
3718
+ // completion is not made stale by presentation-only input.
3719
+ if (!preserveBrowseLoad)
3720
+ this.queryGeneration += 1;
3721
+ if (!wasSearchEligible && !willSearchBeEligible) {
3722
+ this.error = null;
3723
+ if (!this.active)
3724
+ this.status = 'idle';
3725
+ // Current state remains the unfiltered browse state. Keep its pagination
3726
+ // and accepted items intact while the user edits a short query.
3727
+ return immutableActions(actions);
3460
3728
  }
3461
- else {
3462
- this.lastCommittedPage = this.config.paginationMode === 'page' ? this.config.initialPage : undefined;
3463
- this.nextEligiblePosition = this.initialPosition();
3729
+ if (wasSearchEligible && !willSearchBeEligible) {
3730
+ this.restoreBrowseState();
3464
3731
  this.needsInitialRemoteSearch = false;
3732
+ return immutableActions(actions);
3733
+ }
3734
+ this.resetQueryMetadata();
3735
+ this.resetPaginationForRemoteQuery(true);
3736
+ this.needsInitialRemoteSearch = true;
3737
+ if (this.connected) {
3738
+ const request = this.createSearchRequest();
3739
+ if (request)
3740
+ actions.push(Object.freeze({ type: 'request', request }));
3465
3741
  }
3466
3742
  return immutableActions(actions);
3467
3743
  }
@@ -3487,12 +3763,43 @@
3487
3763
  const protocolChanged = previous.protocol !== next.protocol ||
3488
3764
  previous.searchMode !== next.searchMode ||
3489
3765
  previous.paginationMode !== next.paginationMode;
3766
+ const thresholdChanged = previous.minSearchCharacters !== next.minSearchCharacters;
3490
3767
  this.rawConfig = copyCoordinatorConfig(candidate);
3491
3768
  this.config = next;
3492
- if (!protocolChanged) {
3769
+ if (!protocolChanged && !thresholdChanged) {
3493
3770
  this.refreshCursorDepthLimit();
3494
3771
  return Object.freeze({ status: 'accepted', actions: immutableActions([]) });
3495
3772
  }
3773
+ if (!protocolChanged && thresholdChanged) {
3774
+ const wasEligible = this.isSearchEligible(this.query, previous);
3775
+ const willBeEligible = this.isSearchEligible(this.query, next);
3776
+ if (wasEligible === willBeEligible) {
3777
+ this.refreshCursorDepthLimit();
3778
+ return Object.freeze({ status: 'accepted', actions: immutableActions([]) });
3779
+ }
3780
+ const actions = [];
3781
+ const cancellation = this.invalidateActive('config-changed');
3782
+ if (cancellation)
3783
+ actions.push(cancellation);
3784
+ this.queryGeneration += 1;
3785
+ if (wasEligible && !willBeEligible) {
3786
+ this.resetQueryMetadata();
3787
+ this.restoreBrowseState();
3788
+ this.needsInitialRemoteSearch = false;
3789
+ }
3790
+ else {
3791
+ this.browseState = this.captureDataState();
3792
+ this.resetQueryMetadata();
3793
+ this.resetPaginationForRemoteQuery(true);
3794
+ this.needsInitialRemoteSearch = true;
3795
+ if (this.connected) {
3796
+ const request = this.createSearchRequest();
3797
+ if (request)
3798
+ actions.push(Object.freeze({ type: 'request', request }));
3799
+ }
3800
+ }
3801
+ return Object.freeze({ status: 'accepted', actions: immutableActions(actions) });
3802
+ }
3496
3803
  const actions = [];
3497
3804
  const cancellation = this.invalidateActive('config-changed');
3498
3805
  if (cancellation)
@@ -3508,12 +3815,13 @@
3508
3815
  this.resourceLimit = null;
3509
3816
  this.sentinelBlocked = false;
3510
3817
  this.hasMore = this.isRemoteMode() ? false : this.hasMore;
3511
- this.lastCommittedPage = this.config.paginationMode === 'page' && !this.isRemoteMode()
3818
+ this.lastCommittedPage = this.config.paginationMode === 'page' && !this.isRemoteMode() && this.items.length > 0
3512
3819
  ? this.config.initialPage
3513
3820
  : undefined;
3514
3821
  this.nextEligiblePosition = this.initialPosition();
3515
3822
  this.needsInitialRemoteSearch = this.isRemoteMode();
3516
- if (this.connected && this.isRemoteMode()) {
3823
+ this.browseState = null;
3824
+ if (this.connected && this.isSearchEligible(this.query)) {
3517
3825
  const request = this.createSearchRequest();
3518
3826
  if (request)
3519
3827
  actions.push(Object.freeze({ type: 'request', request }));
@@ -3704,13 +4012,93 @@
3704
4012
  isRemoteMode() {
3705
4013
  return this.config.searchMode === 'remote' || this.config.searchMode === 'hybrid';
3706
4014
  }
4015
+ isSearchEligible(query, config = this.config) {
4016
+ if (config.protocol !== 'acknowledged' ||
4017
+ (config.searchMode !== 'remote' && config.searchMode !== 'hybrid'))
4018
+ return true;
4019
+ return Array.from(query.trim()).length >= config.minSearchCharacters;
4020
+ }
4021
+ captureDataState() {
4022
+ return {
4023
+ items: this.items,
4024
+ hasMore: this.hasMore,
4025
+ status: this.status,
4026
+ lastCommittedPage: this.lastCommittedPage,
4027
+ nextEligiblePosition: this.nextEligiblePosition,
4028
+ committedCursors: new Set(this.committedCursors),
4029
+ generationHasAcceptedResult: this.generationHasAcceptedResult,
4030
+ needsInitialRemoteSearch: this.needsInitialRemoteSearch,
4031
+ retryAvailable: this.retryAvailable,
4032
+ retryPosition: this.retryPosition,
4033
+ retryKind: this.retryKind,
4034
+ error: this.error,
4035
+ resourceLimit: this.resourceLimit,
4036
+ sentinelBlocked: this.sentinelBlocked,
4037
+ };
4038
+ }
4039
+ restoreBrowseState() {
4040
+ if (this.browseState) {
4041
+ const state = this.browseState;
4042
+ this.items = state.items;
4043
+ this.hasMore = state.hasMore;
4044
+ this.status = state.status;
4045
+ this.lastCommittedPage = state.lastCommittedPage;
4046
+ this.nextEligiblePosition = state.nextEligiblePosition;
4047
+ this.committedCursors = new Set(state.committedCursors);
4048
+ this.generationHasAcceptedResult = state.generationHasAcceptedResult;
4049
+ this.needsInitialRemoteSearch = state.needsInitialRemoteSearch;
4050
+ this.retryAvailable = state.retryAvailable;
4051
+ this.retryPosition = state.retryPosition;
4052
+ this.retryKind = state.retryKind;
4053
+ this.error = state.error;
4054
+ this.resourceLimit = state.resourceLimit;
4055
+ this.sentinelBlocked = state.sentinelBlocked;
4056
+ this.browseState = null;
4057
+ return;
4058
+ }
4059
+ this.items = asFrozenItems([]);
4060
+ this.hasMore = false;
4061
+ this.status = 'idle';
4062
+ this.lastCommittedPage = undefined;
4063
+ this.nextEligiblePosition = this.browseInitialPosition();
4064
+ this.committedCursors.clear();
4065
+ this.generationHasAcceptedResult = false;
4066
+ this.retryAvailable = false;
4067
+ this.retryPosition = undefined;
4068
+ this.retryKind = undefined;
4069
+ this.error = null;
4070
+ this.resourceLimit = null;
4071
+ this.sentinelBlocked = false;
4072
+ }
4073
+ resetQueryMetadata() {
4074
+ this.error = null;
4075
+ this.status = 'idle';
4076
+ this.generationHasAcceptedResult = false;
4077
+ this.retryAvailable = false;
4078
+ this.retryPosition = undefined;
4079
+ this.retryKind = undefined;
4080
+ this.committedCursors.clear();
4081
+ this.resourceLimit = null;
4082
+ this.sentinelBlocked = false;
4083
+ }
3707
4084
  initialPosition() {
3708
4085
  if (this.config.paginationMode === 'cursor') {
3709
4086
  return Object.freeze({ mode: 'cursor', ordinal: 1 });
3710
4087
  }
3711
- const page = this.isRemoteMode() ? this.config.firstPage : this.config.initialPage + 1;
4088
+ const page = this.isRemoteMode() && this.isSearchEligible(this.query)
4089
+ ? this.config.firstPage
4090
+ : this.items.length > 0 ? this.config.initialPage + 1 : this.config.initialPage;
3712
4091
  return Object.freeze({ mode: 'page', page });
3713
4092
  }
4093
+ browseInitialPosition() {
4094
+ if (this.config.paginationMode === 'cursor') {
4095
+ return Object.freeze({ mode: 'cursor', ordinal: 1 });
4096
+ }
4097
+ return Object.freeze({
4098
+ mode: 'page',
4099
+ page: this.items.length > 0 ? this.config.initialPage + 1 : this.config.initialPage,
4100
+ });
4101
+ }
3714
4102
  resetPaginationForRemoteQuery(clearItems) {
3715
4103
  this.hasMore = false;
3716
4104
  this.lastCommittedPage = undefined;
@@ -3751,7 +4139,10 @@
3751
4139
  }
3752
4140
  }
3753
4141
  createSearchRequest(position = this.nextEligiblePosition) {
3754
- if (!this.connected || !this.isRemoteMode() || this.config.protocol !== 'acknowledged')
4142
+ if (!this.connected
4143
+ || !this.isRemoteMode()
4144
+ || this.config.protocol !== 'acknowledged'
4145
+ || !this.isSearchEligible(this.query))
3755
4146
  return null;
3756
4147
  const request = this.createRequest({ kind: 'search', mode: this.config.searchMode }, position);
3757
4148
  if (request) {
@@ -3774,12 +4165,17 @@
3774
4165
  return null;
3775
4166
  this.requestSequence += 1;
3776
4167
  const check = requestIdCheck(this.requestIdSecret, this.instanceId, this.queryGeneration, this.requestSequence);
4168
+ const requestQuery = kind.kind === 'loadMore'
4169
+ && this.isRemoteMode()
4170
+ && !this.isSearchEligible(this.query)
4171
+ ? ''
4172
+ : this.query;
3777
4173
  const requestId = `data-${this.instanceId}-generation-${this.queryGeneration}-request-${this.requestSequence}-${check}`;
3778
4174
  const base = Object.freeze({
3779
4175
  requestId,
3780
4176
  queryGeneration: this.queryGeneration,
3781
- query: this.query,
3782
- normalizedQuery: this.query.trim(),
4177
+ query: requestQuery,
4178
+ normalizedQuery: requestQuery.trim(),
3783
4179
  fetchLimit,
3784
4180
  position: frozenPosition(position),
3785
4181
  });
@@ -3949,8 +4345,11 @@
3949
4345
  searchMode: 'local',
3950
4346
  paginationMode: 'page',
3951
4347
  firstPage: 1,
4348
+ minSearchCharacters: 0,
3952
4349
  };
3953
- const DATA_LOADING_CONFIG_FIELDS = ['protocol', 'searchMode', 'paginationMode', 'firstPage', 'fetchLimit'];
4350
+ const DATA_LOADING_CONFIG_FIELDS = [
4351
+ 'protocol', 'searchMode', 'paginationMode', 'firstPage', 'fetchLimit', 'minSearchCharacters',
4352
+ ];
3954
4353
  const INVALID_OBJECT_VALUE = Object.freeze({ kind: 'object' });
3955
4354
  const INVALID_ARRAY_VALUE = Object.freeze({ kind: 'array' });
3956
4355
  const INVALID_FUNCTION_VALUE = Object.freeze({ kind: 'function' });
@@ -4069,8 +4468,27 @@
4069
4468
  filteredIndices: [],
4070
4469
  filteredKeys: [],
4071
4470
  intendedRenderKeys: [],
4471
+ displayIndexByKey: new Map(),
4472
+ sourceIndexByKey: new Map(),
4072
4473
  filteredIndexByKey: new Map(),
4474
+ groupedPresentation: [],
4475
+ };
4476
+ // Presentation policy and membership are snapshotted when the dropdown opens
4477
+ // so selection/config updates cannot reorder an active list.
4478
+ this._selectedOptionsSelectionAtOpen = null;
4479
+ this._selectedOptionsConfigAtOpen = {
4480
+ placement: 'original',
4481
+ groupedPlacement: 'within-group',
4073
4482
  };
4483
+ this._scrollToSelectedConfigAtOpen = {
4484
+ enabled: true,
4485
+ multiSelectTarget: 'first',
4486
+ onOpen: 'reveal',
4487
+ behavior: 'smooth',
4488
+ block: 'nearest',
4489
+ };
4490
+ this._closedOptionsViewportAnchor = null;
4491
+ this._openOptionsViewportAnchor = null;
4074
4492
  this._emptyStateContext = null;
4075
4493
  // Null keeps the public/default renderer on its legacy full path. This
4076
4494
  // private state is only used by guarded virtualization integration.
@@ -4127,7 +4545,7 @@
4127
4545
  this._boundArrowClick = null;
4128
4546
  this._pendingFirstRenderMark = false;
4129
4547
  this._pendingSearchRenderMark = false;
4130
- this._rangeAnchorIndex = null;
4548
+ this._rangeAnchorKey = null;
4131
4549
  /** Chip identity is tracked independently of dropdown option positions. */
4132
4550
  this._lastRenderedChipKeys = null;
4133
4551
  this._latestChipScrollGeneration = 0;
@@ -4145,6 +4563,9 @@
4145
4563
  this._lifecycleTimers = new Set();
4146
4564
  this._lifecycleRafs = new Set();
4147
4565
  this._keyboardActiveChangeGeneration = 0;
4566
+ /** Invalidates selected-option positioning scheduled by an earlier opening. */
4567
+ this._openSelectedScrollGeneration = 0;
4568
+ this._openSelectedScrollCleanup = null;
4148
4569
  this._tracking = { events: [], styles: [], limitations: [] };
4149
4570
  this._suppressBlurClose = false;
4150
4571
  this._renderCycleId = 0;
@@ -4322,6 +4743,7 @@
4322
4743
  this._syncListboxAccessibility();
4323
4744
  }
4324
4745
  disconnectedCallback() {
4746
+ this._cancelOpenSelectedScroll();
4325
4747
  this._cancelLatestChipScroll();
4326
4748
  this._cancelBusyPresentation();
4327
4749
  if (this._dataRequestCoordinator) {
@@ -4908,12 +5330,12 @@
4908
5330
  duplicateKeyPolicy: this._getDuplicateKeyPolicy(),
4909
5331
  });
4910
5332
  const activeKey = this._engine.state.activeKey;
4911
- const anchorKey = this._rangeAnchorIndex === null ? undefined : this._itemRegistry.indexToKey.get(this._rangeAnchorIndex);
5333
+ const anchorKey = this._rangeAnchorKey;
4912
5334
  this._itemRegistry = registry;
4913
5335
  this._state.loadedItems = items;
4914
5336
  this._registryItemsRef = items;
4915
5337
  const disabledKeys = this._getBlockedDisabledKeys();
4916
- this._rangeAnchorIndex = anchorKey === undefined ? null : registry.keyToIndex.get(anchorKey) ?? null;
5338
+ this._rangeAnchorKey = anchorKey !== null && registry.keyToRecord.has(anchorKey) ? anchorKey : null;
4917
5339
  this._engine.dispatch({
4918
5340
  type: 'ITEMS_REGISTERED',
4919
5341
  keys: registry.records.map((record) => record.key),
@@ -6162,7 +6584,7 @@
6162
6584
  ───────────────────────────────────────────────────────────────────────── */
6163
6585
 
6164
6586
  .dropdown-arrow-container {
6165
- position: absolute;
6587
+ position: var(--select-arrow-container-position, absolute);
6166
6588
  top: 0;
6167
6589
  right: 0;
6168
6590
  bottom: 0;
@@ -6471,7 +6893,7 @@
6471
6893
  font-weight: var(--select-group-header-weight, 600);
6472
6894
  color: var(--select-group-header-color, var(--select-text-muted));
6473
6895
  background: var(--select-group-header-bg, #f3f4f6);
6474
- text-align: var(--select-group-header-text-align, left);
6896
+ text-align: var(--select-group-header-text-align, start);
6475
6897
  font-size: var(--select-group-header-font-size, 0.7333em);
6476
6898
  text-transform: var(--select-group-header-text-transform, uppercase);
6477
6899
  letter-spacing: var(--select-group-header-letter-spacing, 0.08em);
@@ -7458,6 +7880,15 @@
7458
7880
  this._dropdown.removeAttribute('inert');
7459
7881
  this._dropdown.removeAttribute('aria-hidden');
7460
7882
  this._markOpenStart();
7883
+ this._scrollToSelectedConfigAtOpen = { ...this._config.scrollToSelected };
7884
+ this._openOptionsViewportAnchor = this._scrollToSelectedConfigAtOpen.onOpen === 'preserve'
7885
+ ? (this._closedOptionsViewportAnchor ?? this._captureOptionsViewportAnchor())
7886
+ : null;
7887
+ this._closedOptionsViewportAnchor = null;
7888
+ this._selectedOptionsConfigAtOpen = { ...this._config.selectedOptions };
7889
+ this._selectedOptionsSelectionAtOpen = this._config.selectedOptions.placement === 'selected-first'
7890
+ ? new Set(this._engine.state.selectedKeys)
7891
+ : null;
7461
7892
  this.setAttribute('data-open', 'true');
7462
7893
  this._liftStackingAncestors();
7463
7894
  this._dropdown.style.display = 'block';
@@ -7469,28 +7900,17 @@
7469
7900
  this._emit('open', {});
7470
7901
  this._config.callbacks.onOpen?.();
7471
7902
  this._announce('Options expanded');
7472
- // Scroll to selected if configured
7473
- if (this._config.scrollToSelected.enabled) {
7474
- const keyboardActiveChangeGeneration = this._keyboardActiveChangeGeneration;
7475
- const canRestoreOpenSelection = () => this._state.isOpen
7476
- && this._keyboardActiveChangeGeneration === keyboardActiveChangeGeneration;
7477
- // Use requestAnimationFrame for better timing after render
7478
- this._requestLifecycleFrame(() => {
7479
- if (!canRestoreOpenSelection())
7480
- return;
7481
- // Double RAF to ensure layout is complete
7482
- this._requestLifecycleFrame(() => {
7483
- if (!canRestoreOpenSelection())
7484
- return;
7485
- this._scrollToSelected();
7486
- });
7487
- });
7488
- }
7903
+ this._scheduleOpenSelectedScroll();
7489
7904
  }
7490
7905
  _handleClose(reason = 'programmatic') {
7906
+ if (this._state.isOpen) {
7907
+ this._closedOptionsViewportAnchor = this._captureOptionsViewportAnchor();
7908
+ }
7491
7909
  const effects = this._engine.dispatch({ type: 'CLOSE_REQUEST', reason });
7492
7910
  if (!effects.some((effect) => effect.type === 'POPUP_CLOSED'))
7493
7911
  return;
7912
+ this._cancelOpenSelectedScroll();
7913
+ this._selectedOptionsSelectionAtOpen = null;
7494
7914
  this.removeAttribute('data-open');
7495
7915
  this._restoreLiftedAncestors();
7496
7916
  this._dropdown.setAttribute('data-placement', this._resolvedDropdownPlacement);
@@ -7502,6 +7922,257 @@
7502
7922
  this._config.callbacks.onClose?.();
7503
7923
  this._announce('Options collapsed');
7504
7924
  }
7925
+ /**
7926
+ * Defer the one automatic selected-option positioning operation until the
7927
+ * dropdown's own entrance geometry has settled. Logical active/ARIA state
7928
+ * remains synchronous in _setInitialActiveOption().
7929
+ */
7930
+ _scheduleOpenSelectedScroll() {
7931
+ this._cancelOpenSelectedScroll();
7932
+ const openingConfig = this._scrollToSelectedConfigAtOpen;
7933
+ if (!openingConfig.enabled)
7934
+ return;
7935
+ const generation = this._openSelectedScrollGeneration;
7936
+ const keyboardGeneration = this._keyboardActiveChangeGeneration;
7937
+ const initialScrollTop = this._optionsContainer.scrollTop;
7938
+ const animations = [];
7939
+ const frameIds = new Set();
7940
+ let timerId = null;
7941
+ let completed = false;
7942
+ const isCurrent = () => generation === this._openSelectedScrollGeneration
7943
+ && this._state.isOpen
7944
+ && this.isConnected
7945
+ && this._config.scrollToSelected.enabled
7946
+ && keyboardGeneration === this._keyboardActiveChangeGeneration;
7947
+ const removeListeners = () => {
7948
+ this._optionsContainer.removeEventListener('wheel', cancelForUserInput);
7949
+ this._optionsContainer.removeEventListener('touchstart', cancelForUserInput);
7950
+ this._optionsContainer.removeEventListener('pointerdown', cancelForUserInput);
7951
+ this._optionsContainer.removeEventListener('scroll', cancelForUserScroll);
7952
+ for (const animation of animations) {
7953
+ animation.removeEventListener('finish', onAnimationStateChange);
7954
+ animation.removeEventListener('cancel', onAnimationStateChange);
7955
+ }
7956
+ };
7957
+ const cleanup = () => {
7958
+ removeListeners();
7959
+ for (const id of frameIds)
7960
+ cancelAnimationFrame(id);
7961
+ frameIds.clear();
7962
+ if (timerId !== null) {
7963
+ clearTimeout(timerId);
7964
+ this._lifecycleTimers.delete(timerId);
7965
+ timerId = null;
7966
+ }
7967
+ if (this._openSelectedScrollCleanup === cleanup) {
7968
+ this._openSelectedScrollCleanup = null;
7969
+ }
7970
+ };
7971
+ const cancelForUserInput = () => this._cancelOpenSelectedScroll();
7972
+ const cancelForUserScroll = () => {
7973
+ if (Math.abs(this._optionsContainer.scrollTop - initialScrollTop) > 1) {
7974
+ this._cancelOpenSelectedScroll();
7975
+ }
7976
+ };
7977
+ const finish = () => {
7978
+ if (completed)
7979
+ return;
7980
+ completed = true;
7981
+ cleanup();
7982
+ if (!isCurrent())
7983
+ return;
7984
+ const frameId = requestAnimationFrame(() => {
7985
+ frameIds.delete(frameId);
7986
+ cleanup();
7987
+ if (!isCurrent())
7988
+ return;
7989
+ if (openingConfig.onOpen === 'preserve') {
7990
+ this._restorePreservedOptionsViewport();
7991
+ }
7992
+ else {
7993
+ this._scrollToSelected({
7994
+ onlyIfNeeded: openingConfig.onOpen === 'reveal',
7995
+ setActive: false,
7996
+ config: openingConfig,
7997
+ });
7998
+ }
7999
+ });
8000
+ frameIds.add(frameId);
8001
+ this._openSelectedScrollCleanup = cleanup;
8002
+ };
8003
+ const onAnimationStateChange = () => {
8004
+ if (animations.every((animation) => animation.playState === 'finished' || animation.playState === 'idle'))
8005
+ finish();
8006
+ };
8007
+ const begin = () => {
8008
+ if (!isCurrent()) {
8009
+ cleanup();
8010
+ return;
8011
+ }
8012
+ const getAnimations = this._dropdown.getAnimations;
8013
+ const reducedMotion = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches ?? false;
8014
+ if (!reducedMotion && typeof getAnimations === 'function') {
8015
+ for (const animation of getAnimations.call(this._dropdown)) {
8016
+ const timing = animation.effect?.getComputedTiming();
8017
+ if (!timing || timing.iterations === Infinity || animation.playState === 'finished'
8018
+ || animation.playState === 'idle')
8019
+ continue;
8020
+ animations.push(animation);
8021
+ }
8022
+ }
8023
+ if (animations.length === 0) {
8024
+ if (!reducedMotion && typeof getAnimations !== 'function') {
8025
+ const fallbackWait = this._getDropdownEntranceFallbackDurationMs();
8026
+ if (fallbackWait > 0) {
8027
+ timerId = window.setTimeout(finish, fallbackWait + 34);
8028
+ this._lifecycleTimers.add(timerId);
8029
+ return;
8030
+ }
8031
+ }
8032
+ finish();
8033
+ return;
8034
+ }
8035
+ for (const animation of animations) {
8036
+ animation.addEventListener('finish', onAnimationStateChange);
8037
+ animation.addEventListener('cancel', onAnimationStateChange);
8038
+ }
8039
+ const remainingMs = Math.max(...animations.map((animation) => {
8040
+ const timing = animation.effect?.getComputedTiming();
8041
+ const endTime = Number(timing?.endTime);
8042
+ const currentTime = Number(animation.currentTime ?? 0);
8043
+ return Number.isFinite(endTime) ? Math.max(0, endTime - currentTime) : 0;
8044
+ }));
8045
+ const boundedWait = Math.min(10000, remainingMs + 50);
8046
+ timerId = window.setTimeout(finish, boundedWait);
8047
+ this._lifecycleTimers.add(timerId);
8048
+ };
8049
+ this._optionsContainer.addEventListener('wheel', cancelForUserInput, { passive: true });
8050
+ this._optionsContainer.addEventListener('touchstart', cancelForUserInput, { passive: true });
8051
+ this._optionsContainer.addEventListener('pointerdown', cancelForUserInput, { passive: true });
8052
+ this._optionsContainer.addEventListener('scroll', cancelForUserScroll, { passive: true });
8053
+ this._openSelectedScrollCleanup = cleanup;
8054
+ const frameId = requestAnimationFrame(() => {
8055
+ frameIds.delete(frameId);
8056
+ begin();
8057
+ });
8058
+ frameIds.add(frameId);
8059
+ }
8060
+ _cancelOpenSelectedScroll() {
8061
+ this._openSelectedScrollGeneration += 1;
8062
+ this._openSelectedScrollCleanup?.();
8063
+ this._openSelectedScrollCleanup = null;
8064
+ }
8065
+ _captureOptionsViewportAnchor() {
8066
+ const scroller = this._optionsContainer;
8067
+ const scrollTop = scroller.scrollTop;
8068
+ const order = this._renderPlan.filteredKeys.slice();
8069
+ const viewportTop = scroller.getBoundingClientRect().top + scroller.clientTop;
8070
+ const viewportBottom = viewportTop + scroller.clientHeight;
8071
+ const visible = Array.from(scroller.querySelectorAll('[data-sm-selectable], [data-selectable]'))
8072
+ .map((option) => ({ option, rect: option.getBoundingClientRect() }))
8073
+ .filter(({ rect }) => rect.height > 0 && rect.bottom > viewportTop && rect.top < viewportBottom)
8074
+ .sort((left, right) => left.rect.top - right.rect.top)[0];
8075
+ if (visible) {
8076
+ const sourceIndex = Number(visible.option.getAttribute('data-sm-index') ?? visible.option.getAttribute('data-index'));
8077
+ const key = Number.isInteger(sourceIndex) ? this._itemRegistry.indexToKey.get(sourceIndex) ?? null : null;
8078
+ if (key !== null) {
8079
+ return { key, offset: visible.rect.top - viewportTop, scrollTop, order };
8080
+ }
8081
+ }
8082
+ if (this._guardedVirtualizer && order.length > 0
8083
+ && typeof this._guardedVirtualizer.computeWindow === 'function') {
8084
+ const viewportHeight = this._resolveGuardedViewportHeight();
8085
+ const index = this._guardedVirtualizer.computeWindow(scrollTop, viewportHeight).startIndex;
8086
+ const key = order[index] ?? null;
8087
+ if (key !== null) {
8088
+ return {
8089
+ key,
8090
+ offset: this._guardedVirtualizer.cumulativeOffset(index) - scrollTop,
8091
+ scrollTop,
8092
+ order,
8093
+ };
8094
+ }
8095
+ }
8096
+ return { key: null, offset: 0, scrollTop, order };
8097
+ }
8098
+ /** Restore the previous visible option only when this opening changed order. */
8099
+ _restorePreservedOptionsViewport() {
8100
+ const anchor = this._openOptionsViewportAnchor;
8101
+ this._openOptionsViewportAnchor = null;
8102
+ if (!anchor)
8103
+ return;
8104
+ const nextOrder = this._renderPlan.filteredKeys;
8105
+ const nextPositionByKey = new Map(nextOrder.map((key, index) => [key, index]));
8106
+ const orderChanged = anchor.order.some((key, oldIndex) => {
8107
+ const nextIndex = nextPositionByKey.get(key);
8108
+ return nextIndex !== undefined && nextIndex !== oldIndex;
8109
+ });
8110
+ if (!orderChanged)
8111
+ return;
8112
+ const scroller = this._optionsContainer;
8113
+ const viewportHeight = this._resolveGuardedViewportHeight() || scroller.clientHeight;
8114
+ let targetScrollTop = null;
8115
+ if (anchor.key !== null) {
8116
+ const displayIndex = this._renderPlan.displayIndexByKey.get(anchor.key);
8117
+ if (displayIndex !== undefined) {
8118
+ const sourceIndex = this._renderPlan.sourceIndexByKey.get(anchor.key);
8119
+ const option = sourceIndex === undefined ? null : this._getOptionElementByIndex(sourceIndex);
8120
+ const viewportTop = scroller.getBoundingClientRect().top + scroller.clientTop;
8121
+ const optionTop = option?.getBoundingClientRect().top;
8122
+ if (option && option.getBoundingClientRect().height > 0 && Number.isFinite(optionTop)) {
8123
+ targetScrollTop = scroller.scrollTop + optionTop - viewportTop - anchor.offset;
8124
+ }
8125
+ else if (this._guardedVirtualizer) {
8126
+ targetScrollTop = this._guardedVirtualizer.cumulativeOffset(displayIndex) - anchor.offset;
8127
+ }
8128
+ }
8129
+ }
8130
+ if (targetScrollTop === null)
8131
+ targetScrollTop = anchor.scrollTop;
8132
+ let maxScrollTop = Number.POSITIVE_INFINITY;
8133
+ if (this._guardedVirtualizer) {
8134
+ maxScrollTop = Math.max(0, this._guardedVirtualizer.cumulativeOffset(nextOrder.length) - viewportHeight);
8135
+ }
8136
+ else if (scroller.scrollHeight > 0 && scroller.clientHeight > 0) {
8137
+ maxScrollTop = Math.max(0, scroller.scrollHeight - scroller.clientHeight);
8138
+ }
8139
+ targetScrollTop = Math.max(0, Math.min(targetScrollTop, maxScrollTop));
8140
+ if (Math.abs(targetScrollTop - scroller.scrollTop) < 1)
8141
+ return;
8142
+ // The coordinator owns this single restoration write. The virtualizer may
8143
+ // update its mounted window in response, but it must not issue a second
8144
+ // physical positioning correction for this transaction.
8145
+ this._guardedVirtualScrollTop = targetScrollTop;
8146
+ scroller.scrollTop = targetScrollTop;
8147
+ }
8148
+ /** Used only when Element.getAnimations() is unavailable. */
8149
+ _getDropdownEntranceFallbackDurationMs() {
8150
+ if (window.matchMedia?.('(prefers-reduced-motion: reduce)').matches)
8151
+ return 0;
8152
+ const style = getComputedStyle(this._dropdown);
8153
+ const parseTime = (value) => {
8154
+ const trimmed = value.trim();
8155
+ const parsed = Number.parseFloat(trimmed);
8156
+ if (!Number.isFinite(parsed))
8157
+ return 0;
8158
+ return trimmed.endsWith('ms') ? parsed : trimmed.endsWith('s') ? parsed * 1000 : 0;
8159
+ };
8160
+ const animationDurations = style.animationDuration.split(',');
8161
+ const animationDelays = style.animationDelay.split(',');
8162
+ const animationIterations = style.animationIterationCount.split(',');
8163
+ const maxAnimation = Math.max(0, ...animationDurations.map((duration, index) => {
8164
+ const count = Number.parseFloat(animationIterations[index % animationIterations.length] ?? '1');
8165
+ if (!Number.isFinite(count))
8166
+ return 0;
8167
+ return parseTime(duration)
8168
+ * Math.max(0, count)
8169
+ + parseTime(animationDelays[index % animationDelays.length] ?? '0s');
8170
+ }));
8171
+ const transitionDurations = style.transitionDuration.split(',');
8172
+ const transitionDelays = style.transitionDelay.split(',');
8173
+ const maxTransition = Math.max(0, ...transitionDurations.map((duration, index) => parseTime(duration) + parseTime(transitionDelays[index % transitionDelays.length] ?? '0s')));
8174
+ return Math.min(10000, Math.max(maxAnimation, maxTransition));
8175
+ }
7505
8176
  /** Stop an outstanding exit before reopening, disconnecting or starting another one. */
7506
8177
  _cancelDropdownExit() {
7507
8178
  if (this._dropdownExitTimer !== null) {
@@ -7740,16 +8411,40 @@
7740
8411
  }
7741
8412
  if (this._dataLoadingConfig.protocol === 'acknowledged'
7742
8413
  && (this._dataLoadingConfig.searchMode === 'remote' || this._dataLoadingConfig.searchMode === 'hybrid')) {
8414
+ const wasEligible = Array.from(this._state.searchQuery.trim()).length
8415
+ >= this._dataLoadingConfig.minSearchCharacters;
8416
+ const isEligible = Array.from(query.trim()).length >= this._dataLoadingConfig.minSearchCharacters;
8417
+ if (wasEligible && !isEligible)
8418
+ this._cancelBusyPresentation();
7743
8419
  this._state.searchQuery = query;
7744
8420
  this._syncClearControlState();
7745
8421
  this._state.lastNotifiedQuery = query;
7746
8422
  this._state.lastNotifiedResultCount = 0;
7747
8423
  if (this._dataRequestCoordinator) {
8424
+ const beforeSnapshot = this._dataRequestCoordinator.getSnapshot();
7748
8425
  const actions = this._dataRequestCoordinator.setQuery(query);
7749
8426
  if (this._acknowledgedReady)
7750
8427
  this._dispatchAcknowledgedActions(actions);
7751
- else
8428
+ const startsRequest = actions.some((action) => action.type === 'request');
8429
+ if (this._acknowledgedReady && !startsRequest) {
8430
+ const snapshot = this._dataRequestCoordinator.getSnapshot();
8431
+ const restoredDataChanged = beforeSnapshot.items.length !== snapshot.items.length
8432
+ || beforeSnapshot.items.some((item, index) => item !== snapshot.items[index])
8433
+ || beforeSnapshot.hasMore !== snapshot.hasMore
8434
+ || JSON.stringify(beforeSnapshot.nextEligiblePosition) !== JSON.stringify(snapshot.nextEligiblePosition);
8435
+ this._state.isBusy = snapshot.busy || this._acknowledgedProjectionPending;
8436
+ this._state.isSearching = snapshot.activeRequest?.kind === 'search';
8437
+ this._syncListboxAccessibility();
8438
+ if (actions.some((action) => action.type === 'cancel') || restoredDataChanged) {
8439
+ void this._projectAcknowledgedSnapshot(snapshot, null, false);
8440
+ }
8441
+ else {
8442
+ this._renderOptions();
8443
+ }
8444
+ }
8445
+ else if (!this._acknowledgedReady) {
7752
8446
  this._renderOptions();
8447
+ }
7753
8448
  }
7754
8449
  else if (!this._state.isOpen) {
7755
8450
  this._handleOpen();
@@ -7832,26 +8527,38 @@
7832
8527
  case 'Home':
7833
8528
  e.preventDefault();
7834
8529
  if (this._state.isOpen) {
8530
+ if (this._usesSelectedFirstVisualOrder()) {
8531
+ this._moveToVisualBoundary('first', { shiftKey: e.shiftKey, toggleKey: e.ctrlKey || e.metaKey });
8532
+ break;
8533
+ }
7835
8534
  const selectableIndices = this._getSelectableOptionIndices();
7836
8535
  const firstIndex = selectableIndices[0];
7837
8536
  if (firstIndex === undefined)
7838
8537
  break;
7839
8538
  this._setActive(firstIndex);
7840
8539
  if (this._config.selection.mode === 'multi' && e.shiftKey) {
7841
- this._selectRange(this._rangeAnchorIndex ?? firstIndex, firstIndex, { clear: !(e.ctrlKey || e.metaKey) });
8540
+ const targetKey = this._itemRegistry.indexToKey.get(firstIndex);
8541
+ if (targetKey !== undefined)
8542
+ this._selectKeyboardRange(this._rangeAnchorKey ?? targetKey, targetKey, { clear: !(e.ctrlKey || e.metaKey) });
7842
8543
  }
7843
8544
  }
7844
8545
  break;
7845
8546
  case 'End':
7846
8547
  e.preventDefault();
7847
8548
  if (this._state.isOpen) {
8549
+ if (this._usesSelectedFirstVisualOrder()) {
8550
+ this._moveToVisualBoundary('last', { shiftKey: e.shiftKey, toggleKey: e.ctrlKey || e.metaKey });
8551
+ break;
8552
+ }
7848
8553
  const selectableIndices = this._getSelectableOptionIndices();
7849
8554
  const lastIndex = selectableIndices[selectableIndices.length - 1];
7850
8555
  if (lastIndex === undefined)
7851
8556
  break;
7852
8557
  this._setActive(lastIndex);
7853
8558
  if (this._config.selection.mode === 'multi' && e.shiftKey) {
7854
- this._selectRange(this._rangeAnchorIndex ?? lastIndex, lastIndex, { clear: !(e.ctrlKey || e.metaKey) });
8559
+ const targetKey = this._itemRegistry.indexToKey.get(lastIndex);
8560
+ if (targetKey !== undefined)
8561
+ this._selectKeyboardRange(this._rangeAnchorKey ?? targetKey, targetKey, { clear: !(e.ctrlKey || e.metaKey) });
7855
8562
  }
7856
8563
  }
7857
8564
  break;
@@ -7906,6 +8613,26 @@
7906
8613
  }
7907
8614
  }
7908
8615
  _moveActive(delta, opts) {
8616
+ if (this._usesSelectedFirstVisualOrder()) {
8617
+ const model = this._getVisualNavigationModel();
8618
+ if (model.selectableKeys.length === 0)
8619
+ return;
8620
+ const activeKey = this._engine.state.activeKey;
8621
+ const currentPosition = activeKey === null ? undefined : model.selectablePositionByKey.get(activeKey);
8622
+ // Load-more is only requested after movement reaches the actual visual end.
8623
+ if (delta === 1 && currentPosition === model.selectableKeys.length - 1 && this._requestKeyboardLoadMore())
8624
+ return;
8625
+ const nextKey = resolveVisualMovement(model, activeKey, delta);
8626
+ if (nextKey === null)
8627
+ return;
8628
+ this._setActiveForVisualKey(nextKey);
8629
+ if (this._config.selection.mode === 'multi' && opts?.shiftKey) {
8630
+ const anchorKey = this._rangeAnchorKey ?? activeKey ?? nextKey;
8631
+ this._rangeAnchorKey = anchorKey;
8632
+ this._selectKeyboardRange(anchorKey, nextKey, { clear: !opts.toggleKey });
8633
+ }
8634
+ return;
8635
+ }
7909
8636
  const selectableIndices = this._getSelectableOptionIndices();
7910
8637
  if (selectableIndices.length === 0)
7911
8638
  return;
@@ -7927,14 +8654,90 @@
7927
8654
  const next = selectableIndices[nextPosition];
7928
8655
  this._setActive(next);
7929
8656
  if (this._config.selection.mode === 'multi' && opts?.shiftKey) {
7930
- const anchor = this._rangeAnchorIndex ?? currentIndex;
7931
- const anchorIndex = anchor >= 0 ? anchor : next;
7932
- if (this._rangeAnchorIndex === null) {
7933
- this._rangeAnchorIndex = anchorIndex;
7934
- }
7935
- this._selectRange(anchorIndex, next, { clear: !opts?.toggleKey });
8657
+ const nextKey = this._itemRegistry.indexToKey.get(next);
8658
+ if (nextKey === undefined)
8659
+ return;
8660
+ const anchorKey = this._rangeAnchorKey ?? (currentIndex >= 0 ? this._itemRegistry.indexToKey.get(currentIndex) : undefined) ?? nextKey;
8661
+ this._rangeAnchorKey = anchorKey;
8662
+ this._selectKeyboardRange(anchorKey, nextKey, { clear: !opts?.toggleKey });
7936
8663
  }
7937
8664
  }
8665
+ _usesSelectedFirstVisualOrder() {
8666
+ return this._selectedOptionsConfigAtOpen.placement === 'selected-first';
8667
+ }
8668
+ _getVisualNavigationModel() {
8669
+ this._ensureRegistryCurrent();
8670
+ return createVisualNavigationModel(this._renderPlan.filteredKeys, (key) => {
8671
+ const record = this._itemRegistry.keyToRecord.get(key);
8672
+ if (!record || record.disabled)
8673
+ return false;
8674
+ const option = this._getOptionElementByIndex(record.index);
8675
+ return option?.getAttribute('aria-disabled') !== 'true';
8676
+ });
8677
+ }
8678
+ _setActiveForVisualKey(key, reason = 'keyboard', options = {}) {
8679
+ const sourceIndex = this._renderPlan.sourceIndexByKey.get(key)
8680
+ ?? this._itemRegistry.keyToIndex.get(key);
8681
+ if (sourceIndex === undefined)
8682
+ return;
8683
+ this._setActive(sourceIndex, reason, options);
8684
+ }
8685
+ _moveToVisualBoundary(boundary, opts) {
8686
+ const model = this._getVisualNavigationModel();
8687
+ const targetKey = resolveVisualBoundary(model, boundary);
8688
+ if (targetKey === null)
8689
+ return;
8690
+ const currentKey = this._engine.state.activeKey;
8691
+ this._setActiveForVisualKey(targetKey);
8692
+ if (this._config.selection.mode === 'multi' && opts?.shiftKey) {
8693
+ const anchorKey = this._rangeAnchorKey ?? currentKey ?? targetKey;
8694
+ this._rangeAnchorKey = anchorKey;
8695
+ this._selectKeyboardRange(anchorKey, targetKey, { clear: !opts.toggleKey });
8696
+ }
8697
+ }
8698
+ _selectKeyboardRange(anchorKey, targetKey, opts) {
8699
+ if (this._usesSelectedFirstVisualOrder()) {
8700
+ const model = this._getVisualNavigationModel();
8701
+ const resolvedAnchor = model.selectablePositionByKey.has(anchorKey) ? anchorKey : targetKey;
8702
+ this._rangeAnchorKey = resolvedAnchor;
8703
+ this._selectVisualRange(resolvedAnchor, targetKey, opts);
8704
+ return;
8705
+ }
8706
+ const start = this._itemRegistry.keyToIndex.get(anchorKey);
8707
+ const end = this._itemRegistry.keyToIndex.get(targetKey);
8708
+ if (start !== undefined && end !== undefined)
8709
+ this._selectRange(start, end, opts);
8710
+ }
8711
+ _selectVisualRange(anchorKey, targetKey, opts) {
8712
+ if (this._config.selection.mode !== 'multi')
8713
+ return;
8714
+ this._ensureRegistryCurrent();
8715
+ const model = this._getVisualNavigationModel();
8716
+ const rangeKeys = resolveVisualRange(model, anchorKey, targetKey);
8717
+ if (rangeKeys.length === 0)
8718
+ return;
8719
+ const selectedEntries = this._getSelectedEntries();
8720
+ const entries = opts?.clear
8721
+ ? selectedEntries.filter((entry) => !this._itemRegistry.keyToRecord.has(entry.key))
8722
+ : selectedEntries;
8723
+ for (const key of rangeKeys) {
8724
+ const record = this._itemRegistry.keyToRecord.get(key);
8725
+ if (!record || this._isOptionSelectionBlocked(record.item))
8726
+ continue;
8727
+ entries.push(record);
8728
+ }
8729
+ this._requestSelectionReplacement(entries, opts?.reason ?? 'keyboard', 'select visual range');
8730
+ this._renderOptions();
8731
+ this._updateInputDisplay();
8732
+ const target = this._itemRegistry.keyToRecord.get(targetKey);
8733
+ const selectDetail = target ? this._getSelectEventDetail(target) : null;
8734
+ if (selectDetail)
8735
+ this._emit('select', selectDetail);
8736
+ this._emitChange();
8737
+ this._announce(`${this._state.selectedIndices.size} items selected`);
8738
+ if (selectDetail)
8739
+ this._config.callbacks.onSelect?.(selectDetail);
8740
+ }
7938
8741
  /** Return true only when boundary navigation is held for an in-flight/new page. */
7939
8742
  _requestKeyboardLoadMore() {
7940
8743
  if (!this._state.isOpen
@@ -7962,7 +8765,7 @@
7962
8765
  this._dispatchAcknowledgedActions(actions);
7963
8766
  return true;
7964
8767
  }
7965
- _setActive(index, reason = 'keyboard') {
8768
+ _setActive(index, reason = 'keyboard', options = {}) {
7966
8769
  this._ensureRegistryCurrent();
7967
8770
  const record = this._getRecordByIndex(index);
7968
8771
  let option = this._getOptionElementByIndex(index);
@@ -7973,8 +8776,10 @@
7973
8776
  if (!record || record.disabled || !option || option.getAttribute('aria-disabled') === 'true') {
7974
8777
  return;
7975
8778
  }
7976
- if (reason === 'keyboard')
8779
+ if (reason === 'keyboard' || reason === 'search') {
7977
8780
  this._keyboardActiveChangeGeneration += 1;
8781
+ this._cancelOpenSelectedScroll();
8782
+ }
7978
8783
  const previousIndex = this._state.activeIndex;
7979
8784
  this._dispatchActiveKey(record.key, reason, 'set active');
7980
8785
  if (this._state.activeIndex !== index)
@@ -8001,8 +8806,7 @@
8001
8806
  else {
8002
8807
  this._syncCustomOptionActiveClasses(option, true);
8003
8808
  }
8004
- if (typeof option.scrollIntoView === 'function') {
8005
- // Don't scroll wildly when just opening with pre-selections
8809
+ if (options.scroll !== false && typeof option.scrollIntoView === 'function') {
8006
8810
  option.scrollIntoView({ block: 'nearest', behavior: 'smooth' });
8007
8811
  }
8008
8812
  // Announce position for screen readers
@@ -8058,8 +8862,22 @@
8058
8862
  this._typeTimeout = window.setTimeout(() => {
8059
8863
  this._typeBuffer = '';
8060
8864
  }, 500);
8061
- // Find first matching option
8865
+ // Type-ahead uses the displayed candidate order when a presentation projection is active.
8062
8866
  const getValue = this._config.serverSide.getLabelFromItem || ((item) => item?.label ?? String(item));
8867
+ if (this._usesSelectedFirstVisualOrder()) {
8868
+ const model = this._getVisualNavigationModel();
8869
+ const matchKey = model.selectableKeys.find((key) => {
8870
+ const record = this._itemRegistry.keyToRecord.get(key);
8871
+ return record !== undefined && getValue(record.item).toLowerCase().startsWith(this._typeBuffer);
8872
+ });
8873
+ if (matchKey !== undefined) {
8874
+ const sourceIndex = this._renderPlan.sourceIndexByKey.get(matchKey)
8875
+ ?? this._itemRegistry.keyToIndex.get(matchKey);
8876
+ if (sourceIndex !== undefined)
8877
+ this._setActive(sourceIndex, 'search');
8878
+ }
8879
+ return;
8880
+ }
8063
8881
  const matchIndex = this._state.loadedItems.findIndex((item) => getValue(item).toLowerCase().startsWith(this._typeBuffer));
8064
8882
  if (matchIndex >= 0) {
8065
8883
  this._setActive(matchIndex, 'search');
@@ -8128,6 +8946,17 @@
8128
8946
  };
8129
8947
  }
8130
8948
  _setInitialActiveOption() {
8949
+ if (this._usesSelectedFirstVisualOrder()) {
8950
+ const model = this._getVisualNavigationModel();
8951
+ const selectedKey = model.selectableKeys.find((key) => this._engine.state.selectedKeys.has(key));
8952
+ if (selectedKey === undefined) {
8953
+ this._dispatchActiveKey(null, 'open', 'initial active option');
8954
+ return;
8955
+ }
8956
+ // Resolve via stable identity so the open-time projection remains authoritative.
8957
+ this._setActiveForVisualKey(selectedKey, 'open', { scroll: false });
8958
+ return;
8959
+ }
8131
8960
  const selectableIndices = this._getSelectableOptionIndices();
8132
8961
  const selected = Array.from(this._state.selectedIndices).sort((a, b) => a - b);
8133
8962
  // Opening an empty select must not implicitly assign an active descendant.
@@ -8137,7 +8966,9 @@
8137
8966
  return;
8138
8967
  }
8139
8968
  const target = selected.find((index) => selectableIndices.includes(index)) ?? selectableIndices[0];
8140
- this._setActive(target, 'open');
8969
+ // Set logical active state and ARIA immediately. The open-time coordinator
8970
+ // owns any physical positioning after the dropdown's entrance settles.
8971
+ this._setActive(target, 'open', { scroll: false });
8141
8972
  }
8142
8973
  _announce(message) {
8143
8974
  const effects = computeAccessibilityEffects(deriveAccessibilityState(this._engine.state), {
@@ -8191,9 +9022,10 @@
8191
9022
  const toggleKey = Boolean(opts?.toggleKey);
8192
9023
  const shiftKey = Boolean(opts?.shiftKey);
8193
9024
  if (shiftKey) {
8194
- const anchor = this._rangeAnchorIndex ?? index;
8195
- this._selectRange(anchor, index, { clear: !toggleKey, reason });
8196
- this._rangeAnchorIndex = anchor;
9025
+ const targetKey = record.key;
9026
+ const anchorKey = this._rangeAnchorKey ?? targetKey;
9027
+ this._selectKeyboardRange(anchorKey, targetKey, { clear: !toggleKey, reason });
9028
+ this._rangeAnchorKey = anchorKey;
8197
9029
  return;
8198
9030
  }
8199
9031
  // Multi select with toggle
@@ -8207,7 +9039,7 @@
8207
9039
  // Re-render to update styles (safer than trying to find the element in filtered list)
8208
9040
  this._renderOptions();
8209
9041
  }
8210
- this._rangeAnchorIndex = index;
9042
+ this._rangeAnchorKey = record.key;
8211
9043
  this._updateInputDisplay();
8212
9044
  const selectDetail = this._getSelectEventDetail(record);
8213
9045
  this._emit('select', selectDetail);
@@ -8466,58 +9298,71 @@
8466
9298
  this._optionsContainer.style.transition = 'opacity 0.2s ease-in';
8467
9299
  }, 150);
8468
9300
  }
8469
- _scrollToSelected() {
8470
- if (this._state.selectedIndices.size === 0)
8471
- return;
8472
- const target = this._config.scrollToSelected.multiSelectTarget;
8473
- const indices = Array.from(this._state.selectedIndices).filter((index) => index >= 0).sort((a, b) => a - b);
8474
- if (indices.length === 0)
8475
- return;
8476
- // For multi-select, find the closest selected item to the current scroll position
8477
- let targetIndex;
8478
- if (this._config.selection.mode === 'multi' && indices.length > 1) {
8479
- // Calculate which selected item is closest to the center of the viewport
8480
- const dropdownRect = this._dropdown.getBoundingClientRect();
8481
- const viewportCenter = this._dropdown.scrollTop + (dropdownRect.height / 2);
8482
- // Find the selected item closest to viewport center
8483
- let closestIndex = indices[0];
8484
- let closestDistance = Infinity;
8485
- for (const index of indices) {
8486
- const option = this._getOptionElementByIndex(index);
8487
- if (option) {
8488
- const optionTop = option.offsetTop;
8489
- const distance = Math.abs(optionTop - viewportCenter);
8490
- if (distance < closestDistance) {
8491
- closestDistance = distance;
8492
- closestIndex = index;
8493
- }
8494
- }
8495
- }
8496
- targetIndex = closestIndex;
8497
- }
8498
- else {
8499
- // For single select or only one selected item, use the configured target
8500
- targetIndex = target === 'first' ? indices[0] : indices[indices.length - 1];
8501
- }
8502
- // Find and scroll to the target option
9301
+ _scrollToSelected(options = {}) {
9302
+ const config = options.config ?? this._config.scrollToSelected;
9303
+ if (!config.enabled)
9304
+ return;
9305
+ const targetKey = resolveSelectedTargetKey(this._renderPlan.filteredKeys, this._engine.state.selectedKeys, config.multiSelectTarget);
9306
+ if (targetKey === null)
9307
+ return;
9308
+ const targetIndex = this._renderPlan.sourceIndexByKey.get(targetKey)
9309
+ ?? this._itemRegistry.keyToIndex.get(targetKey);
9310
+ if (targetIndex === undefined)
9311
+ return;
9312
+ // Resolve against the current eligible render plan first. A selected key
9313
+ // outside the filtered projection must never trigger materialization.
8503
9314
  let option = this._getOptionElementByIndex(targetIndex);
8504
9315
  if (!option && this._guardedVirtualizer) {
8505
- const targetKey = this._itemRegistry.indexToKey.get(targetIndex);
8506
- if (targetKey !== undefined) {
8507
- this._materializeGuardedVirtualKey(targetKey);
8508
- option = this._getOptionElementByIndex(targetIndex);
8509
- }
9316
+ this._materializeGuardedVirtualKey(targetKey);
9317
+ option = this._getOptionElementByIndex(targetIndex);
8510
9318
  }
8511
9319
  if (option) {
8512
- // Use smooth scrolling with center alignment for better UX
8513
- if (typeof option.scrollIntoView === 'function') {
8514
- option.scrollIntoView({
8515
- block: this._config.scrollToSelected.block || 'center',
8516
- behavior: 'smooth',
8517
- });
9320
+ const reducedMotion = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches ?? false;
9321
+ this._scrollOptionWithinOptionsContainer(option, config.block || 'nearest', reducedMotion && config.behavior === 'smooth' ? 'auto' : (config.behavior || 'smooth'), options.onlyIfNeeded === true);
9322
+ if (options.setActive !== false) {
9323
+ // Active/ARIA synchronization must not start a second physical scroll.
9324
+ this._setActive(targetIndex, 'programmatic', { scroll: false });
8518
9325
  }
8519
- // Also set it as active for keyboard navigation
8520
- this._setActive(targetIndex, 'programmatic');
9326
+ }
9327
+ }
9328
+ _scrollOptionWithinOptionsContainer(option, block, behavior, onlyIfNeeded) {
9329
+ const scroller = this._optionsContainer;
9330
+ const scrollerRect = scroller.getBoundingClientRect();
9331
+ const viewportTop = scrollerRect.top + scroller.clientTop;
9332
+ const viewportBottom = viewportTop + scroller.clientHeight;
9333
+ const optionRect = option.getBoundingClientRect();
9334
+ if (onlyIfNeeded && optionRect.top >= viewportTop && optionRect.bottom <= viewportBottom)
9335
+ return;
9336
+ if (scroller.clientHeight <= 0 || optionRect.height <= 0)
9337
+ return;
9338
+ let targetScrollTop = scroller.scrollTop;
9339
+ if (block === 'start') {
9340
+ targetScrollTop += optionRect.top - viewportTop;
9341
+ }
9342
+ else if (block === 'center') {
9343
+ targetScrollTop += (optionRect.top + optionRect.bottom - viewportTop - viewportBottom) / 2;
9344
+ }
9345
+ else if (block === 'end') {
9346
+ targetScrollTop += optionRect.bottom - viewportBottom;
9347
+ }
9348
+ else if (optionRect.top < viewportTop) {
9349
+ targetScrollTop += optionRect.top - viewportTop;
9350
+ }
9351
+ else if (optionRect.bottom > viewportBottom) {
9352
+ targetScrollTop += optionRect.bottom - viewportBottom;
9353
+ }
9354
+ else {
9355
+ return;
9356
+ }
9357
+ const maxScrollTop = Math.max(0, scroller.scrollHeight - scroller.clientHeight);
9358
+ targetScrollTop = Math.max(0, Math.min(targetScrollTop, maxScrollTop));
9359
+ if (Math.abs(targetScrollTop - scroller.scrollTop) < 1)
9360
+ return;
9361
+ if (typeof scroller.scrollTo === 'function') {
9362
+ scroller.scrollTo({ top: targetScrollTop, behavior });
9363
+ }
9364
+ else {
9365
+ scroller.scrollTop = targetScrollTop;
8521
9366
  }
8522
9367
  }
8523
9368
  async _loadMoreItems(trigger = 'manual') {
@@ -8967,6 +9812,13 @@
8967
9812
  * Clear search query and restore full option list
8968
9813
  */
8969
9814
  clearSearch() {
9815
+ if (this._dataLoadingConfig.protocol === 'acknowledged'
9816
+ && (this._dataLoadingConfig.searchMode === 'remote' || this._dataLoadingConfig.searchMode === 'hybrid')
9817
+ && this._dataRequestCoordinator) {
9818
+ this._input.value = '';
9819
+ this._handleSearch('');
9820
+ return;
9821
+ }
8970
9822
  this._state.searchQuery = '';
8971
9823
  if (this._config.searchable) {
8972
9824
  this._input.value = '';
@@ -8996,9 +9848,21 @@
8996
9848
  this._invalidateGuardedMeasurements();
8997
9849
  const previousMode = this._config.selection.mode;
8998
9850
  const previousEnabled = this._config.enabled;
9851
+ const previousOpenScrollEnabled = this._config.scrollToSelected.enabled;
8999
9852
  const previousDataLoadingConfig = this._dataLoadingConfig;
9000
- const { dataLoading, callbacks, ...legacyConfig } = config;
9853
+ let searchEligibilityBecameInactive = false;
9854
+ const { dataLoading, callbacks, selectedOptions, scrollToSelected, ...legacyConfig } = config;
9001
9855
  const legacyUpdate = { ...legacyConfig };
9856
+ if (selectedOptions !== undefined) {
9857
+ const validation = validateSelectedOptionsConfig(selectedOptions);
9858
+ if (validation.valid)
9859
+ legacyUpdate.selectedOptions = validation.value;
9860
+ }
9861
+ if (scrollToSelected !== undefined) {
9862
+ const validation = validateScrollToSelectedConfig(scrollToSelected);
9863
+ if (validation.valid)
9864
+ legacyUpdate.scrollToSelected = validation.value;
9865
+ }
9002
9866
  let configErrorDetail;
9003
9867
  if (callbacks !== undefined && callbacks !== null) {
9004
9868
  const callbackInput = callbacks;
@@ -9018,6 +9882,10 @@
9018
9882
  legacyUpdate.callbacks = legacyCallbacks;
9019
9883
  }
9020
9884
  this._config = this._mergeConfig(this._config, legacyUpdate);
9885
+ if (previousOpenScrollEnabled && !this._config.scrollToSelected.enabled) {
9886
+ this._openOptionsViewportAnchor = null;
9887
+ this._cancelOpenSelectedScroll();
9888
+ }
9021
9889
  if (dataLoading !== undefined) {
9022
9890
  const dataLoadingPrototype = dataLoading !== null && typeof dataLoading === 'object'
9023
9891
  ? Object.getPrototypeOf(dataLoading)
@@ -9027,6 +9895,13 @@
9027
9895
  : dataLoading;
9028
9896
  const validation = validateDataLoadingConfig(candidate);
9029
9897
  if (validation.valid) {
9898
+ const wasRemoteEligible = previousDataLoadingConfig.protocol === 'acknowledged'
9899
+ && (previousDataLoadingConfig.searchMode === 'remote' || previousDataLoadingConfig.searchMode === 'hybrid')
9900
+ && Array.from(this._state.searchQuery.trim()).length >= previousDataLoadingConfig.minSearchCharacters;
9901
+ const becomesRemoteEligible = validation.value.protocol === 'acknowledged'
9902
+ && (validation.value.searchMode === 'remote' || validation.value.searchMode === 'hybrid')
9903
+ && Array.from(this._state.searchQuery.trim()).length >= validation.value.minSearchCharacters;
9904
+ searchEligibilityBecameInactive = wasRemoteEligible && !becomesRemoteEligible;
9030
9905
  this._dataLoadingConfig = validation.value;
9031
9906
  this._hasLastInvalidDataLoadingCandidate = false;
9032
9907
  this._lastInvalidDataLoadingCandidate = undefined;
@@ -9114,6 +9989,8 @@
9114
9989
  const acknowledgedModeChanged = previousDataLoadingConfig.protocol !== this._dataLoadingConfig.protocol
9115
9990
  || previousDataLoadingConfig.searchMode !== this._dataLoadingConfig.searchMode
9116
9991
  || previousDataLoadingConfig.paginationMode !== this._dataLoadingConfig.paginationMode;
9992
+ if (searchEligibilityBecameInactive)
9993
+ this._cancelBusyPresentation();
9117
9994
  if (coordinator && switchesToLegacy) {
9118
9995
  if (this._acknowledgedReady && !this._acknowledgedProjectionPending && !this._acknowledgedProjectionSettling) {
9119
9996
  const update = coordinator.updateConfig(this._createCoordinatorConfig());
@@ -9148,8 +10025,14 @@
9148
10025
  this._state.isBusy = snapshot.busy;
9149
10026
  this._state.isSearching = snapshot.activeRequest?.kind === 'search';
9150
10027
  this._syncListboxAccessibility();
9151
- if (update.actions.every((action) => action.type !== 'request'))
9152
- this._renderOptions();
10028
+ if (update.actions.every((action) => action.type !== 'request')) {
10029
+ if (this._acknowledgedSnapshotDiffersFromLoadedItems(snapshot)) {
10030
+ this._reconcileAcknowledgedSnapshot(snapshot);
10031
+ }
10032
+ else {
10033
+ this._renderOptions();
10034
+ }
10035
+ }
9153
10036
  }
9154
10037
  }
9155
10038
  }
@@ -9308,14 +10191,12 @@
9308
10191
  }
9309
10192
  _ensureDataRequestCoordinator() {
9310
10193
  if (!this._dataRequestCoordinator) {
9311
- const isRemote = this._dataLoadingConfig.searchMode === 'remote'
9312
- || this._dataLoadingConfig.searchMode === 'hybrid';
9313
10194
  try {
9314
10195
  this._dataRequestCoordinator = new DataRequestCoordinator({
9315
10196
  config: this._createCoordinatorConfig(),
9316
10197
  initialQuery: this._state.searchQuery,
9317
10198
  initialItems: this._state.loadedItems,
9318
- hasMore: !isRemote && (this._config.infiniteScroll.enabled || this._config.loadMore.enabled),
10199
+ hasMore: this._config.infiniteScroll.enabled || this._config.loadMore.enabled,
9319
10200
  });
9320
10201
  }
9321
10202
  catch (error) {
@@ -9551,19 +10432,39 @@
9551
10432
  activeKey: this._engine.state.activeKey,
9552
10433
  };
9553
10434
  }
9554
- _createLegacyRenderPlan(filteredIndices) {
9555
- const indices = [...filteredIndices];
9556
- const filteredKeys = indices
9557
- .map((index) => this._itemRegistry.indexToKey.get(index))
9558
- .filter((key) => key !== undefined);
9559
- const filteredIndexByKey = new Map();
9560
- filteredKeys.forEach((key, filteredIndex) => filteredIndexByKey.set(key, filteredIndex));
10435
+ _createLegacyRenderPlan(filteredIndices, groupedPresentation = []) {
10436
+ const sourceIndices = [...filteredIndices];
10437
+ const sourceOrderedKeys = groupedPresentation.length > 0
10438
+ ? groupedPresentation.flatMap((group) => group.orderedKeys)
10439
+ : sourceIndices
10440
+ .map((index) => this._itemRegistry.indexToKey.get(index))
10441
+ .filter((key) => key !== undefined);
10442
+ const shouldProjectSelectedFirst = this._usesSelectedFirstVisualOrder()
10443
+ && groupedPresentation.length === 0;
10444
+ const selectedKeys = this._selectedOptionsSelectionAtOpen ?? this._engine.state.selectedKeys;
10445
+ const filteredKeys = shouldProjectSelectedFirst
10446
+ ? projectSelectedOptionKeys(sourceOrderedKeys, selectedKeys)
10447
+ : sourceOrderedKeys;
10448
+ const indices = filteredKeys
10449
+ .map((key) => this._itemRegistry.keyToIndex.get(key))
10450
+ .filter((index) => index !== undefined);
10451
+ const displayIndexByKey = new Map();
10452
+ const sourceIndexByKey = new Map();
10453
+ filteredKeys.forEach((key, displayIndex) => {
10454
+ displayIndexByKey.set(key, displayIndex);
10455
+ const sourceIndex = this._itemRegistry.keyToIndex.get(key);
10456
+ if (sourceIndex !== undefined)
10457
+ sourceIndexByKey.set(key, sourceIndex);
10458
+ });
9561
10459
  return {
9562
10460
  mode: 'legacy-full',
9563
10461
  filteredIndices: indices,
9564
10462
  filteredKeys,
9565
10463
  intendedRenderKeys: filteredKeys.slice(),
9566
- filteredIndexByKey,
10464
+ displayIndexByKey,
10465
+ sourceIndexByKey,
10466
+ filteredIndexByKey: displayIndexByKey,
10467
+ groupedPresentation,
9567
10468
  };
9568
10469
  }
9569
10470
  _createVirtualRenderPlan(startIndex, endIndex) {
@@ -9572,12 +10473,16 @@
9572
10473
  const filteredIndices = intendedRenderKeys
9573
10474
  .map((key) => this._itemRegistry.keyToIndex.get(key))
9574
10475
  .filter((index) => index !== undefined);
10476
+ const displayIndexByKey = new Map(this._renderPlan.displayIndexByKey);
9575
10477
  return {
9576
10478
  mode: 'virtual-window',
9577
10479
  filteredIndices,
9578
10480
  filteredKeys,
9579
10481
  intendedRenderKeys,
9580
- filteredIndexByKey: new Map(this._renderPlan.filteredIndexByKey),
10482
+ displayIndexByKey,
10483
+ sourceIndexByKey: new Map(this._renderPlan.sourceIndexByKey),
10484
+ filteredIndexByKey: displayIndexByKey,
10485
+ groupedPresentation: this._renderPlan.groupedPresentation,
9581
10486
  };
9582
10487
  }
9583
10488
  _ensureGuardedVirtualizer(filteredKeys) {
@@ -9725,6 +10630,7 @@
9725
10630
  searchMode: dataLoading?.searchMode ?? 'local',
9726
10631
  paginationMode: dataLoading?.paginationMode ?? 'page',
9727
10632
  firstPage: dataLoading?.firstPage ?? 1,
10633
+ minSearchCharacters: dataLoading?.minSearchCharacters ?? 0,
9728
10634
  ...(dataLoading?.fetchLimit === undefined ? {} : { fetchLimit: dataLoading.fetchLimit }),
9729
10635
  };
9730
10636
  this._acknowledgedSearchMode = config.dataLoading?.searchMode ?? 'local';
@@ -9779,6 +10685,12 @@
9779
10685
  for (const action of actions) {
9780
10686
  if (action.type === 'cancel') {
9781
10687
  this._cancelBusyPresentation();
10688
+ const snapshot = this._dataRequestCoordinator?.getSnapshot();
10689
+ if (snapshot) {
10690
+ this._state.isBusy = snapshot.busy || this._acknowledgedProjectionPending;
10691
+ this._state.isSearching = snapshot.activeRequest?.kind === 'search';
10692
+ this._syncListboxAccessibility();
10693
+ }
9782
10694
  this._dispatchAcknowledgedEvent('dataRequestCancel', action.notification);
9783
10695
  try {
9784
10696
  this._dataRequestCancelCallback?.(action.notification);
@@ -9864,6 +10776,34 @@
9864
10776
  return Promise.resolve();
9865
10777
  return this._projectAcknowledgedSnapshot(this._dataRequestCoordinator.getSnapshot(), this._acknowledgedProjectionRequest ?? this._acknowledgedLastRequest, this._acknowledgedProjectionCommitsPosition);
9866
10778
  }
10779
+ _acknowledgedSnapshotDiffersFromLoadedItems(snapshot) {
10780
+ const loadedItems = this._state.loadedItems;
10781
+ return loadedItems.length !== snapshot.items.length
10782
+ || loadedItems.some((item, index) => item !== snapshot.items[index]);
10783
+ }
10784
+ _reconcileAcknowledgedSnapshot(snapshot) {
10785
+ if (!this._acknowledgedSnapshotDiffersFromLoadedItems(snapshot))
10786
+ return;
10787
+ const activeProjection = this._acknowledgedProjectionTask;
10788
+ if (this._acknowledgedProjectionRunning && activeProjection) {
10789
+ // Deferred config is reconciled from inside the current projection's
10790
+ // settlement callback. Wait until that task releases its running guard,
10791
+ // then project the coordinator's latest accepted snapshot.
10792
+ void activeProjection.then(() => {
10793
+ if (!this.isConnected)
10794
+ return;
10795
+ const latestSnapshot = this._dataRequestCoordinator?.getSnapshot() ?? snapshot;
10796
+ if (this._acknowledgedSnapshotDiffersFromLoadedItems(latestSnapshot)) {
10797
+ void this._projectAcknowledgedSnapshot(latestSnapshot, null, false);
10798
+ }
10799
+ else {
10800
+ this._dispatchPendingAcknowledgedSearchIntent();
10801
+ }
10802
+ });
10803
+ return;
10804
+ }
10805
+ void this._projectAcknowledgedSnapshot(snapshot, null, false);
10806
+ }
9867
10807
  _projectAcknowledgedSnapshot(snapshot, request, commitPosition) {
9868
10808
  if (this._acknowledgedProjectionRunning) {
9869
10809
  return this._acknowledgedProjectionTask ?? Promise.resolve();
@@ -9920,7 +10860,10 @@
9920
10860
  }
9921
10861
  if (!this._state.searchQuery
9922
10862
  && this._acknowledgedPendingSearchQuery === null
9923
- && !this._isActivelyEditingSearchInput()) {
10863
+ && !this._isActivelyEditingSearchInput()
10864
+ && !(this._dataLoadingConfig.protocol === 'acknowledged'
10865
+ && (this._dataLoadingConfig.searchMode === 'remote' || this._dataLoadingConfig.searchMode === 'hybrid')
10866
+ && this._dataLoadingConfig.minSearchCharacters > 0)) {
9924
10867
  this._updateInputDisplay();
9925
10868
  }
9926
10869
  this._syncListboxAccessibility();
@@ -10083,6 +11026,11 @@
10083
11026
  this._state.isBusy = state.busy;
10084
11027
  this._state.isSearching = state.activeRequest?.kind === 'search';
10085
11028
  this._syncListboxAccessibility();
11029
+ if (update.actions.every((action) => action.type !== 'request')
11030
+ && this._acknowledgedSnapshotDiffersFromLoadedItems(state)) {
11031
+ this._reconcileAcknowledgedSnapshot(state);
11032
+ return;
11033
+ }
10086
11034
  }
10087
11035
  this._dispatchPendingAcknowledgedSearchIntent();
10088
11036
  }
@@ -10488,11 +11436,31 @@
10488
11436
  // Handle Grouped Items Rendering (when no search query)
10489
11437
  if (this._state.groupedItems.length > 0 && !query) {
10490
11438
  this._destroyGuardedVirtualizer();
10491
- this._renderPlan = this._createLegacyRenderPlan(this._itemRegistry.records.map((record) => record.index));
11439
+ const groupedSource = this._state.groupedItems.map((group, groupIndex) => ({
11440
+ group,
11441
+ groupIndex,
11442
+ orderedKeys: group.options
11443
+ .map((item) => this._state.loadedItems.indexOf(item))
11444
+ .filter((index) => index >= 0)
11445
+ .map((index) => this._itemRegistry.indexToKey.get(index))
11446
+ .filter((key) => key !== undefined),
11447
+ }));
11448
+ const groupedOrder = this._usesSelectedFirstVisualOrder()
11449
+ ? projectSelectedOptionGroups(groupedSource.map(({ groupIndex, orderedKeys }) => ({ groupIdentity: groupIndex, orderedKeys })), this._selectedOptionsSelectionAtOpen ?? this._engine.state.selectedKeys)
11450
+ : groupedSource.map(({ groupIndex, orderedKeys }) => ({ groupIdentity: groupIndex, orderedKeys }));
11451
+ const groupedPresentation = groupedOrder.map(({ groupIdentity, orderedKeys }) => ({
11452
+ group: this._state.groupedItems[groupIdentity],
11453
+ groupIndex: groupIdentity,
11454
+ orderedKeys,
11455
+ }));
11456
+ const groupedIndices = groupedPresentation.flatMap(({ orderedKeys }) => orderedKeys
11457
+ .map((key) => this._itemRegistry.keyToIndex.get(key))
11458
+ .filter((index) => index !== undefined));
11459
+ this._renderPlan = this._createLegacyRenderPlan(groupedIndices, groupedPresentation);
10492
11460
  filteredIndicesForScope = this._renderPlan.filteredIndices;
10493
11461
  this._registerShadowItems(filteredIndicesForScope);
10494
11462
  this._refreshVirtualizationScope(filteredIndicesForScope);
10495
- this._state.groupedItems.forEach((group, groupIndex) => {
11463
+ this._renderPlan.groupedPresentation.forEach(({ group, groupIndex, orderedKeys }) => {
10496
11464
  let header;
10497
11465
  if (this.groupHeaderRenderer) {
10498
11466
  header = this.groupHeaderRenderer(group, groupIndex);
@@ -10518,10 +11486,10 @@
10518
11486
  }
10519
11487
  header.setAttribute('part', 'group-header');
10520
11488
  this._optionsContainer.appendChild(header);
10521
- group.options.forEach(item => {
10522
- // Find original index for correct ID generation and selection
10523
- const index = this._state.loadedItems.indexOf(item);
10524
- if (index !== -1) {
11489
+ orderedKeys.forEach((key) => {
11490
+ const index = this._itemRegistry.keyToIndex.get(key);
11491
+ if (index !== undefined) {
11492
+ const item = this._state.loadedItems[index];
10525
11493
  this._renderSingleOption(item, index, getValue, getLabel);
10526
11494
  }
10527
11495
  });
@@ -10590,13 +11558,16 @@
10590
11558
  const chunkSize = 80;
10591
11559
  let cursor = 0;
10592
11560
  let maxRenderTarget = 0;
10593
- if (this._state.selectedIndices.size > 0 && this._config.scrollToSelected.enabled) {
10594
- const indices = Array.from(this._state.selectedIndices).filter((index) => index >= 0).sort((a, b) => a - b);
10595
- const targetIndex = this._config.scrollToSelected.multiSelectTarget === 'first' ? indices[0] : indices[indices.length - 1];
10596
- const filteredPos = filteredIndices.indexOf(targetIndex);
10597
- if (filteredPos !== -1) {
10598
- maxRenderTarget = filteredPos + 20; // Ensure we render up to the selection
10599
- }
11561
+ if (this._state.isOpen
11562
+ && this._config.scrollToSelected.enabled
11563
+ && this._scrollToSelectedConfigAtOpen.enabled
11564
+ && this._scrollToSelectedConfigAtOpen.onOpen !== 'preserve') {
11565
+ const targetKey = resolveSelectedTargetKey(this._renderPlan.filteredKeys, this._engine.state.selectedKeys, this._scrollToSelectedConfigAtOpen.multiSelectTarget);
11566
+ const targetPosition = targetKey === null
11567
+ ? undefined
11568
+ : this._renderPlan.displayIndexByKey.get(targetKey);
11569
+ if (targetPosition !== undefined)
11570
+ maxRenderTarget = targetPosition + 20;
10600
11571
  }
10601
11572
  const renderChunk = () => {
10602
11573
  if (renderCycleId !== this._renderCycleId) {
@@ -12106,6 +13077,9 @@
12106
13077
  exports.toggleClass = toggleClass;
12107
13078
  exports.transition = transition;
12108
13079
  exports.validateDataLoadingConfig = validateDataLoadingConfig;
13080
+ exports.validateScrollToSelectedConfig = validateScrollToSelectedConfig;
13081
+ exports.validateSelectedOptionsConfig = validateSelectedOptionsConfig;
13082
+ exports.validateSelectedOptionsConfigUpdate = validateSelectedOptionsConfigUpdate;
12109
13083
  exports.validateTemplate = validateTemplate;
12110
13084
  exports.valuesEqual = valuesEqual;
12111
13085
  exports.warnCSPViolation = warnCSPViolation;