svelte-5-select 1.0.2 → 2.0.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.
Files changed (36) hide show
  1. package/README.md +239 -109
  2. package/dist/ChevronIcon.svelte +8 -13
  3. package/dist/ClearIcon.svelte +3 -11
  4. package/dist/LoadingIcon.svelte +9 -2
  5. package/dist/Select.svelte +954 -436
  6. package/dist/Select.svelte.d.ts +37 -5
  7. package/dist/aria-handlers.svelte.d.ts +4 -1
  8. package/dist/aria-handlers.svelte.js +19 -8
  9. package/dist/filter.d.ts +10 -2
  10. package/dist/filter.js +14 -7
  11. package/dist/index.d.ts +2 -3
  12. package/dist/index.js +1 -2
  13. package/dist/keyboard-navigation.svelte.d.ts +7 -2
  14. package/dist/keyboard-navigation.svelte.js +285 -47
  15. package/dist/no-styles/ChevronIcon.svelte +11 -0
  16. package/dist/no-styles/ChevronIcon.svelte.d.ts +26 -0
  17. package/dist/no-styles/ClearIcon.svelte +8 -0
  18. package/dist/no-styles/ClearIcon.svelte.d.ts +26 -0
  19. package/dist/no-styles/LoadingIcon.svelte +13 -0
  20. package/dist/no-styles/LoadingIcon.svelte.d.ts +26 -0
  21. package/dist/no-styles/Select.svelte +1383 -0
  22. package/dist/no-styles/Select.svelte.d.ts +38 -0
  23. package/dist/select-state.svelte.d.ts +15 -0
  24. package/dist/select-state.svelte.js +161 -0
  25. package/dist/styles/default.css +112 -71
  26. package/dist/tailwind.css +120 -17
  27. package/dist/types.d.ts +459 -129
  28. package/dist/use-hover.svelte.d.ts +3 -7
  29. package/dist/use-hover.svelte.js +91 -36
  30. package/dist/use-load-options.svelte.d.ts +18 -3
  31. package/dist/use-load-options.svelte.js +333 -42
  32. package/dist/use-value.svelte.d.ts +2 -11
  33. package/dist/use-value.svelte.js +322 -111
  34. package/dist/utils.d.ts +19 -8
  35. package/dist/utils.js +52 -8
  36. package/package.json +117 -94
