fix: keep MultiSelect focus out of the closing list and expose it as a combobox

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Guilhem Lemouel
2026-10-14 02:14:55 -07:00
co-authored by Claude Opus 5.5
parent 8df700cad9
commit d40b42818b
2 changed files with 86 additions and 72 deletions
@@ -74,6 +74,7 @@
let filterText = $state<string>('')
let open = $state<boolean>(false)
let wrapperEl: HTMLDivElement | undefined = $state()
const listId = $props.id()
let searchInputEl: TextInput | undefined = $state()
let currentValue = $derived(value ?? [])
@@ -148,15 +149,21 @@
wrapperEl?.focus()
}
// Escape that closes the list must not also close the drawer or popover around the field.
// Melt popovers listen on `document`, where Svelte handles delegated events of portaled
// content too, so only stopping immediate propagation keeps the event from them.
function consumeEscape(e: KeyboardEvent) {
e.preventDefault()
e.stopImmediatePropagation()
}
function onFieldKeydown(e: KeyboardEvent) {
if (e.target !== wrapperEl) return
if (!open && (e.key === 'Enter' || e.key === ' ' || e.key === 'ArrowDown')) {
e.preventDefault()
open = true
} else if (open && e.key === 'Escape') {
// Consumed here so a drawer around the field stays open.
e.preventDefault()
e.stopPropagation()
consumeEscape(e)
open = false
} else if (open && e.key === 'Tab') {
open = false
@@ -165,12 +172,11 @@
function onSearchKeydown(e: KeyboardEvent) {
if (e.key === 'Escape') {
e.preventDefault()
e.stopPropagation()
consumeEscape(e)
closeAndFocusField()
} else if (e.key === 'Tab') {
// The list is portaled to the end of <body>: moving focus back to the field first lets
// Tab continue from the field rather than off the end of the page.
// The list may be portaled to the end of <body>: moving focus back to the field first
// lets Tab continue from the field rather than off the end of the page.
closeAndFocusField()
}
}
@@ -182,7 +188,8 @@
<div
bind:this={wrapperEl}
role="button"
role="combobox"
aria-controls={listId}
aria-expanded={open && !disabled}
aria-haspopup="listbox"
aria-disabled={disabled}
@@ -198,11 +205,7 @@
className
)}
{style}
onpointerup={() => {
open = true
// Pressing the field focused it, out of an already open list's search input.
searchInputEl?.focus()
}}
onpointerup={() => (open = true)}
onkeydown={onFieldKeydown}
use:clickOutside={{ onClickOutside: () => (open = false) }}
{id}
@@ -257,6 +260,7 @@
disabled ? 'disabled' : ''
)}
ulClass="options"
{listId}
>
{#snippet header()}
{#if showSearch}
@@ -265,7 +269,9 @@
bind:this={searchInputEl}
bind:value={filterText}
inputProps={{
onblur: (e) => open && e.relatedTarget !== wrapperEl && searchInputEl?.focus(),
// Pressing the field or a chip focuses the field; typing must still filter.
// Not once the last option is picked, as the input is then unmounting.
onblur: () => open && showSearch && searchInputEl?.focus(),
onkeydown: onSearchKeydown,
placeholder: searchPlaceholder
}}
@@ -26,7 +26,8 @@
startSnippet,
endSnippet,
bottomSnippet,
highlightFirstOnOpen = false
highlightFirstOnOpen = false,
listId
}: {
processedItems?: ProcessedItem<T>[]
value: T | undefined
@@ -49,6 +50,8 @@
bottomSnippet?: Snippet<[{ close: () => void }]>
/** When true, the first item is highlighted when the dropdown opens (even without filterText) */
highlightFirstOnOpen?: boolean
/** `id` of the options list, for a field's `aria-controls`. */
listId?: string
} = $props()
let processedItems = $derived(
@@ -106,63 +109,68 @@
{getInputRect}
class={className}
>
{@render header?.()}
{#if processedItems?.length === 0}
<div class="py-8 px-4 text-center text-primary text-xs">{noItemsMsg}</div>
{/if}
<ul
class={twMerge(
'flex-1 flex flex-col',
enableOverflowYAuto.current ? 'overflow-y-auto' : '',
ulClass
)}
>
{#each processedItems ?? [] as item, itemIndex}
{#if (item.__select_group && itemIndex === 0) || processedItems?.[itemIndex - 1]?.__select_group !== item.__select_group}
<li
class={twMerge(
'mx-4 pb-1 mb-2 text-xs font-semibold text-primary border-b border-border-light',
itemIndex === 0 ? 'mt-3' : 'mt-6'
)}
>
{item.__select_group}
</li>
{/if}
<li>
<button
class={twMerge(
'py-2 px-4 w-full font-normal text-left text-primary text-xs',
itemIndex === keyArrowPos || item.value === value
? 'bg-surface-secondary dark:bg-surface-tertiary'
: 'hover:bg-surface-hover',
endSnippet || item.__is_create ? 'flex items-center justify-between gap-2' : '',
itemButtonWrapperClasses,
item.disabled ? 'cursor-not-allowed text-disabled' : ''
)}
onclick={(e) => {
e.stopImmediatePropagation()
if (!item.disabled) onSelectValue(item)
}}
>
{@render startSnippet?.({ item, close: () => (open = false) })}
<!-- Label and subtitle stay one block so that, with an `endSnippet` making the button a
<!-- A closed list stays mounted for its collapse animation. Inert, its controls leave the tab
order at once, so Tab from a field rendered around it (`disablePortal`) skips them. -->
<div class="contents" inert={!isVisible}>
{@render header?.()}
{#if processedItems?.length === 0}
<div class="py-8 px-4 text-center text-primary text-xs">{noItemsMsg}</div>
{/if}
<ul
id={listId}
class={twMerge(
'flex-1 flex flex-col',
enableOverflowYAuto.current ? 'overflow-y-auto' : '',
ulClass
)}
>
{#each processedItems ?? [] as item, itemIndex}
{#if (item.__select_group && itemIndex === 0) || processedItems?.[itemIndex - 1]?.__select_group !== item.__select_group}
<li
class={twMerge(
'mx-4 pb-1 mb-2 text-xs font-semibold text-primary border-b border-border-light',
itemIndex === 0 ? 'mt-3' : 'mt-6'
)}
>
{item.__select_group}
</li>
{/if}
<li>
<button
class={twMerge(
'py-2 px-4 w-full font-normal text-left text-primary text-xs',
itemIndex === keyArrowPos || item.value === value
? 'bg-surface-secondary dark:bg-surface-tertiary'
: 'hover:bg-surface-hover',
endSnippet || item.__is_create ? 'flex items-center justify-between gap-2' : '',
itemButtonWrapperClasses,
item.disabled ? 'cursor-not-allowed text-disabled' : ''
)}
onclick={(e) => {
e.stopImmediatePropagation()
if (!item.disabled) onSelectValue(item)
}}
>
{@render startSnippet?.({ item, close: () => (open = false) })}
<!-- Label and subtitle stay one block so that, with an `endSnippet` making the button a
flex row, the subtitle sits under the name rather than beside the row's actions. -->
<div class="min-w-0 flex-1">
<span class={itemLabelWrapperClasses}>
{item.label || '\xa0'}
</span>
{#if item.subtitle}
<div class="text-2xs text-secondary">{item.subtitle}</div>
<div class="min-w-0 flex-1">
<span class={itemLabelWrapperClasses}>
{item.label || '\xa0'}
</span>
{#if item.subtitle}
<div class="text-2xs text-secondary">{item.subtitle}</div>
{/if}
</div>
{#if item.__is_create}
<PlusIcon class="inline ml-auto" size={16} />
{:else}
{@render endSnippet?.({ item, close: () => (open = false) })}
{/if}
</div>
{#if item.__is_create}
<PlusIcon class="inline ml-auto" size={16} />
{:else}
{@render endSnippet?.({ item, close: () => (open = false) })}
{/if}
</button>
</li>
{/each}
</ul>
{@render bottomSnippet?.({ close: () => (open = false) })}
</button>
</li>
{/each}
</ul>
{@render bottomSnippet?.({ close: () => (open = false) })}
</div>
</GenericDropdown>