@@ -0,0 +1,1383 @@
1
+ <svelte:options runes={true} />
2
+
3
+ <!--
4
+ @component
5
+ A select/autocomplete/typeahead control: a WAI-ARIA combobox with a floating
6
+ listbox popup. Generic over your item type; supports multi-select, async
7
+ loading (`loadOptions`), grouping (`groupBy`), and snippet-based customization.
8
+ Bind `value` (and optionally `justValue`, `filterText`, `listOpen`, `focused`).
9
+ -->
10
+
11
+ <script lang="ts" generics="Item extends ItemLike = SelectItem, Multiple extends boolean = false">
12
+ import { onDestroy, onMount, tick, untrack } from 'svelte';
13
+ import { DEV } from 'esm-env';
14
+ import { offset, flip, shift } from 'svelte-floating-ui/dom';
15
+ import type {
16
+ FloatingConfig,
17
+ ItemLike,
18
+ SelectProps,
19
+ SelectRow,
20
+ SelectValue,
21
+ SelectClearValue,
22
+ SelectErrorEvent,
23
+ } from '../types';
24
+ import { createFloatingActions } from 'svelte-floating-ui';
25
+ import { useAriaHandlers } from '../aria-handlers.svelte';
26
+
27
+ import _filter from '../filter';
28
+
29
+ import ChevronIcon from './ChevronIcon.svelte';
30
+ import ClearIcon from './ClearIcon.svelte';
31
+ import LoadingIcon from './LoadingIcon.svelte';
32
+ import type { SelectItem } from '../types';
33
+ import type { HTMLInputAttributes } from 'svelte/elements';
34
+ import { createSelectState } from '../select-state.svelte';
35
+ import { useKeyboardNavigation } from '../keyboard-navigation.svelte';
36
+ import { useHover } from '../use-hover.svelte';
37
+ import { useValue } from '../use-value.svelte';
38
+ import { useLoadOptions } from '../use-load-options.svelte';
39
+ import {
40
+ areItemsEqual,
41
+ convertStringItemsToObjects,
42
+ getItemProperty,
43
+ isItemSelectableCheck,
44
+ normalizeItem,
45
+ createGroupHeaderItem as _createGroupHeaderItem,
46
+ } from '../utils';
47
+
48
+ const defaultItemFilter = (label: string, filterText: string, _option: SelectItem): boolean =>
49
+ `${label}`.toLowerCase().includes(filterText?.toLowerCase());
50
+
51
+ const defaultOnError = (_error: SelectErrorEvent): void => {};
52
+ const defaultOnLoaded = (_options: SelectItem[]): void => {};
53
+
54
+ let timeout = $state<ReturnType<typeof setTimeout>>();
55
+
56
+ let {
57
+ // Core data props
58
+ filterText = $bindable(''),
59
+ itemId = 'value',
60
+ items = $bindable<Item[] | string[] | null>(null),
61
+ justValue = $bindable(),
62
+ label = 'label',
63
+ value = $bindable(),
64
+
65
+ // UI props
66
+ disabled = false,
67
+ focused = $bindable(false),
68
+ hasError = false,
69
+ id = null,
70
+ listOpen = $bindable(false),
71
+ loading = $bindable(false),
72
+ name = null,
73
+ placeholder = 'Please select',
74
+ placeholderAlwaysShow = false,
75
+ showChevron = false,
76
+
77
+ // Behavior props
78
+ clearable = true,
79
+ clearFilterTextOnBlur = true,
80
+ closeListOnChange = true,
81
+ filterSelectedItems = true,
82
+ groupHeaderSelectable = false,
83
+ multiFullItemClearable = false,
84
+ multiple = false as Multiple,
85
+ required = false,
86
+ searchable = true,
87
+ useJustValue = false,
88
+
89
+ // Styling props
90
+ containerStyles = '',
91
+ inputStyles = '',
92
+ listStyles = '',
93
+ hideEmptyState = false,
94
+
95
+ // Advanced props
96
+ debounceWait = 300,
97
+ floatingConfig = {},
98
+ hoverItemIndex = $bindable(0),
99
+ inputAttributes = {},
100
+ listAutoWidth = true,
101
+ listOffset = 5,
102
+ loadOptionsDeps = [],
103
+
104
+ // Function props
105
+ createGroupHeaderItem = (groupValue: string, _item: Item) => {
106
+ return _createGroupHeaderItem(groupValue, label);
107
+ },
108
+ debounce = (fn: () => void, wait = 1) => {
109
+ clearTimeout(timeout);
110
+ timeout = setTimeout(fn, wait);
111
+ },
112
+ filter = _filter,
113
+ groupBy = undefined,
114
+ groupFilter = (groups: string[]) => groups,
115
+ itemFilter = defaultItemFilter,
116
+ loadOptions = undefined,
117
+
118
+ // ARIA props
119
+ ariaLabel = undefined,
120
+ ariaErrorMessage = undefined,
121
+ ariaClearSelectLabel = 'Clear selection',
122
+ ariaRemoveItemLabel = (label: string) => `Remove ${label}`,
123
+ ariaCleared = () => {
124
+ return `Selection cleared.`;
125
+ },
126
+ ariaEmpty = () => {
127
+ return `No options`;
128
+ },
129
+ ariaFocused = () => {
130
+ // In select-only mode (searchable={false}) the input is readonly, so
131
+ // "type to refine" would instruct an action that does nothing
132
+ return searchable
133
+ ? `Select is focused, type to refine list, press down to open the menu.`
134
+ : `Select is focused, press down to open the menu.`;
135
+ },
136
+ ariaListOpen = (label: string, count: number) => {
137
+ return `You are currently focused on option ${label}. There are ${count} results available.`;
138
+ },
139
+ ariaLoading = () => {
140
+ return `Loading Data`;
141
+ },
142
+ ariaValues = (values: string) => {
143
+ return `Option ${values}, selected.`;
144
+ },
145
+
146
+ // Custom behavior
147
+ handleClear = internalHandleClear,
148
+
149
+ // Event handlers
150
+ onblur = () => {},
151
+ onclear = () => {},
152
+ onerror = defaultOnError,
153
+ onfilter = () => {},
154
+ onfocus = () => {},
155
+ onhoveritem = () => {},
156
+ onloaded = defaultOnLoaded,
157
+ onselect = () => {},
158
+ onSelectionChange = () => {},
159
+ onValueChange = () => {},
160
+
161
+ // Snippet props
162
+ chevronIconSnippet,
163
+ clearIconSnippet,
164
+ emptySnippet,
165
+ inputHiddenSnippet,
166
+ itemSnippet,
167
+ listAppendSnippet,
168
+ listPrependSnippet,
169
+ listSnippet,
170
+ prependSnippet,
171
+ loadingIconSnippet,
172
+ multiClearIconSnippet,
173
+ requiredSnippet,
174
+ selectionSnippet,
175
+
176
+ // DOM references (for binding)
177
+ container = $bindable(undefined),
178
+ input = $bindable(undefined),
179
+ ...rest
180
+ }: SelectProps<Item, Multiple> = $props();
181
+
182
+ let normalizedValue = $derived<SelectItem | SelectItem[] | null>(normalizeItem(value));
183
+
184
+ const _uid = $props.id();
185
+ const _generatedId = `svelte-select-${_uid}`;
186
+ let _id = $derived(id ?? _generatedId);
187
+
188
+ // Group headers render as options only when they are selectable; otherwise they are presentational
189
+ const isPresentationalHeader = (item: SelectItem | undefined): boolean => !!item?.groupHeader && !item.selectable;
190
+
191
+ const DEFAULT_INPUT_ATTRS = {
192
+ autocapitalize: 'none',
193
+ autocomplete: 'off',
194
+ autocorrect: 'off',
195
+ spellcheck: false,
196
+ tabindex: 0,
197
+ type: 'text',
198
+ 'aria-autocomplete': 'list',
199
+ } as const;
200
+
201
+ const ariaHandlers = useAriaHandlers({
202
+ get ariaValues() {
203
+ return ariaValues;
204
+ },
205
+ get ariaListOpen() {
206
+ return ariaListOpen;
207
+ },
208
+ get ariaFocused() {
209
+ return ariaFocused;
210
+ },
211
+ get ariaEmpty() {
212
+ return ariaEmpty;
213
+ },
214
+ get ariaLoading() {
215
+ return ariaLoading;
216
+ },
217
+ });
218
+
219
+ function internalHandleClear(_e?: MouseEvent): void {
220
+ selectState.clearState = true;
221
+ onclear(value as unknown as SelectClearValue<Item, Multiple>);
222
+ value = undefined;
223
+ closeList();
224
+ handleFocus();
225
+ }
226
+
227
+ let list = $state<HTMLDivElement | undefined>();
228
+ let filteredItems = $derived.by<SelectItem[]>(() =>
229
+ filter({
230
+ loadOptions,
231
+ filterText,
232
+ items,
233
+ multiple,
234
+ value: normalizedValue,
235
+ itemId,
236
+ groupBy,
237
+ label,
238
+ filterSelectedItems,
239
+ itemFilter,
240
+ convertStringItemsToObjects,
241
+ applyGrouping,
242
+ }),
243
+ );
244
+
245
+ // Fold the flat filteredItems (header, item, item, header, …) into real
246
+ // listbox groups so each group can carry role="group" named by its header.
247
+ // Flat indices are preserved on every entry so ids, aria-activedescendant
248
+ // and hover keep working. Without groupBy every row is a plain option and
249
+ // the list renders flat exactly as before.
250
+ type GroupRow =
251
+ | { type: 'option'; item: SelectItem; index: number }
252
+ | { type: 'group'; headerIndex: number; header: SelectItem; options: { item: SelectItem; index: number }[] };
253
+
254
+ let groupedRows = $derived.by<GroupRow[]>(() => {
255
+ const rows: GroupRow[] = [];
256
+ let current: Extract<GroupRow, { type: 'group' }> | null = null;
257
+ filteredItems.forEach((item, index) => {
258
+ if (item.groupHeader) {
259
+ current = { type: 'group', headerIndex: index, header: item, options: [] };
260
+ rows.push(current);
261
+ } else if (item.groupItem && current) {
262
+ current.options.push({ item, index });
263
+ } else {
264
+ current = null;
265
+ rows.push({ type: 'option', item, index });
266
+ }
267
+ });
268
+ return rows;
269
+ });
270
+ // The option the combobox currently points at. With a custom listSnippet the
271
+ // consumer owns option rendering, so this only resolves if they honour the
272
+ // documented id contract — a dev-only effect below warns when it dangles.
273
+ let _activeDescendantId = $derived(
274
+ listOpen && filteredItems[hoverItemIndex] && !isPresentationalHeader(filteredItems[hoverItemIndex])
275
+ ? `listbox-${_id}-item-${hoverItemIndex}`
276
+ : undefined,
277
+ );
278
+ let _inputAttributes = $derived.by<HTMLInputAttributes>(() => {
279
+ const attrs: HTMLInputAttributes = {
280
+ ...DEFAULT_INPUT_ATTRS,
281
+ // The APG select-only pattern has no autocomplete behavior: with
282
+ // searchable={false} the input is readonly and typing never refines
283
+ // the list, so advertising list-autocomplete would misinform AT
284
+ 'aria-autocomplete': searchable ? ('list' as const) : undefined,
285
+ // The selection renders in a sibling div, so the combobox's own
286
+ // accessible value is the (empty) filter text; describe the element
287
+ // holding the selection so browse-mode users can read it from the
288
+ // input itself. Multiple mode is excluded: each chip is separately
289
+ // focusable and announced, and the description would also read
290
+ // every remove-button label.
291
+ 'aria-describedby': !multiple && value ? `selected-${_id}` : undefined,
292
+ role: 'combobox',
293
+ 'aria-controls': listOpen ? `listbox-${_id}` : undefined,
294
+ 'aria-expanded': listOpen,
295
+ 'aria-haspopup': 'listbox',
296
+ 'aria-activedescendant': _activeDescendantId,
297
+ // Only an explicit ariaLabel: a default aria-label would override an external
298
+ // <label for={id}> in accessible-name computation. Without either, the
299
+ // placeholder still names the input as the spec's last-resort fallback.
300
+ 'aria-label': ariaLabel,
301
+ 'aria-required': required || undefined,
302
+ 'aria-invalid': hasError || undefined,
303
+ // aria-errormessage is only meaningful alongside aria-invalid="true"
304
+ 'aria-errormessage': hasError && ariaErrorMessage ? ariaErrorMessage : undefined,
305
+ readonly: !searchable,
306
+ id: id ? id : undefined,
307
+ ...inputAttributes,
308
+ // Disabled is expressed with aria-disabled + readonly rather than the native
309
+ // `disabled` attribute so the current value stays in the accessibility tree
310
+ // and screen readers can still announce it. Spread last (after
311
+ // inputAttributes) so a disabled control is never left interactive or
312
+ // tab-reachable; interaction is blocked by the `disabled` guards in
313
+ // handleClick/handleFocus/handleItemClick and the disabled effect, which
314
+ // also force-closes a programmatically opened list.
315
+ ...(disabled ? { 'aria-disabled': true, readonly: true, tabindex: -1 } : {}),
316
+ };
317
+ // A consumer handler in inputAttributes must add to the input's own
318
+ // oninput/onblur/onfocus/onkeydown, not replace them: these attributes
319
+ // are spread after the template's handlers (later-spread-wins), which
320
+ // would otherwise silently disable filtering, focus handling, and
321
+ // keyboard navigation. Composed order: the component's handler first,
322
+ // then the consumer's.
323
+ const internalHandlers = {
324
+ oninput: handleInput,
325
+ onblur: handleBlur,
326
+ onfocus: handleFocus,
327
+ onkeydown: handleKeyDown,
328
+ };
329
+ for (const key of Object.keys(internalHandlers) as (keyof typeof internalHandlers)[]) {
330
+ const consumer = inputAttributes?.[key];
331
+ if (typeof consumer !== 'function') continue;
332
+ const internal = internalHandlers[key] as (e: Event) => unknown;
333
+ (attrs as Record<string, unknown>)[key] = (e: Event) => {
334
+ internal(e);
335
+ (consumer as (e: Event) => unknown)(e);
336
+ };
337
+ }
338
+ return attrs;
339
+ });
340
+ let prefloat = $state(true);
341
+ let hasValue = $derived(multiple ? Array.isArray(value) && value.length > 0 : !!value);
342
+ let placeholderText = $derived(
343
+ placeholderAlwaysShow && multiple
344
+ ? placeholder
345
+ : multiple && Array.isArray(value) && value.length === 0
346
+ ? placeholder
347
+ : value
348
+ ? ''
349
+ : placeholder,
350
+ );
351
+ let showClear = $derived(hasValue && clearable && !disabled && !loading);
352
+ let hideSelectedItem = $derived(hasValue && filterText.length > 0);
353
+
354
+ /**
355
+ * Instance export — call via a `bind:this` reference: returns the currently
356
+ * rendered rows. They include any group headers synthesized by `groupBy`
357
+ * (hence `SelectRow` rather than `Item`); narrow with `isGroupHeader`.
358
+ */
359
+ export function getFilteredItems(): SelectRow<Item>[] {
360
+ return filteredItems as SelectRow<Item>[];
361
+ }
362
+
363
+ // Announce a cleared selection explicitly: the live region uses
364
+ // aria-relevant="additions text", so merely emptying the selection span
365
+ // announces nothing.
366
+ let selectionCleared = $state(false);
367
+ let prevHadValue = false; // seeded by the first effect run below
368
+ $effect(() => {
369
+ hasValue;
370
+ focused;
371
+ untrack(() => {
372
+ if (!focused || hasValue) {
373
+ selectionCleared = false;
374
+ } else if (prevHadValue) {
375
+ selectionCleared = true;
376
+ }
377
+ prevHadValue = hasValue;
378
+ });
379
+ });
380
+
381
+ let ariaSelection = $derived(
382
+ hasValue
383
+ ? ariaHandlers.handleAriaSelection({
384
+ value,
385
+ filteredItems,
386
+ hoverItemIndex,
387
+ listOpen,
388
+ multiple,
389
+ label,
390
+ })
391
+ : selectionCleared
392
+ ? ariaCleared()
393
+ : '',
394
+ );
395
+
396
+ // svelte-floating-ui keeps a reference to this object; effects below mutate it in place
397
+ let _floatingConfig = $state<FloatingConfig>({
398
+ strategy: 'absolute',
399
+ placement: 'bottom-start',
400
+ autoUpdate: false,
401
+ });
402
+
403
+ // The shared reactive state object: live accessors over the props and derived
404
+ // values above, plus internal shared state owned by the factory. Composables
405
+ // read and write these fields directly.
406
+ const selectState = createSelectState<Item>({
407
+ get value() {
408
+ return value;
409
+ },
410
+ set value(v) {
411
+ value = v;
412
+ },
413
+ get items() {
414
+ return items;
415
+ },
416
+ set items(v) {
417
+ items = v;
418
+ },
419
+ get filterText() {
420
+ return filterText;
421
+ },
422
+ set filterText(v) {
423
+ filterText = v;
424
+ },
425
+ get justValue() {
426
+ return justValue;
427
+ },
428
+ set justValue(v) {
429
+ justValue = v;
430
+ },
431
+ get listOpen() {
432
+ return listOpen;
433
+ },
434
+ set listOpen(v) {
435
+ listOpen = v;
436
+ },
437
+ get loading() {
438
+ return loading;
439
+ },
440
+ set loading(v) {
441
+ loading = v;
442
+ },
443
+ get focused() {
444
+ return focused;
445
+ },
446
+ set focused(v) {
447
+ focused = v;
448
+ },
449
+ get hoverItemIndex() {
450
+ return hoverItemIndex;
451
+ },
452
+ set hoverItemIndex(v) {
453
+ hoverItemIndex = v;
454
+ },
455
+ get multiple() {
456
+ return multiple;
457
+ },
458
+ get itemId() {
459
+ return itemId;
460
+ },
461
+ get label() {
462
+ return label;
463
+ },
464
+ get searchable() {
465
+ return searchable;
466
+ },
467
+ get disabled() {
468
+ return disabled;
469
+ },
470
+ get useJustValue() {
471
+ return useJustValue;
472
+ },
473
+ get closeListOnChange() {
474
+ return closeListOnChange;
475
+ },
476
+ get debounceWait() {
477
+ return debounceWait;
478
+ },
479
+ get groupBy() {
480
+ return groupBy;
481
+ },
482
+ get loadOptions() {
483
+ return loadOptions;
484
+ },
485
+ get loadOptionsDeps() {
486
+ return loadOptionsDeps;
487
+ },
488
+ get filteredItems() {
489
+ return filteredItems;
490
+ },
491
+ get normalizedValue() {
492
+ return normalizedValue;
493
+ },
494
+ get hasValue() {
495
+ return hasValue;
496
+ },
497
+ });
498
+
499
+ // The active-tag mechanism (ArrowLeft/ArrowRight + Backspace) is otherwise
500
+ // only visible as a CSS outline; announce it so non-sighted users can use it
501
+ let activeTagLabel = $derived(
502
+ multiple && selectState.activeValue !== undefined && Array.isArray(value)
503
+ ? ((value as Item[])[selectState.activeValue]?.[label] as string | undefined)
504
+ : undefined,
505
+ );
506
+ let ariaContext = $derived.by(() => {
507
+ if (activeTagLabel !== undefined) {
508
+ return `${activeTagLabel} is active. Press Backspace to remove, or left and right arrow keys to move between selected options.`;
509
+ }
510
+ // Tracked triggers: the list opening/closing, the result count changing
511
+ // (filtering), and the loading flag. hoverItemIndex is deliberately read
512
+ // untracked — aria-activedescendant already announces each option as the
513
+ // keyboard cursor lands on it, so recomputing here per keystroke made every
514
+ // arrow key announce the option name twice AND re-read the whole result
515
+ // count. Leaving the region's text unchanged means it simply stays silent
516
+ // while arrowing, which is what the APG pattern expects.
517
+ listOpen;
518
+ filteredItems.length;
519
+ loading;
520
+ return untrack(() =>
521
+ ariaHandlers.handleAriaContent({
522
+ value,
523
+ filteredItems,
524
+ hoverItemIndex,
525
+ listOpen,
526
+ multiple,
527
+ label,
528
+ loading,
529
+ }),
530
+ );
531
+ });
532
+
533
+ // Initialize composables (creation order is effect order: value, hover, load options)
534
+ const valueManager = useValue(selectState, {
535
+ closeList,
536
+ // Deferred: loadOptionsManager is created a few lines below
537
+ retireStaleValidation: () => loadOptionsManager.retireValidationForFreshSelection(),
538
+ onValueChange: (v) => onValueChange?.(v as unknown as SelectValue<Item, Multiple>),
539
+ onSelectionChange: (v) => onSelectionChange?.(v as unknown as SelectValue<Item, Multiple>),
540
+ onclear: (v) => onclear(v as unknown as SelectClearValue<Item, Multiple>),
541
+ onselect: (s) => onselect?.(s as Item),
542
+ });
543
+
544
+ const hoverManager = useHover(selectState);
545
+
546
+ const loadOptionsManager = useLoadOptions(selectState, {
547
+ debounce: (fn, wait) => debounce(fn, wait),
548
+ onloaded: (opts) => onloaded(opts as (Item | SelectItem)[]),
549
+ onerror: (err) => onerror(err),
550
+ });
551
+
552
+ const keyboardNav = useKeyboardNavigation(selectState, {
553
+ closeList,
554
+ setHoverIndex: hoverManager.setHoverIndex,
555
+ handleSelect,
556
+ handleMultiItemClear: valueManager.handleMultiItemClear,
557
+ });
558
+
559
+ // Keyboard navigation must keep the hovered option visible. This hooks the
560
+ // key handler rather than an effect on hoverItemIndex so mouse hover never
561
+ // triggers scrolling.
562
+ function handleKeyDown(e: KeyboardEvent): void {
563
+ keyboardNav.handleKeyDown(e);
564
+ const isTypeAhead = !searchable && e.key.length === 1;
565
+ if (
566
+ e.key === 'ArrowDown' ||
567
+ e.key === 'ArrowUp' ||
568
+ e.key === 'Home' ||
569
+ e.key === 'End' ||
570
+ e.key === 'PageDown' ||
571
+ e.key === 'PageUp' ||
572
+ isTypeAhead
573
+ ) {
574
+ void tick().then(scrollHoveredItemIntoView);
575
+ }
576
+ }
577
+
578
+ function scrollHoveredItemIntoView(): void {
579
+ if (!listOpen || !list) return;
580
+ const el = document.getElementById(`listbox-${_id}-item-${hoverItemIndex}`);
581
+ el?.scrollIntoView?.({ block: 'nearest' });
582
+ }
583
+
584
+ const [floatingRef, floatingContent, floatingUpdate] = createFloatingActions(_floatingConfig);
585
+
586
+ onMount(() => {
587
+ // A disabled Select never grabs focus on mount; the disabled effect
588
+ // below also normalizes an initial `focused: true` back to false.
589
+ if (disabled) return;
590
+ if (listOpen) focused = true;
591
+ if (focused && input) input.focus();
592
+ });
593
+
594
+ // Keep the floating middleware in sync with listOffset. User overrides are
595
+ // merged INTO _floatingConfig: svelte-floating-ui re-reads that object on its
596
+ // own deferred/autoUpdate recomputes, so a merge into a throwaway copy would
597
+ // be reverted one tick later.
598
+ $effect.pre(() => {
599
+ const middleware = [offset(listOffset), flip(), shift()];
600
+ floatingConfig;
601
+ untrack(() => {
602
+ _floatingConfig.middleware = middleware;
603
+ if (floatingConfig) Object.assign(_floatingConfig, floatingConfig);
604
+ if (container && list) {
605
+ floatingUpdate(_floatingConfig);
606
+ }
607
+ });
608
+ });
609
+
610
+ // Sync the focused prop with real DOM focus, and close the list on unfocus.
611
+ // `bind:focused` is documented as writable, so a parent write must move real
612
+ // DOM focus: `focused = true` alone used to leave focus elsewhere while the
613
+ // window keydown handler (gated only on `focused`) claimed arrow/Enter keys
614
+ // page-wide, with no blur ever able to reset it. Transition-guarded so the
615
+ // mount run doesn't closeList(), which wiped an initial filterText via
616
+ // clearFilterTextOnBlur while the mount loadOptions fetch used the original text.
617
+ let prevFocused = focused;
618
+ $effect(() => {
619
+ focused;
620
+ untrack(() => {
621
+ if (focused === prevFocused) return;
622
+ prevFocused = focused;
623
+ if (focused) {
624
+ if (disabled) {
625
+ // A disabled Select cannot be focused programmatically
626
+ focused = false;
627
+ prevFocused = false;
628
+ return;
629
+ }
630
+ if (input && document.activeElement !== input) handleFocus();
631
+ } else {
632
+ closeList();
633
+ selectState.activeValue = undefined;
634
+ if (input && document.activeElement === input) input.blur();
635
+ }
636
+ });
637
+ });
638
+
639
+ // Setup filter text: every write after mount behaves like typing (opens the
640
+ // list); only the mount run stays passive — an initial filterText filters
641
+ // (and fetches, with loadOptions) without opening the list or moving focus.
642
+ // A first-run flag, not a prevFilterText compare: the effect only reruns on
643
+ // real changes, and the old compare against the last *typed* value silently
644
+ // ignored a programmatic write that happened to equal it (fetching against
645
+ // a closed list with loadOptions).
646
+ let filterTextSeeded = false;
647
+ $effect(() => {
648
+ filterText;
649
+ untrack(() => {
650
+ if (!filterTextSeeded) {
651
+ filterTextSeeded = true;
652
+ return;
653
+ }
654
+ setupFilterText();
655
+ });
656
+ });
657
+
658
+ // Fire onhoveritem. The callback runs untracked: reactive reads inside a
659
+ // consumer callback must not become dependencies of this effect, and an
660
+ // inline callback prop changing identity per parent render must not refire.
661
+ $effect(() => {
662
+ hoverItemIndex;
663
+ untrack(() => onhoveritem?.(hoverItemIndex));
664
+ });
665
+
666
+ // Fire onfilter — untracked like onhoveritem; an onfilter that writes
667
+ // `items` would otherwise loop through filteredItems
668
+ $effect(() => {
669
+ filteredItems;
670
+ listOpen;
671
+ untrack(() => {
672
+ if (filteredItems && listOpen) onfilter?.(filteredItems as SelectRow<Item>[]);
673
+ });
674
+ });
675
+
676
+ // Floating UI config
677
+ $effect(() => {
678
+ if (container && floatingConfig) {
679
+ untrack(() => {
680
+ Object.assign(_floatingConfig, floatingConfig);
681
+ floatingUpdate(_floatingConfig);
682
+ });
683
+ }
684
+ });
685
+
686
+ // List mounted
687
+ $effect(() => {
688
+ listOpen;
689
+ untrack(() => {
690
+ // A closed list retires Tab's commit-intent; the next open starts
691
+ // from an auto-parked cursor again (see handleTabKey). Reset on
692
+ // close, not open: a type-ahead press that opens the list parks
693
+ // the cursor in the same handler, and a reset-on-open flush would
694
+ // clobber that intent.
695
+ if (!listOpen) selectState.userNavigatedSinceOpen = false;
696
+ listMounted(list, listOpen);
697
+ if (listOpen && container && list) {
698
+ setListWidth();
699
+ // Opening with a value starts hovered on that value; bring it into view
700
+ void tick().then(scrollHoveredItemIntoView);
701
+ }
702
+ });
703
+ });
704
+
705
+ // Focus when list opens
706
+ $effect(() => {
707
+ if (input && listOpen && !focused) handleFocus();
708
+ });
709
+
710
+ // Dev-only: a custom listSnippet takes over option rendering, so the combobox's
711
+ // aria-activedescendant only resolves if the consumer reproduces the option ids.
712
+ // A dangling activedescendant points assistive tech at nothing, which is worse
713
+ // than a plain listbox — so surface it rather than letting it fail silently.
714
+ $effect(() => {
715
+ if (!DEV) return;
716
+ const activeId = _activeDescendantId;
717
+ const hasListSnippet = !!listSnippet;
718
+ untrack(() => {
719
+ if (!hasListSnippet || !activeId || document.getElementById(activeId)) return;
720
+ console.warn(
721
+ `[svelte-select] listSnippet is rendering the list, but no element with id "${activeId}" ` +
722
+ "exists, so the combobox's aria-activedescendant points at nothing and screen readers " +
723
+ 'cannot follow keyboard navigation. Give each option you render ' +
724
+ `id="listbox-${_id}-item-{index}" (matching its index in the snippet argument) and ` +
725
+ 'role="option".',
726
+ );
727
+ });
728
+ });
729
+
730
+ // Dev-only: items are compared by their `itemId` field everywhere
731
+ // (selection, hover, dedup), and entries missing that field all compare
732
+ // equal — the first pick works, every later click on a different option
733
+ // reads "already selected" and just closes the list, and every option
734
+ // renders selected. The failure is completely silent, so surface the
735
+ // config error instead.
736
+ let warnedAboutMissingItemId = false;
737
+ $effect(() => {
738
+ if (!DEV) return;
739
+ const currentItems = items;
740
+ const currentItemId = itemId;
741
+ untrack(() => {
742
+ if (warnedAboutMissingItemId || !currentItems?.length) return;
743
+ const missing = (currentItems as (Item | string)[]).some(
744
+ (item) => typeof item !== 'string' && getItemProperty(item, currentItemId) === undefined,
745
+ );
746
+ if (!missing) return;
747
+ warnedAboutMissingItemId = true;
748
+ console.warn(
749
+ `[svelte-select] Some items have no "${currentItemId}" field (the current \`itemId\`). ` +
750
+ 'Items are compared by that field, so items without it all compare as the same ' +
751
+ 'item — selection, hover state, and deduplication will misbehave. Point `itemId` ' +
752
+ 'at a field your items actually have, or add the field to your items.',
753
+ );
754
+ });
755
+ });
756
+
757
+ // Dev-only: warn once the input is mounted if it has no robust accessible
758
+ // name. The placeholder is only a last-resort fallback that some screen
759
+ // readers ignore, so an unnamed combobox is a real gap worth surfacing.
760
+ $effect(() => {
761
+ // Gate on esm-env's DEV, never on Vite's build-time env object: that object
762
+ // is undefined outside a Vite bundle, so reading its DEV flag threw at mount
763
+ // for rollup/webpack/no-build consumers. esm-env resolves per-bundler and
764
+ // tree-shakes this whole effect out of production builds.
765
+ if (!DEV) return;
766
+ input;
767
+ ariaLabel;
768
+ untrack(() => {
769
+ if (!input) return;
770
+ const named = !!ariaLabel || !!input.getAttribute('aria-labelledby') || (input.labels?.length ?? 0) > 0;
771
+ if (!named) {
772
+ console.warn(
773
+ '[svelte-select] The Select input has no accessible name. Pass `ariaLabel`, ' +
774
+ 'or set the `id` prop and add a matching `<label for={id}>`, so screen readers ' +
775
+ 'can announce the field. The placeholder is only a last-resort fallback and is ' +
776
+ 'ignored by some assistive tech.',
777
+ );
778
+ }
779
+ });
780
+ });
781
+
782
+ // The listbox needs its own accessible name (ARIA 1.2): `ariaLabel` covers
783
+ // one recommended naming path, but the others — `id` + external `<label for>`
784
+ // or an `aria-labelledby` supplied through `inputAttributes` — name only the
785
+ // input; neither cascades to the floating list. Resolve a name when the list
786
+ // opens, in the same precedence the input uses: explicit ariaLabel, then the
787
+ // input's own aria-labelledby (forwarded), then the associated label —
788
+ // referenced via aria-labelledby when it is external and has an id (live
789
+ // text), otherwise a text snapshot. The consumer's label is never mutated.
790
+ let listboxLabelledby = $state<string | undefined>();
791
+ let listboxLabelText = $state<string | undefined>();
792
+ $effect(() => {
793
+ listOpen;
794
+ ariaLabel;
795
+ untrack(() => {
796
+ listboxLabelledby = undefined;
797
+ listboxLabelText = undefined;
798
+ if (!listOpen || ariaLabel || !input) return;
799
+ const inputLabelledby = input.getAttribute('aria-labelledby');
800
+ if (inputLabelledby) {
801
+ listboxLabelledby = inputLabelledby;
802
+ return;
803
+ }
804
+ const labelEl = input.labels?.[0];
805
+ if (!labelEl) return;
806
+ // An implicit wrapping <label> contains the component itself, so
807
+ // both aria-labelledby and a plain textContent snapshot would pull
808
+ // in everything rendered inside (chips, options, live regions).
809
+ // Snapshot only the label's own text — the nodes outside this
810
+ // component's subtree.
811
+ const wrapsComponent = container ? labelEl.contains(container) : false;
812
+ if (!wrapsComponent && labelEl.id) {
813
+ listboxLabelledby = labelEl.id;
814
+ } else if (!wrapsComponent) {
815
+ listboxLabelText = labelEl.textContent?.trim() || undefined;
816
+ } else {
817
+ let text = '';
818
+ for (const node of labelEl.childNodes) {
819
+ if (node === container || (node instanceof Element && container && node.contains(container)))
820
+ continue;
821
+ text += node.textContent ?? '';
822
+ }
823
+ listboxLabelText = text.trim() || undefined;
824
+ }
825
+ });
826
+ });
827
+
828
+ // Auto update floating config
829
+ $effect(() => {
830
+ if (container && floatingConfig?.autoUpdate === undefined) {
831
+ _floatingConfig.autoUpdate = true;
832
+ }
833
+ });
834
+
835
+ // Disabled state
836
+ $effect(() => {
837
+ disabled;
838
+ // listOpen is a tracked trigger too: neither setupFilterText nor the list
839
+ // template gates on disabled, so a programmatic bind:listOpen (or
840
+ // filterText) write while disabled would otherwise render an operable
841
+ // list — this effect only reruns on `disabled` flips without it.
842
+ listOpen;
843
+ untrack(() => {
844
+ if (!disabled) return;
845
+ listOpen = false;
846
+ filterText = '';
847
+ // Disabling must also release focus: every keyboard handler gates
848
+ // on `focused`, so a Select disabled while it held focus stayed
849
+ // fully keyboard-operable (list toggling, Enter selection,
850
+ // Backspace tag removal) despite being aria-disabled. This also
851
+ // normalizes an initial `focused: true, disabled: true` mount.
852
+ if (focused) focused = false;
853
+ if (input && document.activeElement === input) input.blur();
854
+ });
855
+ });
856
+
857
+ function applyGrouping(_items: SelectItem[]): SelectItem[] {
858
+ if (!groupBy) return _items;
859
+
860
+ const groupValues: string[] = [];
861
+ const groups: Record<string, SelectItem[]> = {};
862
+
863
+ _items.forEach((item) => {
864
+ const groupValue: string = groupBy(item as Item);
865
+
866
+ if (!groupValues.includes(groupValue)) {
867
+ groupValues.push(groupValue);
868
+ groups[groupValue] = [];
869
+ if (groupValue) {
870
+ groups[groupValue].push(
871
+ Object.assign(createGroupHeaderItem(groupValue, item as Item), {
872
+ id: groupValue,
873
+ groupHeader: true,
874
+ selectable: groupHeaderSelectable,
875
+ }),
876
+ );
877
+ }
878
+ }
879
+
880
+ groups[groupValue].push(Object.assign({ groupItem: !!groupValue }, item));
881
+ });
882
+
883
+ const sortedGroupedItems: SelectItem[] = [];
884
+
885
+ groupFilter(groupValues).forEach((groupValue: string) => {
886
+ if (groups[groupValue]) sortedGroupedItems.push(...groups[groupValue]);
887
+ });
888
+
889
+ return sortedGroupedItems;
890
+ }
891
+
892
+ function setupFilterText() {
893
+ if (loadOptions) {
894
+ if (filterText.length > 0) {
895
+ if (!listOpen) listOpen = true;
896
+ // Typing dismisses an armed tag cursor here too — mirrors the
897
+ // non-loadOptions branch below; without this the cursor stayed
898
+ // highlighted and announced while the user typed (Backspace
899
+ // itself was already guarded by the filterText check)
900
+ if (multiple) selectState.activeValue = undefined;
901
+ }
902
+ return;
903
+ }
904
+
905
+ if (filterText.length === 0) return;
906
+
907
+ listOpen = true;
908
+
909
+ if (multiple) {
910
+ selectState.activeValue = undefined;
911
+ }
912
+ }
913
+
914
+ function handleFocus(e?: FocusEvent): void {
915
+ // The input is no longer natively `disabled`, so it can still be
916
+ // click-focused — keep a disabled Select non-interactive here.
917
+ if (disabled) return;
918
+ if (focused && input === document?.activeElement) return;
919
+ if (e) {
920
+ onfocus?.(e);
921
+ }
922
+ input?.focus();
923
+ focused = true;
924
+ }
925
+
926
+ // A blur while the list is scrolling is deferred, not dropped: DOM focus is
927
+ // already gone, so no further blur will ever fire — without a replay the list
928
+ // stays open and the window keydown handler keeps hijacking keys.
929
+ let pendingBlur: FocusEvent | boolean = false;
930
+
931
+ async function handleBlur(e?: FocusEvent): Promise<void> {
932
+ if (selectState.isScrolling) {
933
+ pendingBlur = e ?? true;
934
+ return;
935
+ }
936
+ pendingBlur = false;
937
+ if (listOpen || focused) {
938
+ if (e) onblur?.(e);
939
+ closeList();
940
+ focused = false;
941
+ selectState.activeValue = undefined;
942
+ input?.blur();
943
+ }
944
+ }
945
+
946
+ // Replay a deferred blur once scrolling settles — unless focus is back on
947
+ // the input (the scroll itself blurred it only transiently)
948
+ $effect(() => {
949
+ selectState.isScrolling;
950
+ untrack(() => {
951
+ if (selectState.isScrolling || pendingBlur === false) return;
952
+ const deferred = pendingBlur === true ? undefined : pendingBlur;
953
+ pendingBlur = false;
954
+ if (document.activeElement !== input) void handleBlur(deferred);
955
+ });
956
+ });
957
+
958
+ function handleClick(ev: MouseEvent) {
959
+ ev.preventDefault();
960
+ if (disabled) return;
961
+ if (filterText && filterText.length > 0) return (listOpen = true);
962
+ listOpen = !listOpen;
963
+ }
964
+
965
+ function closeList() {
966
+ if (clearFilterTextOnBlur) {
967
+ filterText = '';
968
+ }
969
+ listOpen = false;
970
+ // Reset Tab's commit-intent synchronously, not only in the listOpen
971
+ // effect below: a consumer callback that reopens the list in the same
972
+ // flush would otherwise carry stale intent into the reopened list (the
973
+ // effect would run once and only ever observe listOpen === true)
974
+ selectState.userNavigatedSinceOpen = false;
975
+ // A load armed by typing must not fire (spinner + stale items) on a closed list;
976
+ // reads through the effect miss this when clearFilterTextOnBlur is false
977
+ loadOptionsManager.cancelPendingFilterLoad();
978
+ }
979
+
980
+ onDestroy(() => {
981
+ // The floating list can outlive the component's own tree; remove it explicitly
982
+ // eslint-disable-next-line svelte/no-dom-manipulating
983
+ list?.remove();
984
+ // A debounced load firing after unmount would fetch and invoke callbacks
985
+ // on a dead component
986
+ clearTimeout(timeout);
987
+ clearTimeout(prefloatTimeout);
988
+ loadOptionsManager.invalidateLoads();
989
+ });
990
+
991
+ function handleSelect(item: SelectItem): void {
992
+ if (!item || item.selectable === false) return;
993
+ valueManager.itemSelected(item);
994
+ }
995
+
996
+ function handleItemClick(item: SelectItem, i: number): void {
997
+ // Defence in depth: the disabled effect force-closes the list, but a
998
+ // pointer must never mutate a disabled control's value even if a list
999
+ // is momentarily rendered
1000
+ if (disabled) return;
1001
+ if (item?.selectable === false) return;
1002
+ if (!multiple && !Array.isArray(normalizedValue) && areItemsEqual(normalizedValue, item, itemId))
1003
+ return closeList();
1004
+ if (hoverManager.isItemSelectable(item)) {
1005
+ hoverItemIndex = i;
1006
+ handleSelect(item);
1007
+ }
1008
+ }
1009
+
1010
+ function setListWidth(): void {
1011
+ if (!container || !list) return;
1012
+ const { width } = container.getBoundingClientRect();
1013
+ list.style.width = listAutoWidth ? width + 'px' : 'auto';
1014
+ }
1015
+
1016
+ let prefloatTimeout: ReturnType<typeof setTimeout> | undefined;
1017
+ function listMounted(list: HTMLDivElement | undefined, listOpen: boolean) {
1018
+ if (!list || !listOpen) return (prefloat = true);
1019
+ clearTimeout(prefloatTimeout);
1020
+ prefloatTimeout = setTimeout(() => {
1021
+ prefloat = false;
1022
+ }, 0);
1023
+ }
1024
+
1025
+ function handleInput(ev: Event): void {
1026
+ const target = ev.target as HTMLInputElement;
1027
+ listOpen = true;
1028
+ selectState.prevFilterText = filterText;
1029
+ filterText = target.value;
1030
+ // Typing this session is commit-intent for Tab (see handleTabKey).
1031
+ // Marked here — on the real input event — rather than gating on the
1032
+ // current filterText, so a consumer-seeded initial value or text
1033
+ // retained across a close (clearFilterTextOnBlur={false}) can't arm a
1034
+ // commit the user never expressed.
1035
+ selectState.userNavigatedSinceOpen = true;
1036
+ }
1037
+
1038
+ /**
1039
+ * Instance export — call via a `bind:this` reference: clears the selection,
1040
+ * filter text, and open/focus state back to an empty control. Does not fire
1041
+ * `onclear` (it is a programmatic reset, not a user clear).
1042
+ */
1043
+ export function reset(): void {
1044
+ selectState.clearState = true;
1045
+ value = undefined;
1046
+ filterText = '';
1047
+ listOpen = false;
1048
+ hoverItemIndex = 0;
1049
+ selectState.activeValue = undefined;
1050
+ justValue = undefined;
1051
+ focused = false;
1052
+ }
1053
+ </script>
1054
+
1055
+ <!-- Outside clicks close the list via the input's native blur -->
1056
+ <svelte:window onkeydown={handleKeyDown} />
1057
+
1058
+ <div
1059
+ class="svelte-select {rest.class}"
1060
+ class:multi={multiple}
1061
+ class:disabled
1062
+ class:focused
1063
+ class:list-open={listOpen}
1064
+ class:show-chevron={showChevron}
1065
+ class:error={hasError}
1066
+ style={containerStyles}
1067
+ onpointerup={handleClick}
1068
+ onmousedown={(ev) => {
1069
+ // Pressing a non-input surface (the chevron area, a chip, multi-mode
1070
+ // whitespace) must not blur the input: the blur handler closes the
1071
+ // list, and this press's own pointerup — bubbling to handleClick —
1072
+ // would read that fresh closed state and toggle the list straight
1073
+ // back open. The input keeps its default behavior so caret placement
1074
+ // and text selection still work. (The list has its own guard and
1075
+ // stops propagation before reaching this one.)
1076
+ if (ev.target !== input) ev.preventDefault();
1077
+ }}
1078
+ bind:this={container}
1079
+ use:floatingRef
1080
+ role="none">
1081
+ {#if listOpen}
1082
+ <div
1083
+ use:floatingContent
1084
+ bind:this={list}
1085
+ class="svelte-select-list"
1086
+ class:prefloat
1087
+ style={listStyles}
1088
+ onscroll={hoverManager.handleListScroll}
1089
+ onscrollend={hoverManager.handleListScrollEnd}
1090
+ onmousemove={() => {
1091
+ // Real pointer movement over the open list is commit-intent for
1092
+ // Tab (see handleTabKey). mousemove — not mouseover — because
1093
+ // browsers synthesize mouseover when the list renders under a
1094
+ // stationary cursor, which is zero user action.
1095
+ selectState.userNavigatedSinceOpen = true;
1096
+ }}
1097
+ onpointerup={(ev) => {
1098
+ if (ev.pointerType === 'mouse') ev.preventDefault();
1099
+ ev.stopPropagation();
1100
+ }}
1101
+ onmousedown={(ev) => {
1102
+ ev.preventDefault();
1103
+ ev.stopPropagation();
1104
+ }}
1105
+ role="listbox"
1106
+ tabindex="-1"
1107
+ aria-label={ariaLabel ?? listboxLabelText}
1108
+ aria-labelledby={listboxLabelledby}
1109
+ aria-busy={loading || undefined}
1110
+ aria-multiselectable={multiple || undefined}
1111
+ id="listbox-{_id}">
1112
+ {#if listPrependSnippet}
1113
+ {@render listPrependSnippet()}
1114
+ {/if}
1115
+ {#if listSnippet}
1116
+ {@render listSnippet(filteredItems as SelectRow<Item>[])}
1117
+ {:else if filteredItems?.length > 0}
1118
+ {#snippet optionEntry(item: SelectItem, i: number)}
1119
+ <!-- Non-selectable group headers are aria-hidden rather than
1120
+ role="presentation": a listbox may only own option/group children,
1121
+ and groups are transparent for that check, so a presentational row
1122
+ inside one is an invalid listbox child (axe aria-required-children).
1123
+ The group's accessible name still resolves via aria-labelledby,
1124
+ which follows hidden targets. Selectable headers are real options. -->
1125
+ <div
1126
+ onmouseover={() => hoverManager.handleHover(i)}
1127
+ onfocus={() => hoverManager.handleHover(i)}
1128
+ onclick={(ev) => {
1129
+ ev.stopPropagation();
1130
+ handleItemClick(item, i);
1131
+ }}
1132
+ onkeydown={(ev) => {
1133
+ ev.preventDefault();
1134
+ ev.stopPropagation();
1135
+ }}
1136
+ class="list-item"
1137
+ tabindex="-1"
1138
+ role={isPresentationalHeader(item) ? undefined : 'option'}
1139
+ id="listbox-{_id}-item-{i}"
1140
+ aria-hidden={isPresentationalHeader(item) ? true : undefined}
1141
+ aria-selected={isPresentationalHeader(item) ? undefined : hoverManager.isItemActive(item)}
1142
+ aria-disabled={isPresentationalHeader(item) || isItemSelectableCheck(item) ? undefined : true}>
1143
+ <div
1144
+ class="item"
1145
+ class:list-group-title={item.groupHeader}
1146
+ class:active={hoverManager.isItemActive(item)}
1147
+ class:first={i === 0}
1148
+ class:last={i === filteredItems.length - 1}
1149
+ class:hover={hoverItemIndex === i}
1150
+ class:group-item={item.groupItem}
1151
+ class:not-selectable={item?.selectable === false}>
1152
+ {#if itemSnippet}
1153
+ {@render itemSnippet(item as SelectRow<Item>, i)}
1154
+ {:else}
1155
+ {item?.[label]}
1156
+ {/if}
1157
+ </div>
1158
+ </div>
1159
+ {/snippet}
1160
+ {#each groupedRows as row}
1161
+ {#if row.type === 'group'}
1162
+ <!-- A real listbox group named by its header (presentational or
1163
+ selectable) via aria-labelledby, wrapping that group's options -->
1164
+ <div role="group" aria-labelledby="listbox-{_id}-item-{row.headerIndex}">
1165
+ {@render optionEntry(row.header, row.headerIndex)}
1166
+ {#each row.options as opt}
1167
+ {@render optionEntry(opt.item, opt.index)}
1168
+ {/each}
1169
+ </div>
1170
+ {:else}
1171
+ {@render optionEntry(row.item, row.index)}
1172
+ {/if}
1173
+ {/each}
1174
+ {:else if !hideEmptyState}
1175
+ {#if emptySnippet}
1176
+ {@render emptySnippet()}
1177
+ {:else if !loading}
1178
+ <!-- Decorative: this state is announced via the role="status" live
1179
+ region below, so hide the visual copy from AT to avoid stray
1180
+ non-option text inside the listbox. The visible copy comes from
1181
+ the same ariaEmpty/ariaLoading props as the announcement, so a
1182
+ localized consumer never shows one language and announces
1183
+ another. -->
1184
+ <div class="empty" aria-hidden="true">{ariaEmpty()}</div>
1185
+ {:else}
1186
+ <div class="empty" aria-hidden="true">{ariaLoading()}</div>
1187
+ {/if}
1188
+ {/if}
1189
+ {#if listAppendSnippet}
1190
+ {@render listAppendSnippet()}
1191
+ {/if}
1192
+ </div>
1193
+ {/if}
1194
+
1195
+ <!-- Two dedicated polite live regions (role="status" implies aria-live="polite"
1196
+ + aria-atomic="true"). Atomic re-reads the whole region on any content change,
1197
+ which announces edits and clears reliably across screen readers — unlike the
1198
+ old aria-atomic="false"/aria-relevant="additions text" combination. The spans
1199
+ persist (only their text is gated on focus) so they exist before content
1200
+ changes, as live regions require. -->
1201
+ <span id="aria-selection-{_id}" role="status" class="a11y-text a11y-selection">
1202
+ {focused ? ariaSelection : ''}
1203
+ </span>
1204
+ <span id="aria-context-{_id}" role="status" class="a11y-text a11y-context">
1205
+ {focused ? ariaContext : ''}
1206
+ </span>
1207
+
1208
+ <div class="prepend">
1209
+ {#if prependSnippet}
1210
+ {@render prependSnippet()}
1211
+ {/if}
1212
+ </div>
1213
+
1214
+ <div class="value-container">
1215
+ {#if hasValue}
1216
+ {#if multiple}
1217
+ {#each Array.isArray(value) ? (value as Item[]) : [] as item, i}
1218
+ <!-- In multiFullItemClearable mode the whole chip is the remove control, so it
1219
+ must be a focusable button with a keyboard (Enter/Space) path — otherwise
1220
+ removal is mouse-only. Otherwise it stays a non-semantic wrapper around the
1221
+ dedicated remove button below. -->
1222
+ <!-- svelte-ignore a11y_no_noninteractive_tabindex -->
1223
+ <!-- tabindex and role="button" are set together under the same guard, so the
1224
+ element is interactive exactly when it is focusable (the linter can't see this). -->
1225
+ <div
1226
+ class="multi-item"
1227
+ class:active={selectState.activeValue === i}
1228
+ class:disabled
1229
+ onclick={(ev) => {
1230
+ ev.preventDefault();
1231
+ // Gated like the keydown path below: a pointer must never
1232
+ // mutate a disabled control's value (see handleItemClick)
1233
+ if (multiFullItemClearable && !disabled) {
1234
+ void valueManager.handleMultiItemClear(i);
1235
+ // Like the dedicated remove button below: focus returns
1236
+ // to the input so the removal announcement is not lost —
1237
+ // the live regions are gated on `focused`, and a chip
1238
+ // press that kept focus on the chip would otherwise
1239
+ // remove the chip from the DOM and drop focus to <body>
1240
+ // with the removal never announced.
1241
+ handleFocus();
1242
+ }
1243
+ }}
1244
+ onpointerup={multiFullItemClearable && !disabled
1245
+ ? (ev) => {
1246
+ // Same containment as the dedicated remove button below:
1247
+ // removing a tag must not bubble to the container's list
1248
+ // toggle and pop the dropdown as a side effect
1249
+ ev.stopPropagation();
1250
+ }
1251
+ : undefined}
1252
+ onkeydown={multiFullItemClearable && !disabled
1253
+ ? (ev) => {
1254
+ if (ev.key !== 'Enter' && ev.key !== ' ') return;
1255
+ ev.preventDefault();
1256
+ ev.stopPropagation();
1257
+ valueManager.handleMultiItemClear(i);
1258
+ handleFocus();
1259
+ }
1260
+ : undefined}
1261
+ role={multiFullItemClearable && !disabled ? 'button' : 'none'}
1262
+ tabindex={multiFullItemClearable && !disabled ? 0 : undefined}
1263
+ aria-label={multiFullItemClearable && !disabled
1264
+ ? ariaRemoveItemLabel(String(item[label]))
1265
+ : undefined}>
1266
+ <span class="multi-item-text">
1267
+ {#if selectionSnippet}
1268
+ {@render selectionSnippet(item, i)}
1269
+ {:else}
1270
+ {item[label]}
1271
+ {/if}
1272
+ </span>
1273
+
1274
+ {#if !disabled && !multiFullItemClearable && ClearIcon}
1275
+ <!-- A real button: keyboard-focusable, Enter/Space activate via click.
1276
+ mousedown is prevented so a mouse removal never steals focus from
1277
+ the input; pointerup must not bubble to the container's list toggle. -->
1278
+ <button
1279
+ type="button"
1280
+ class="multi-item-clear"
1281
+ aria-label={ariaRemoveItemLabel(String(item[label]))}
1282
+ onmousedown={(ev) => ev.preventDefault()}
1283
+ onpointerup={(ev) => ev.stopPropagation()}
1284
+ onclick={(ev) => {
1285
+ ev.stopPropagation();
1286
+ valueManager.handleMultiItemClear(i);
1287
+ handleFocus();
1288
+ }}>
1289
+ {#if multiClearIconSnippet}
1290
+ {@render multiClearIconSnippet()}
1291
+ {:else}
1292
+ <ClearIcon />
1293
+ {/if}
1294
+ </button>
1295
+ {/if}
1296
+ </div>
1297
+ {/each}
1298
+ {:else}
1299
+ <div id="selected-{_id}" class="selected-item" class:hide-selected-item={hideSelectedItem}>
1300
+ {#if selectionSnippet}
1301
+ {@render selectionSnippet(value as Item)}
1302
+ {:else}
1303
+ {!Array.isArray(normalizedValue) ? normalizedValue?.[label] : ''}
1304
+ {/if}
1305
+ </div>
1306
+ {/if}
1307
+ {/if}
1308
+
1309
+ <input
1310
+ onkeydown={handleKeyDown}
1311
+ onblur={handleBlur}
1312
+ oninput={handleInput}
1313
+ onfocus={handleFocus}
1314
+ {..._inputAttributes}
1315
+ bind:this={input}
1316
+ value={filterText}
1317
+ placeholder={placeholderText}
1318
+ style={inputStyles} />
1319
+ </div>
1320
+
1321
+ <div class="indicators">
1322
+ {#if loading}
1323
+ <div class="icon loading" aria-hidden="true">
1324
+ {#if loadingIconSnippet}
1325
+ {@render loadingIconSnippet()}
1326
+ {:else}
1327
+ <LoadingIcon />
1328
+ {/if}
1329
+ </div>
1330
+ {/if}
1331
+
1332
+ {#if showClear}
1333
+ <!-- Same guards as the tag-remove buttons: mousedown is prevented so
1334
+ clearing never steals focus from the input, and pointerup must not
1335
+ bubble to the container's list toggle (a clear would reopen the list). -->
1336
+ <button
1337
+ type="button"
1338
+ class="icon clear-select"
1339
+ aria-label={ariaClearSelectLabel}
1340
+ onmousedown={(ev) => ev.preventDefault()}
1341
+ onpointerup={(ev) => ev.stopPropagation()}
1342
+ onclick={handleClear}>
1343
+ {#if clearIconSnippet}
1344
+ {@render clearIconSnippet()}
1345
+ {:else}
1346
+ <ClearIcon />
1347
+ {/if}
1348
+ </button>
1349
+ {/if}
1350
+
1351
+ {#if showChevron}
1352
+ <div class="icon chevron" aria-hidden="true">
1353
+ {#if chevronIconSnippet}
1354
+ {@render chevronIconSnippet(listOpen)}
1355
+ {:else}
1356
+ <ChevronIcon />
1357
+ {/if}
1358
+ </div>
1359
+ {/if}
1360
+ </div>
1361
+ {#if inputHiddenSnippet}
1362
+ {@render inputHiddenSnippet(value)}
1363
+ {:else if multiple && Array.isArray(value) && value.length > 0}
1364
+ {#each value as Item[] as item}
1365
+ <input {name} type="hidden" value={useJustValue ? item[itemId] : JSON.stringify(item)} />
1366
+ {/each}
1367
+ {:else if !multiple}
1368
+ <input {name} type="hidden" value={value ? (useJustValue ? justValue : JSON.stringify(value)) : ''} />
1369
+ {/if}
1370
+
1371
+ {#if required && (!value || (Array.isArray(value) && value.length === 0))}
1372
+ {#if requiredSnippet}
1373
+ {@render requiredSnippet(value)}
1374
+ {:else}
1375
+ <!-- Constraint validation focuses the first invalid control — this one.
1376
+ An aria-hidden element must never hold focus (and this one is
1377
+ invisible), so forward it to the real combobox input immediately. -->
1378
+ <select class="required" required tabindex="-1" aria-hidden="true" onfocus={() => handleFocus()}></select>
1379
+ {/if}
1380
+ {/if}
1381
+ </div>
1382
+
1383
+