Combobox
An input with a list of predefined items to select.
<script setup lang="ts">
import { h, useId } from 'vue';
import type { FunctionalComponent } from 'vue';
import { Combobox } from '@vase-ui/vue/combobox';
import styles from './index.module.css';
const id = useId();
const ICON_PROPS = {
width: '16',
height: '16',
viewBox: '0 0 16 16',
style: { display: 'block' },
};
const CheckIcon: FunctionalComponent = (_, { attrs }) =>
h('svg', { ...ICON_PROPS, fill: 'none', stroke: 'currentColor', ...attrs }, [
h('path', { d: 'm2.5 8.5 4 4 7-9' }),
]);
const XIcon: FunctionalComponent = (_, { attrs }) =>
h(
'svg',
{
...ICON_PROPS,
fill: 'none',
stroke: 'currentColor',
'stroke-linecap': 'square',
'stroke-linejoin': 'round',
...attrs,
},
[h('path', { d: 'm4.5 4.5 7 7m-7 0 7-7' })],
);
const CaretDownIcon: FunctionalComponent = (_, { attrs }) =>
h('svg', { ...ICON_PROPS, fill: 'currentColor', ...attrs }, [h('path', { d: 'M12 6H4l4 4.5z' })]);
interface Fruit {
label: string;
value: string;
}
const fruits: Fruit[] = [
{ label: 'Apple', value: 'apple' },
{ label: 'Banana', value: 'banana' },
{ label: 'Orange', value: 'orange' },
{ label: 'Pineapple', value: 'pineapple' },
{ label: 'Grape', value: 'grape' },
{ label: 'Mango', value: 'mango' },
{ label: 'Strawberry', value: 'strawberry' },
{ label: 'Blueberry', value: 'blueberry' },
{ label: 'Raspberry', value: 'raspberry' },
{ label: 'Blackberry', value: 'blackberry' },
{ label: 'Cherry', value: 'cherry' },
{ label: 'Peach', value: 'peach' },
{ label: 'Pear', value: 'pear' },
{ label: 'Plum', value: 'plum' },
{ label: 'Kiwi', value: 'kiwi' },
{ label: 'Watermelon', value: 'watermelon' },
{ label: 'Cantaloupe', value: 'cantaloupe' },
{ label: 'Honeydew', value: 'honeydew' },
{ label: 'Papaya', value: 'papaya' },
{ label: 'Guava', value: 'guava' },
{ label: 'Lychee', value: 'lychee' },
{ label: 'Pomegranate', value: 'pomegranate' },
{ label: 'Apricot', value: 'apricot' },
{ label: 'Grapefruit', value: 'grapefruit' },
{ label: 'Passionfruit', value: 'passionfruit' },
];
const popupHiddenClass = styles.PopupHidden;
</script>
<template>
<Combobox.Root :items="fruits">
<div :class="styles.Label">
<label :for="id">Choose a fruit</label>
<Combobox.InputGroup :class="styles.InputGroup">
<Combobox.Input :id="id" placeholder="e.g. Apple" :class="styles.Input" />
<div :class="styles.ActionButtons">
<Combobox.Clear :class="styles.Clear" aria-label="Clear selection">
<XIcon />
</Combobox.Clear>
<Combobox.Trigger :class="styles.Trigger" aria-label="Open popup">
<CaretDownIcon />
</Combobox.Trigger>
</div>
</Combobox.InputGroup>
</div>
<Combobox.Portal>
<Combobox.Positioner :class="styles.Positioner" :side-offset="4">
<Transition :enter-from-class="popupHiddenClass" :leave-to-class="popupHiddenClass" appear>
<Combobox.Popup :class="styles.Popup">
<Combobox.Empty>
<div :class="styles.Empty">No fruits found.</div>
</Combobox.Empty>
<Combobox.List :class="styles.List">
<template #item="{ item }">
<Combobox.Item v-slot="{ state }" :value="item" :class="styles.Item">
<span v-if="state.selected" :class="styles.ItemIndicator">
<CheckIcon />
</span>
<span :class="styles.ItemText">{{ item.label }}</span>
</Combobox.Item>
</template>
</Combobox.List>
</Combobox.Popup>
</Transition>
</Combobox.Positioner>
</Combobox.Portal>
</Combobox.Root>
</template>.InputGroup {
box-sizing: border-box;
position: relative;
width: 14rem;
height: 2rem;
border: 1px solid oklch(14.5% 0 0deg);
background-color: white;
@media (prefers-color-scheme: dark) {
border: 1px solid white;
background-color: oklch(14.5% 0 0deg);
}
&:focus-within {
outline: 2px solid oklch(14.5% 0 0deg);
outline-offset: -1px;
@media (prefers-color-scheme: dark) {
outline-color: white;
}
}
&:has(.Clear) .Input {
padding: 0 calc(0.5rem + 2rem * 2) 0 0.5rem;
}
}
.Input {
box-sizing: border-box;
padding: 0 calc(0.5rem + 2rem) 0 0.5rem;
margin: 0;
border: none;
border-radius: 0;
width: 100%;
height: 100%;
font-family: inherit;
font-size: 0.875rem;
line-height: 1.25rem;
font-weight: 400;
background-color: white;
color: oklch(14.5% 0 0deg);
@media (any-pointer: coarse) {
font-size: 1rem;
line-height: 1.5rem;
}
@media (prefers-color-scheme: dark) {
background-color: oklch(14.5% 0 0deg);
color: white;
}
&::placeholder {
color: oklch(55.6% 0 0deg);
@media (prefers-color-scheme: dark) {
color: oklch(70.8% 0 0deg);
}
}
&:focus {
outline: none;
}
}
.Label {
display: flex;
flex-direction: column;
gap: 0.25rem;
font-size: 0.875rem;
line-height: 1.25rem;
font-weight: 700;
color: oklch(14.5% 0 0deg);
position: relative;
@media (prefers-color-scheme: dark) {
color: white;
}
}
.ActionButtons {
box-sizing: border-box;
position: absolute;
display: flex;
align-items: center;
justify-content: center;
bottom: 0;
height: 100%;
right: 0;
border: none;
color: oklch(55.6% 0 0deg);
padding: 0;
@media (prefers-color-scheme: dark) {
color: oklch(70.8% 0 0deg);
}
}
.Trigger,
.Clear {
box-sizing: border-box;
display: flex;
align-items: center;
justify-content: center;
width: 1.5rem;
height: 100%;
color: oklch(14.5% 0 0deg);
border: none;
padding: 0;
background: none;
@media (prefers-color-scheme: dark) {
color: white;
}
}
.Positioner {
outline: 0;
}
.Popup {
box-sizing: border-box;
background-color: white;
color: oklch(14.5% 0 0deg);
width: var(--anchor-width);
max-width: var(--available-width);
transition:
opacity 0.1s,
transform 0.1s;
transform-origin: var(--transform-origin);
border: 1px solid oklch(14.5% 0 0deg);
box-shadow: 0.25rem 0.25rem 0 rgb(0 0 0 / 12%);
@media (prefers-color-scheme: dark) {
background-color: oklch(14.5% 0 0deg);
color: white;
border: 1px solid white;
box-shadow: none;
}
}
/* The enter-from and leave-to class of the `<Transition>` around the popup. */
.PopupHidden {
opacity: 0;
transform: scale(0.95);
}
.List {
box-sizing: border-box;
overflow-y: auto;
overscroll-behavior: contain;
padding-block: 0.25rem;
scroll-padding-block: 0.25rem;
outline: 0;
max-height: min(22.5rem, var(--available-height));
&[data-empty] {
padding: 0;
}
}
.Item {
box-sizing: border-box;
outline: 0;
cursor: default;
-webkit-user-select: none;
user-select: none;
padding-block: 0.5rem;
padding-left: 0.5rem;
padding-right: 0.5rem;
display: grid;
gap: 0.5rem;
align-items: center;
grid-template-columns: 1rem 1fr;
font-size: 0.875rem;
line-height: 1rem;
&[data-highlighted] {
z-index: 0;
position: relative;
color: white;
@media (prefers-color-scheme: dark) {
color: oklch(14.5% 0 0deg);
}
}
&[data-highlighted]::before {
content: '';
z-index: -1;
position: absolute;
inset-block: 0;
inset-inline: 0;
background-color: oklch(14.5% 0 0deg);
@media (prefers-color-scheme: dark) {
background-color: white;
}
}
}
.ItemText {
grid-column-start: 2;
}
.ItemIndicator {
grid-column-start: 1;
}
.Empty {
box-sizing: border-box;
padding: 1rem 1rem 1rem 0.5rem;
font-size: 0.875rem;
line-height: 1rem;
color: oklch(55.6% 0 0deg);
@media (prefers-color-scheme: dark) {
color: oklch(70.8% 0 0deg);
}
}<script setup lang="ts">
import { h, useId } from 'vue';
import type { FunctionalComponent } from 'vue';
import { Combobox } from '@vase-ui/vue/combobox';
const id = useId();
const ICON_PROPS = {
width: '16',
height: '16',
viewBox: '0 0 16 16',
style: { display: 'block' },
};
const CheckIcon: FunctionalComponent = (_, { attrs }) =>
h('svg', { ...ICON_PROPS, fill: 'none', stroke: 'currentColor', ...attrs }, [
h('path', { d: 'm2.5 8.5 4 4 7-9' }),
]);
const XIcon: FunctionalComponent = (_, { attrs }) =>
h(
'svg',
{
...ICON_PROPS,
fill: 'none',
stroke: 'currentColor',
'stroke-linecap': 'square',
'stroke-linejoin': 'round',
...attrs,
},
[h('path', { d: 'm4.5 4.5 7 7m-7 0 7-7' })],
);
const CaretDownIcon: FunctionalComponent = (_, { attrs }) =>
h('svg', { ...ICON_PROPS, fill: 'currentColor', ...attrs }, [h('path', { d: 'M12 6H4l4 4.5z' })]);
interface Fruit {
label: string;
value: string;
}
const fruits: Fruit[] = [
{ label: 'Apple', value: 'apple' },
{ label: 'Banana', value: 'banana' },
{ label: 'Orange', value: 'orange' },
{ label: 'Pineapple', value: 'pineapple' },
{ label: 'Grape', value: 'grape' },
{ label: 'Mango', value: 'mango' },
{ label: 'Strawberry', value: 'strawberry' },
{ label: 'Blueberry', value: 'blueberry' },
{ label: 'Raspberry', value: 'raspberry' },
{ label: 'Blackberry', value: 'blackberry' },
{ label: 'Cherry', value: 'cherry' },
{ label: 'Peach', value: 'peach' },
{ label: 'Pear', value: 'pear' },
{ label: 'Plum', value: 'plum' },
{ label: 'Kiwi', value: 'kiwi' },
{ label: 'Watermelon', value: 'watermelon' },
{ label: 'Cantaloupe', value: 'cantaloupe' },
{ label: 'Honeydew', value: 'honeydew' },
{ label: 'Papaya', value: 'papaya' },
{ label: 'Guava', value: 'guava' },
{ label: 'Lychee', value: 'lychee' },
{ label: 'Pomegranate', value: 'pomegranate' },
{ label: 'Apricot', value: 'apricot' },
{ label: 'Grapefruit', value: 'grapefruit' },
{ label: 'Passionfruit', value: 'passionfruit' },
];
const popupHiddenClass = 'scale-95 opacity-0';
</script>
<template>
<Combobox.Root :items="fruits">
<div
class="relative flex flex-col gap-1 text-sm leading-5 font-bold text-neutral-950 dark:text-white"
>
<label :for="id">Choose a fruit</label>
<Combobox.InputGroup
class="relative h-8 w-56 border border-neutral-950 bg-white dark:bg-neutral-950 focus-within:outline-2 focus-within:-outline-offset-1 focus-within:outline-neutral-950 dark:focus-within:outline-white dark:border-white [&>input]:pr-[calc(0.5rem+2rem)] has-[.combobox-clear]:[&>input]:pr-[calc(0.5rem+2rem*2)]"
>
<Combobox.Input
:id="id"
placeholder="e.g. Apple"
class="h-full w-full border-0 bg-white pl-2 dark:bg-neutral-950 text-sm any-pointer-coarse:text-base font-normal text-neutral-950 outline-none placeholder:text-neutral-500 dark:placeholder:text-neutral-400 dark:text-white"
/>
<div
class="absolute right-0 bottom-0 flex h-full items-center justify-center text-neutral-500 dark:text-neutral-400"
>
<Combobox.Clear
class="combobox-clear flex h-full w-6 items-center justify-center border-0 bg-transparent p-0 text-neutral-950 dark:text-white"
aria-label="Clear selection"
>
<XIcon />
</Combobox.Clear>
<Combobox.Trigger
class="flex h-full w-6 items-center justify-center border-0 bg-transparent p-0 text-neutral-950 dark:text-white"
aria-label="Open popup"
>
<CaretDownIcon />
</Combobox.Trigger>
</div>
</Combobox.InputGroup>
</div>
<Combobox.Portal>
<Combobox.Positioner class="outline-none" :side-offset="4">
<Transition :enter-from-class="popupHiddenClass" :leave-to-class="popupHiddenClass" appear>
<Combobox.Popup
class="w-[var(--anchor-width)] max-w-[var(--available-width)] origin-[var(--transform-origin)] border border-neutral-950 bg-white text-neutral-950 shadow-[0.25rem_0.25rem_0_rgb(0_0_0_/_12%)] transition-[scale,opacity] duration-100 dark:border-white dark:bg-neutral-950 dark:text-white dark:shadow-none"
>
<Combobox.Empty>
<div class="py-4 pr-4 pl-2 text-sm leading-4 text-neutral-500 dark:text-neutral-400">
No fruits found.
</div>
</Combobox.Empty>
<Combobox.List
class="max-h-[min(22.5rem,var(--available-height))] overflow-y-auto overscroll-contain py-1 scroll-py-1 outline-0 data-empty:p-0"
>
<template #item="{ item }">
<Combobox.Item
v-slot="{ state }"
:value="item"
class="grid cursor-default grid-cols-[1rem_1fr] items-center gap-2 p-2 text-sm leading-4 outline-none select-none data-highlighted:relative data-highlighted:z-0 data-highlighted:text-white data-highlighted:before:absolute data-highlighted:before:inset-0 data-highlighted:before:z-[-1] data-highlighted:before:bg-neutral-950 dark:data-highlighted:text-neutral-950 dark:data-highlighted:before:bg-white"
>
<span v-if="state.selected" class="col-start-1">
<CheckIcon />
</span>
<span class="col-start-2">{{ item.label }}</span>
</Combobox.Item>
</template>
</Combobox.List>
</Combobox.Popup>
</Transition>
</Combobox.Positioner>
</Combobox.Portal>
</Combobox.Root>
</template>Usage guidelines
- Combobox is a Select with a filter: Use Combobox when the value must be one of a set of predefined items. It works like Select, but the user types in an input to filter the items. Prefer Combobox to Select when the list is long enough to need a filter.
- Avoid for search widgets: Combobox does not accept free-form text. For a search widget, use Autocomplete.
- Avoid when there is no input: Use Select when the combobox has no input. Select has the accessibility features of a listbox with no input.
- Form controls must have an accessible name: Label the control with a native
<label>,<Field.Label>or<Combobox.Label>.<Combobox.Label>names the control: the input, or the trigger when the input is in the popup. When no label is visible, give the control anaria-label. See the forms guide. - Closing animations: Put a
<Transition appear>around<Combobox.Popup>. WithoutkeepMounted, the popup mounts at each open, so the<Transition>needsappear. The popup stays in the DOM until its leave ends. A close puts the text back at once. An open during the leave starts with that text and with each item. See the animation guide.
Anatomy
Import the component and assemble its parts:
<script setup lang="ts">
import { Combobox } from '@vase-ui/vue/combobox';
</script>
<template>
<Combobox.Root>
<Combobox.Label />
<Combobox.InputGroup>
<Combobox.Input />
<Combobox.Trigger />
<Combobox.Icon />
<Combobox.Clear />
<Combobox.Value />
<Combobox.Chips>
<Combobox.Chip>
<Combobox.ChipRemove />
</Combobox.Chip>
</Combobox.Chips>
</Combobox.InputGroup>
<Combobox.Portal>
<Combobox.Backdrop />
<Combobox.Positioner>
<Combobox.Popup>
<Combobox.Arrow />
<Combobox.Status />
<Combobox.Empty />
<Combobox.List>
<Combobox.Row>
<Combobox.Item v-slot="{ state }">
<span v-if="state.selected">✓</span>
</Combobox.Item>
</Combobox.Row>
<Combobox.Separator />
<Combobox.Group>
<Combobox.GroupLabel />
</Combobox.Group>
</Combobox.List>
</Combobox.Popup>
</Combobox.Positioner>
</Combobox.Portal>
</Combobox.Root>
</template>Item values
Each <Combobox.Item> takes a value prop that identifies it. Pass the item that the item slot of <Combobox.List> renders. The slot renders each filtered item, and gets { item, index }:
<script setup lang="ts">
import { Combobox } from '@vase-ui/vue/combobox';
const items = [
{ id: 'apple', label: 'Apple' },
{ id: 'banana', label: 'Banana' },
{ id: 'orange', label: 'Orange' },
];
</script>
<template>
<Combobox.Root :items="items">
<Combobox.Input />
<Combobox.Portal>
<Combobox.Positioner>
<Combobox.Popup>
<Combobox.List>
<template #item="{ item }">
<Combobox.Item :value="item">{{ item.label }}</Combobox.Item>
</template>
</Combobox.List>
</Combobox.Popup>
</Combobox.Positioner>
</Combobox.Portal>
</Combobox.Root>
</template>That item is the selected value. The modelValue and defaultValue props take it, and valueChange gives it. To store IDs instead, see Value selection with IDs.
Examples
Typed component
Combobox.Root is a generic component with the type arguments Value, Multiple and Item. Multiple defaults to false, and Item defaults to Value.
To fix the types, give the part its type arguments in an instantiation expression. Use the result as a component:
<script setup lang="ts">
import { Combobox } from '@vase-ui/vue/combobox';
interface User {
id: string;
name: string;
}
// The type arguments are `Value`, `Multiple` and `Item`.
const UserCombobox = Combobox.Root<string, false, User>;
const items = Combobox.createItems<User, string>([{ id: 'leslie', name: 'Leslie Alexander' }], {
getValue: (user) => user.id,
getLabel: (user) => user.name,
});
function log(value: string | null) {
console.log(value);
}
</script>
<template>
<UserCombobox :items="items" default-value="leslie" @value-change="log">
<!-- ... -->
</UserCombobox>
</template>A createItems() collection has items that differ from its selection values. The root needs the third type argument, Item, to accept such a collection. Without it, the type check refuses the collection.
A wrapper that declares defineProps<ComboboxRootProps<Value, Multiple, Item>>() and forwards the props with v-bind does not work. Vue gives an absent Boolean prop the value false. The wrapper then passes false for each Boolean prop that its consumer omits, such as open, and the combobox stays closed. Wrap a part shows a generic wrapper that keeps the types.
Value selection with IDs
When your app stores IDs and not item objects, use Combobox.createItems with getValue and getLabel. They derive the selection value and the display label of each item.
With static data, create the collection at module scope. The parameters of the two functions get their types from users. Give the derived ID to the value prop of <Combobox.Item>, not the item that the slot renders:
<script setup lang="ts">
import { Combobox } from '@vase-ui/vue/combobox';
const users = [
{ id: 'leslie', name: 'Leslie Alexander' },
{ id: 'kathryn', name: 'Kathryn Murphy' },
];
const items = Combobox.createItems(users, {
getValue: (user) => user.id,
getLabel: (user) => user.name,
});
</script>
<template>
<Combobox.Root :items="items">
<Combobox.List>
<template #item="{ item: user }">
<Combobox.Item :value="user.id">{{ user.name }}</Combobox.Item>
</template>
</Combobox.List>
</Combobox.Root>
</template>The props and the events of the selection use the derived IDs, and the list still gets the original items. The filter and the typeahead use the derived label.
When the data loads or changes at run time, make the collection in a computed. The collection then changes only with its data:
<script setup lang="ts">
import { computed, shallowRef } from 'vue';
import { Combobox } from '@vase-ui/vue/combobox';
interface User {
id: string;
name: string;
}
const users = shallowRef<User[]>([]);
const items = computed(() =>
Combobox.createItems(users.value, {
getValue: (user) => user.id,
getLabel: (user) => user.name,
}),
);
</script>
<template>
<Combobox.Root :items="items">
<!-- ... -->
</Combobox.Root>
</template><script setup lang="ts">
import { h, useId } from 'vue';
import type { FunctionalComponent } from 'vue';
import { Combobox } from '@vase-ui/vue/combobox';
import styles from './index.module.css';
const id = useId();
const ICON_PROPS = {
width: '16',
height: '16',
viewBox: '0 0 16 16',
style: { display: 'block' },
};
const CheckIcon: FunctionalComponent = (_, { attrs }) =>
h('svg', { ...ICON_PROPS, fill: 'none', stroke: 'currentColor', ...attrs }, [
h('path', { d: 'm2.5 8.5 4 4 7-9' }),
]);
const XIcon: FunctionalComponent = (_, { attrs }) =>
h(
'svg',
{
...ICON_PROPS,
fill: 'none',
stroke: 'currentColor',
'stroke-linecap': 'square',
'stroke-linejoin': 'round',
...attrs,
},
[h('path', { d: 'm4.5 4.5 7 7m-7 0 7-7' })],
);
const CaretDownIcon: FunctionalComponent = (_, { attrs }) =>
h('svg', { ...ICON_PROPS, fill: 'currentColor', ...attrs }, [h('path', { d: 'M12 6H4l4 4.5z' })]);
interface Fruit {
id: string;
name: string;
}
const fruits: Fruit[] = [
{ id: 'apple', name: 'Apple' },
{ id: 'banana', name: 'Banana' },
{ id: 'orange', name: 'Orange' },
{ id: 'pineapple', name: 'Pineapple' },
{ id: 'grape', name: 'Grape' },
{ id: 'mango', name: 'Mango' },
{ id: 'strawberry', name: 'Strawberry' },
{ id: 'blueberry', name: 'Blueberry' },
{ id: 'raspberry', name: 'Raspberry' },
{ id: 'blackberry', name: 'Blackberry' },
{ id: 'cherry', name: 'Cherry' },
{ id: 'peach', name: 'Peach' },
{ id: 'pear', name: 'Pear' },
{ id: 'plum', name: 'Plum' },
{ id: 'kiwi', name: 'Kiwi' },
{ id: 'watermelon', name: 'Watermelon' },
];
const items = Combobox.createItems(fruits, {
getValue: (fruit) => fruit.id,
getLabel: (fruit) => fruit.name,
});
const popupHiddenClass = styles.PopupHidden;
</script>
<template>
<Combobox.Root :items="items" default-value="banana">
<div :class="styles.Label">
<label :for="id">Choose a fruit</label>
<Combobox.InputGroup :class="styles.InputGroup">
<Combobox.Input :id="id" placeholder="e.g. Apple" :class="styles.Input" />
<div :class="styles.ActionButtons">
<Combobox.Clear :class="styles.Clear" aria-label="Clear selection">
<XIcon />
</Combobox.Clear>
<Combobox.Trigger :class="styles.Trigger" aria-label="Open popup">
<CaretDownIcon />
</Combobox.Trigger>
</div>
</Combobox.InputGroup>
</div>
<Combobox.Portal>
<Combobox.Positioner :class="styles.Positioner" :side-offset="4">
<Transition :enter-from-class="popupHiddenClass" :leave-to-class="popupHiddenClass" appear>
<Combobox.Popup :class="styles.Popup">
<Combobox.Empty>
<div :class="styles.Empty">No fruits found.</div>
</Combobox.Empty>
<Combobox.List :class="styles.List">
<template #item="{ item }">
<Combobox.Item v-slot="{ state }" :value="item.id" :class="styles.Item">
<span v-if="state.selected" :class="styles.ItemIndicator">
<CheckIcon />
</span>
<span :class="styles.ItemText">{{ item.name }}</span>
</Combobox.Item>
</template>
</Combobox.List>
</Combobox.Popup>
</Transition>
</Combobox.Positioner>
</Combobox.Portal>
</Combobox.Root>
</template>.InputGroup {
box-sizing: border-box;
position: relative;
width: 14rem;
height: 2rem;
border: 1px solid oklch(14.5% 0 0deg);
background-color: white;
@media (prefers-color-scheme: dark) {
border: 1px solid white;
background-color: oklch(14.5% 0 0deg);
}
&:focus-within {
outline: 2px solid oklch(14.5% 0 0deg);
outline-offset: -1px;
@media (prefers-color-scheme: dark) {
outline-color: white;
}
}
&:has(.Clear) .Input {
padding: 0 calc(0.5rem + 2rem * 2) 0 0.5rem;
}
}
.Input {
box-sizing: border-box;
padding: 0 calc(0.5rem + 2rem) 0 0.5rem;
margin: 0;
border: none;
border-radius: 0;
width: 100%;
height: 100%;
font-family: inherit;
font-size: 0.875rem;
line-height: 1.25rem;
font-weight: 400;
background-color: white;
color: oklch(14.5% 0 0deg);
@media (any-pointer: coarse) {
font-size: 1rem;
line-height: 1.5rem;
}
@media (prefers-color-scheme: dark) {
background-color: oklch(14.5% 0 0deg);
color: white;
}
&::placeholder {
color: oklch(55.6% 0 0deg);
@media (prefers-color-scheme: dark) {
color: oklch(70.8% 0 0deg);
}
}
&:focus {
outline: none;
}
}
.Label {
display: flex;
flex-direction: column;
gap: 0.25rem;
font-size: 0.875rem;
line-height: 1.25rem;
font-weight: 700;
color: oklch(14.5% 0 0deg);
position: relative;
@media (prefers-color-scheme: dark) {
color: white;
}
}
.ActionButtons {
box-sizing: border-box;
position: absolute;
display: flex;
align-items: center;
justify-content: center;
bottom: 0;
height: 100%;
right: 0;
border: none;
color: oklch(55.6% 0 0deg);
padding: 0;
@media (prefers-color-scheme: dark) {
color: oklch(70.8% 0 0deg);
}
}
.Trigger,
.Clear {
box-sizing: border-box;
display: flex;
align-items: center;
justify-content: center;
width: 1.5rem;
height: 100%;
color: oklch(14.5% 0 0deg);
border: none;
padding: 0;
background: none;
@media (prefers-color-scheme: dark) {
color: white;
}
}
.Positioner {
outline: 0;
}
.Popup {
box-sizing: border-box;
background-color: white;
color: oklch(14.5% 0 0deg);
width: var(--anchor-width);
max-width: var(--available-width);
transition:
opacity 0.1s,
transform 0.1s;
transform-origin: var(--transform-origin);
border: 1px solid oklch(14.5% 0 0deg);
box-shadow: 0.25rem 0.25rem 0 rgb(0 0 0 / 12%);
@media (prefers-color-scheme: dark) {
background-color: oklch(14.5% 0 0deg);
color: white;
border: 1px solid white;
box-shadow: none;
}
}
/* The enter-from and leave-to class of the `<Transition>` around the popup. */
.PopupHidden {
opacity: 0;
transform: scale(0.95);
}
.List {
box-sizing: border-box;
overflow-y: auto;
overscroll-behavior: contain;
padding-block: 0.25rem;
scroll-padding-block: 0.25rem;
outline: 0;
max-height: min(22.5rem, var(--available-height));
&[data-empty] {
padding: 0;
}
}
.Item {
box-sizing: border-box;
outline: 0;
cursor: default;
-webkit-user-select: none;
user-select: none;
padding-block: 0.5rem;
padding-left: 0.5rem;
padding-right: 0.5rem;
display: grid;
gap: 0.5rem;
align-items: center;
grid-template-columns: 1rem 1fr;
font-size: 0.875rem;
line-height: 1rem;
&[data-highlighted] {
z-index: 0;
position: relative;
color: white;
@media (prefers-color-scheme: dark) {
color: oklch(14.5% 0 0deg);
}
}
&[data-highlighted]::before {
content: '';
z-index: -1;
position: absolute;
inset-block: 0;
inset-inline: 0;
background-color: oklch(14.5% 0 0deg);
@media (prefers-color-scheme: dark) {
background-color: white;
}
}
}
.ItemText {
grid-column-start: 2;
}
.ItemIndicator {
grid-column-start: 1;
}
.Empty {
box-sizing: border-box;
padding: 1rem 1rem 1rem 0.5rem;
font-size: 0.875rem;
line-height: 1rem;
color: oklch(55.6% 0 0deg);
@media (prefers-color-scheme: dark) {
color: oklch(70.8% 0 0deg);
}
}<script setup lang="ts">
import { h, useId } from 'vue';
import type { FunctionalComponent } from 'vue';
import { Combobox } from '@vase-ui/vue/combobox';
const id = useId();
const ICON_PROPS = {
width: '16',
height: '16',
viewBox: '0 0 16 16',
style: { display: 'block' },
};
const CheckIcon: FunctionalComponent = (_, { attrs }) =>
h('svg', { ...ICON_PROPS, fill: 'none', stroke: 'currentColor', ...attrs }, [
h('path', { d: 'm2.5 8.5 4 4 7-9' }),
]);
const XIcon: FunctionalComponent = (_, { attrs }) =>
h(
'svg',
{
...ICON_PROPS,
fill: 'none',
stroke: 'currentColor',
'stroke-linecap': 'square',
'stroke-linejoin': 'round',
...attrs,
},
[h('path', { d: 'm4.5 4.5 7 7m-7 0 7-7' })],
);
const CaretDownIcon: FunctionalComponent = (_, { attrs }) =>
h('svg', { ...ICON_PROPS, fill: 'currentColor', ...attrs }, [h('path', { d: 'M12 6H4l4 4.5z' })]);
interface Fruit {
id: string;
name: string;
}
const fruits: Fruit[] = [
{ id: 'apple', name: 'Apple' },
{ id: 'banana', name: 'Banana' },
{ id: 'orange', name: 'Orange' },
{ id: 'pineapple', name: 'Pineapple' },
{ id: 'grape', name: 'Grape' },
{ id: 'mango', name: 'Mango' },
{ id: 'strawberry', name: 'Strawberry' },
{ id: 'blueberry', name: 'Blueberry' },
{ id: 'raspberry', name: 'Raspberry' },
{ id: 'blackberry', name: 'Blackberry' },
{ id: 'cherry', name: 'Cherry' },
{ id: 'peach', name: 'Peach' },
{ id: 'pear', name: 'Pear' },
{ id: 'plum', name: 'Plum' },
{ id: 'kiwi', name: 'Kiwi' },
{ id: 'watermelon', name: 'Watermelon' },
];
const items = Combobox.createItems(fruits, {
getValue: (fruit) => fruit.id,
getLabel: (fruit) => fruit.name,
});
const popupHiddenClass = 'scale-95 opacity-0';
</script>
<template>
<Combobox.Root :items="items" default-value="banana">
<div
class="relative flex flex-col gap-1 text-sm leading-5 font-bold text-neutral-950 dark:text-white"
>
<label :for="id">Choose a fruit</label>
<Combobox.InputGroup
class="relative h-8 w-56 border border-neutral-950 bg-white dark:bg-neutral-950 focus-within:outline-2 focus-within:-outline-offset-1 focus-within:outline-neutral-950 dark:focus-within:outline-white dark:border-white [&>input]:pr-[calc(0.5rem+2rem)] has-[.combobox-clear]:[&>input]:pr-[calc(0.5rem+2rem*2)]"
>
<Combobox.Input
:id="id"
placeholder="e.g. Apple"
class="h-full w-full border-0 bg-white pl-2 dark:bg-neutral-950 text-sm any-pointer-coarse:text-base font-normal text-neutral-950 outline-none placeholder:text-neutral-500 dark:placeholder:text-neutral-400 dark:text-white"
/>
<div
class="absolute right-0 bottom-0 flex h-full items-center justify-center text-neutral-500 dark:text-neutral-400"
>
<Combobox.Clear
class="combobox-clear flex h-full w-6 items-center justify-center border-0 bg-transparent p-0 text-neutral-950 dark:text-white"
aria-label="Clear selection"
>
<XIcon />
</Combobox.Clear>
<Combobox.Trigger
class="flex h-full w-6 items-center justify-center border-0 bg-transparent p-0 text-neutral-950 dark:text-white"
aria-label="Open popup"
>
<CaretDownIcon />
</Combobox.Trigger>
</div>
</Combobox.InputGroup>
</div>
<Combobox.Portal>
<Combobox.Positioner class="outline-none" :side-offset="4">
<Transition :enter-from-class="popupHiddenClass" :leave-to-class="popupHiddenClass" appear>
<Combobox.Popup
class="w-[var(--anchor-width)] max-w-[var(--available-width)] origin-[var(--transform-origin)] border border-neutral-950 bg-white text-neutral-950 shadow-[0.25rem_0.25rem_0_rgb(0_0_0_/_12%)] transition-[scale,opacity] duration-100 dark:border-white dark:bg-neutral-950 dark:text-white dark:shadow-none"
>
<Combobox.Empty>
<div class="py-4 pr-4 pl-2 text-sm leading-4 text-neutral-500 dark:text-neutral-400">
No fruits found.
</div>
</Combobox.Empty>
<Combobox.List
class="max-h-[min(22.5rem,var(--available-height))] overflow-y-auto overscroll-contain py-1 scroll-py-1 outline-0 data-empty:p-0"
>
<template #item="{ item }">
<Combobox.Item
v-slot="{ state }"
:value="item.id"
class="grid cursor-default grid-cols-[1rem_1fr] items-center gap-2 p-2 text-sm leading-4 outline-none select-none data-highlighted:relative data-highlighted:z-0 data-highlighted:text-white data-highlighted:before:absolute data-highlighted:before:inset-0 data-highlighted:before:z-[-1] data-highlighted:before:bg-neutral-950 dark:data-highlighted:text-neutral-950 dark:data-highlighted:before:bg-white"
>
<span v-if="state.selected" class="col-start-1">
<CheckIcon />
</span>
<span class="col-start-2">{{ item.name }}</span>
</Combobox.Item>
</template>
</Combobox.List>
</Combobox.Popup>
</Transition>
</Combobox.Positioner>
</Combobox.Portal>
</Combobox.Root>
</template>Use primitive items for a simple list. Use object values when the selected record is useful state of the app. Use createItems() when the selection needs a stable primitive ID and the list uses object records.
Stable IDs keep the match of the items when a data library replaces the row objects at a refetch. With object values, use isItemEqualToValue to compare their IDs.
When a server filters the results, items is the list of records that the app knows. filteredItems is the window of results that the popup shows. Give filteredItems the source items, not the derived values. Keep the flat or grouped structure of items:
<script setup lang="ts">
import { computed, shallowRef } from 'vue';
import { Combobox } from '@vase-ui/vue/combobox';
interface User {
id: string;
name: string;
}
const knownUsers = shallowRef<User[]>([]);
const searchResults = shallowRef<User[]>([]);
const selectedUserId = shallowRef<string | null>(null);
const items = computed(() =>
Combobox.createItems(knownUsers.value, {
getValue: (user) => user.id,
getLabel: (user) => user.name,
}),
);
</script>
<template>
<Combobox.Root v-model="selectedUserId" :items="items" :filtered-items="searchResults">
<!-- ... -->
</Combobox.Root>
</template>Put the record of the selected user in knownUsers. Its label then stays available while the record is not in searchResults. Or give itemToStringLabel, when the selected value alone gives the label.
Multiple select
Add the multiple prop to <Combobox.Root> to let the user select more than one item. The value is then an array. Render each selected item as a <Combobox.Chip> in <Combobox.Chips>. The user can remove a chip.
<script setup lang="ts">
import { h, useId } from 'vue';
import type { FunctionalComponent } from 'vue';
import { Combobox } from '@vase-ui/vue/combobox';
import styles from './index.module.css';
const id = useId();
const ICON_PROPS = {
width: '16',
height: '16',
viewBox: '0 0 16 16',
style: { display: 'block' },
};
const CheckIcon: FunctionalComponent = (_, { attrs }) =>
h('svg', { ...ICON_PROPS, fill: 'none', stroke: 'currentColor', ...attrs }, [
h('path', { d: 'm2.5 8.5 4 4 7-9' }),
]);
const XIcon: FunctionalComponent = (_, { attrs }) =>
h(
'svg',
{
...ICON_PROPS,
fill: 'none',
stroke: 'currentColor',
'stroke-linecap': 'square',
'stroke-linejoin': 'round',
...attrs,
},
[h('path', { d: 'm4.5 4.5 7 7m-7 0 7-7' })],
);
interface ProgrammingLanguage {
id: string;
value: string;
}
const langs: ProgrammingLanguage[] = [
{ id: 'js', value: 'JavaScript' },
{ id: 'ts', value: 'TypeScript' },
{ id: 'py', value: 'Python' },
{ id: 'java', value: 'Java' },
{ id: 'cpp', value: 'C++' },
{ id: 'cs', value: 'C#' },
{ id: 'php', value: 'PHP' },
{ id: 'ruby', value: 'Ruby' },
{ id: 'go', value: 'Go' },
{ id: 'rust', value: 'Rust' },
{ id: 'swift', value: 'Swift' },
];
const popupHiddenClass = styles.PopupHidden;
</script>
<template>
<Combobox.Root :items="langs" multiple>
<div :class="styles.Container">
<label :class="styles.Label" :for="id">Programming languages</label>
<Combobox.InputGroup :class="styles.InputGroup">
<Combobox.Value v-slot="{ value }">
<Combobox.Chips
:class="styles.Chips"
:aria-label="value.length > 0 ? 'Selected languages' : undefined"
>
<Combobox.Chip
v-for="language in value"
:key="language.id"
:class="styles.Chip"
:aria-label="language.value"
aria-description="Press Backspace or Delete to remove"
>
{{ language.value }}
<Combobox.ChipRemove
:class="styles.ChipRemove"
:aria-label="`Remove ${language.value}`"
>
<XIcon />
</Combobox.ChipRemove>
</Combobox.Chip>
<Combobox.Input
:id="id"
:placeholder="value.length > 0 ? '' : 'e.g. TypeScript'"
:aria-description="
value.length > 0
? `${value.length} selected. From the start of the input, press Left Arrow to focus the selected items`
: undefined
"
:class="styles.Input"
/>
</Combobox.Chips>
</Combobox.Value>
</Combobox.InputGroup>
</div>
<Combobox.Portal>
<Combobox.Positioner :class="styles.Positioner" :side-offset="4">
<Transition :enter-from-class="popupHiddenClass" :leave-to-class="popupHiddenClass" appear>
<Combobox.Popup :class="styles.Popup">
<Combobox.Empty>
<div :class="styles.Empty">No languages found.</div>
</Combobox.Empty>
<Combobox.List>
<template #item="{ item: language }">
<Combobox.Item v-slot="{ state }" :class="styles.Item" :value="language">
<span v-if="state.selected" :class="styles.ItemIndicator">
<CheckIcon />
</span>
<span :class="styles.ItemText">{{ language.value }}</span>
</Combobox.Item>
</template>
</Combobox.List>
</Combobox.Popup>
</Transition>
</Combobox.Positioner>
</Combobox.Portal>
</Combobox.Root>
</template>.Container {
max-width: 28rem;
display: flex;
flex-direction: column;
gap: 0.25rem;
}
.Label {
display: flex;
flex-direction: column;
gap: 0.25rem;
font-size: 0.875rem;
line-height: 1.25rem;
font-weight: 700;
color: oklch(14.5% 0 0deg);
@media (prefers-color-scheme: dark) {
color: white;
}
}
.InputGroup {
box-sizing: border-box;
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 0.125rem;
border: 1px solid oklch(14.5% 0 0deg);
background-color: white;
min-height: 2rem;
padding: 0.25rem 0.5rem;
width: 16rem;
cursor: text;
@media (min-width: 32rem) {
width: 22rem;
}
@media (prefers-color-scheme: dark) {
border: 1px solid white;
background-color: oklch(14.5% 0 0deg);
}
&:has(.Chip) {
padding-inline: 0.25rem;
}
&:focus-within {
outline: 2px solid oklch(14.5% 0 0deg);
outline-offset: -1px;
@media (prefers-color-scheme: dark) {
outline-color: white;
}
}
}
.Chips {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 0.25rem;
width: 100%;
}
.Chip {
box-sizing: border-box;
display: flex;
align-items: center;
min-height: calc(1.5rem - 2px);
background-color: oklch(97% 0 0deg);
color: oklch(14.5% 0 0deg);
font-size: 0.875rem;
line-height: 1;
padding: 0 0.2rem 0 0.4rem;
overflow: hidden;
gap: 0.25rem;
outline: 0;
cursor: default;
@media (prefers-color-scheme: dark) {
background-color: oklch(26.9% 0 0deg);
color: white;
}
&:focus-within {
background-color: oklch(14.5% 0 0deg);
color: white;
@media (prefers-color-scheme: dark) {
background-color: white;
color: oklch(14.5% 0 0deg);
}
}
@media (hover: hover) {
&[data-highlighted] {
background-color: oklch(14.5% 0 0deg);
color: white;
@media (prefers-color-scheme: dark) {
background-color: white;
color: oklch(14.5% 0 0deg);
}
}
}
}
.ChipButton {
display: flex;
align-items: center;
background: none;
border: none;
padding: 0.125rem 0.25rem 0.125rem 0.5rem;
font-size: inherit;
color: inherit;
cursor: default;
flex: 1;
outline: 0;
}
.ChipRemove {
box-sizing: border-box;
width: 1rem;
height: 1rem;
padding: 0;
border: none;
background: none;
display: flex;
align-items: center;
justify-content: center;
color: inherit;
@media (hover: hover) {
&:hover {
background-color: oklch(92.2% 0 0deg);
@media (prefers-color-scheme: dark) {
background-color: oklch(37.1% 0 0deg);
}
}
}
}
.Chip:focus-within .ChipRemove {
@media (hover: hover) {
&:hover {
background-color: oklch(37.1% 0 0deg);
@media (prefers-color-scheme: dark) {
background-color: oklch(92.2% 0 0deg);
}
}
}
}
.Input {
flex: 1;
box-sizing: border-box;
padding: 0;
margin: 0;
border: none;
border-radius: 0;
height: calc(1.5rem - 2px);
font-family: inherit;
font-size: 0.875rem;
line-height: 1.25rem;
font-weight: 400;
background-color: white;
color: oklch(14.5% 0 0deg);
min-width: 3rem;
@media (any-pointer: coarse) {
font-size: 1rem;
line-height: 1.5rem;
}
@media (prefers-color-scheme: dark) {
background-color: oklch(14.5% 0 0deg);
color: white;
}
&::placeholder {
color: oklch(55.6% 0 0deg);
@media (prefers-color-scheme: dark) {
color: oklch(70.8% 0 0deg);
}
}
&:focus {
outline: none;
}
}
.Positioner {
outline: 0;
z-index: 50;
}
.Popup {
box-sizing: border-box;
padding-block: 0.25rem;
background-color: white;
color: oklch(14.5% 0 0deg);
width: var(--anchor-width);
max-width: var(--available-width);
max-height: min(var(--available-height), 24.5rem);
overflow-y: auto;
scroll-padding-block: 0.25rem;
overscroll-behavior: contain;
transition:
opacity 0.1s,
transform 0.1s;
transform-origin: var(--transform-origin);
border: 1px solid oklch(14.5% 0 0deg);
box-shadow: 0.25rem 0.25rem 0 rgb(0 0 0 / 12%);
@media (prefers-color-scheme: dark) {
background-color: oklch(14.5% 0 0deg);
color: white;
border: 1px solid white;
box-shadow: none;
}
}
/* The enter-from and leave-to class of the `<Transition>` around the popup. */
.PopupHidden {
opacity: 0;
transform: scale(0.95);
}
.Item {
box-sizing: border-box;
outline: 0;
cursor: default;
-webkit-user-select: none;
user-select: none;
padding-block: 0.5rem;
padding-left: 0.5rem;
padding-right: 0.5rem;
display: grid;
gap: 0.5rem;
align-items: center;
grid-template-columns: 1rem 1fr;
font-size: 0.875rem;
line-height: 1rem;
&[aria-selected='true'] {
z-index: 0;
position: relative;
color: oklch(14.5% 0 0deg);
@media (prefers-color-scheme: dark) {
color: white;
}
}
&[aria-selected='true']::before,
&[data-highlighted]::before {
content: '';
z-index: -1;
position: absolute;
inset-block: 0;
inset-inline: 0;
}
@media (hover: hover) {
&[data-highlighted] {
z-index: 0;
position: relative;
color: white;
@media (prefers-color-scheme: dark) {
color: oklch(14.5% 0 0deg);
}
}
&[data-highlighted]::before {
background-color: oklch(14.5% 0 0deg);
@media (prefers-color-scheme: dark) {
background-color: white;
}
}
}
}
.ItemText {
grid-column-start: 2;
}
.ItemIndicator {
grid-column-start: 1;
}
.ItemName {
font-weight: 700;
color: inherit;
}
.Empty {
box-sizing: border-box;
font-size: 0.875rem;
line-height: 1rem;
color: oklch(55.6% 0 0deg);
padding: 0.5rem 1rem 0.5rem 0.5rem;
@media (prefers-color-scheme: dark) {
color: oklch(70.8% 0 0deg);
}
}<script setup lang="ts">
import { h, useId } from 'vue';
import type { FunctionalComponent } from 'vue';
import { Combobox } from '@vase-ui/vue/combobox';
const id = useId();
const ICON_PROPS = {
width: '16',
height: '16',
viewBox: '0 0 16 16',
style: { display: 'block' },
};
const CheckIcon: FunctionalComponent = (_, { attrs }) =>
h('svg', { ...ICON_PROPS, fill: 'none', stroke: 'currentColor', ...attrs }, [
h('path', { d: 'm2.5 8.5 4 4 7-9' }),
]);
const XIcon: FunctionalComponent = (_, { attrs }) =>
h(
'svg',
{
...ICON_PROPS,
fill: 'none',
stroke: 'currentColor',
'stroke-linecap': 'square',
'stroke-linejoin': 'round',
...attrs,
},
[h('path', { d: 'm4.5 4.5 7 7m-7 0 7-7' })],
);
interface ProgrammingLanguage {
id: string;
value: string;
}
const langs: ProgrammingLanguage[] = [
{ id: 'js', value: 'JavaScript' },
{ id: 'ts', value: 'TypeScript' },
{ id: 'py', value: 'Python' },
{ id: 'java', value: 'Java' },
{ id: 'cpp', value: 'C++' },
{ id: 'cs', value: 'C#' },
{ id: 'php', value: 'PHP' },
{ id: 'ruby', value: 'Ruby' },
{ id: 'go', value: 'Go' },
{ id: 'rust', value: 'Rust' },
{ id: 'swift', value: 'Swift' },
];
const popupHiddenClass = 'scale-95 opacity-0';
</script>
<template>
<Combobox.Root :items="langs" multiple>
<div class="max-w-md flex flex-col gap-1">
<label
class="flex flex-col gap-1 text-sm leading-5 font-bold text-neutral-950 dark:text-white"
:for="id"
>Programming languages</label
>
<Combobox.InputGroup
class="flex min-h-8 w-64 cursor-text flex-wrap items-center gap-0.5 border border-neutral-950 bg-white dark:bg-neutral-950 px-2 py-1 focus-within:outline-2 focus-within:-outline-offset-1 focus-within:outline-neutral-950 dark:focus-within:outline-white has-[button]:px-1 dark:border-white min-[32rem]:w-[22rem]"
>
<Combobox.Value v-slot="{ value }">
<Combobox.Chips
class="flex w-full flex-wrap items-center gap-1"
:aria-label="value.length > 0 ? 'Selected languages' : undefined"
>
<Combobox.Chip
v-for="language in value"
:key="language.id"
class="group flex min-h-[calc(1.5rem-2px)] cursor-default items-center gap-1 overflow-hidden bg-neutral-100 py-0 pr-[0.2rem] pl-[0.4rem] text-sm leading-none text-neutral-950 outline-none focus-within:bg-neutral-950 focus-within:text-white [@media(hover:hover)]:data-highlighted:bg-neutral-950 [@media(hover:hover)]:data-highlighted:text-white dark:bg-neutral-800 dark:text-white dark:focus-within:bg-white dark:focus-within:text-neutral-950 dark:[@media(hover:hover)]:data-highlighted:bg-white dark:[@media(hover:hover)]:data-highlighted:text-neutral-950"
:aria-label="language.value"
aria-description="Press Backspace or Delete to remove"
>
{{ language.value }}
<Combobox.ChipRemove
class="flex size-4 items-center justify-center border-0 bg-transparent p-0 text-inherit hover:bg-neutral-200 group-focus-within:hover:bg-neutral-700 dark:hover:bg-neutral-700 dark:group-focus-within:hover:bg-neutral-200"
:aria-label="`Remove ${language.value}`"
>
<XIcon />
</Combobox.ChipRemove>
</Combobox.Chip>
<Combobox.Input
:id="id"
:placeholder="value.length > 0 ? '' : 'e.g. TypeScript'"
:aria-description="
value.length > 0
? `${value.length} selected. From the start of the input, press Left Arrow to focus the selected items`
: undefined
"
class="h-[calc(1.5rem-2px)] min-w-12 flex-1 border-0 bg-white p-0 text-sm any-pointer-coarse:text-base dark:bg-neutral-950 font-normal text-neutral-950 outline-none placeholder:text-neutral-500 dark:placeholder:text-neutral-400 dark:text-white"
/>
</Combobox.Chips>
</Combobox.Value>
</Combobox.InputGroup>
</div>
<Combobox.Portal>
<Combobox.Positioner class="z-50 outline-none" :side-offset="4">
<Transition :enter-from-class="popupHiddenClass" :leave-to-class="popupHiddenClass" appear>
<Combobox.Popup
class="w-[var(--anchor-width)] max-h-[min(var(--available-height),24.5rem)] max-w-[var(--available-width)] origin-[var(--transform-origin)] overflow-y-auto overscroll-contain border border-neutral-950 bg-white py-1 text-neutral-950 shadow-[0.25rem_0.25rem_0_rgb(0_0_0_/_12%)] transition-[scale,opacity] dark:border-white dark:bg-neutral-950 dark:text-white dark:shadow-none"
>
<Combobox.Empty>
<div class="py-2 pr-4 pl-2 text-sm leading-4 text-neutral-500 dark:text-neutral-400">
No languages found.
</div>
</Combobox.Empty>
<Combobox.List>
<template #item="{ item: language }">
<Combobox.Item
v-slot="{ state }"
class="grid cursor-default grid-cols-[1rem_1fr] items-center gap-2 p-2 text-sm leading-4 outline-none select-none aria-selected:relative aria-selected:z-0 aria-selected:text-neutral-950 aria-selected:before:absolute aria-selected:before:inset-0 aria-selected:before:z-[-1] [@media(hover:hover)]:data-highlighted:relative [@media(hover:hover)]:data-highlighted:z-0 [@media(hover:hover)]:data-highlighted:text-white [@media(hover:hover)]:data-highlighted:before:absolute [@media(hover:hover)]:data-highlighted:before:inset-0 [@media(hover:hover)]:data-highlighted:before:z-[-1] [@media(hover:hover)]:data-highlighted:before:bg-neutral-950 dark:aria-selected:text-white dark:[@media(hover:hover)]:data-highlighted:text-neutral-950 dark:[@media(hover:hover)]:data-highlighted:before:bg-white"
:value="language"
>
<span v-if="state.selected" class="col-start-1">
<CheckIcon />
</span>
<span class="col-start-2">{{ language.value }}</span>
</Combobox.Item>
</template>
</Combobox.List>
</Combobox.Popup>
</Transition>
</Combobox.Positioner>
</Combobox.Portal>
</Combobox.Root>
</template>To let screen readers announce how to reach and remove the chips, give aria-description to <Combobox.Chip> and <Combobox.Input>. Also give aria-label to <Combobox.Chips> and <Combobox.ChipRemove>. Vase UI does not ship these strings. Translate them with the rest of your interface.
To limit the visible chips, slice the selected values that <Combobox.Value> gives to its slot:
<script setup lang="ts">
import { Combobox } from '@vase-ui/vue/combobox';
const CHIP_LIMIT = 3;
const fruits = ['Apple', 'Banana', 'Cherry', 'Grape', 'Mango'];
</script>
<template>
<Combobox.Root multiple :items="fruits">
<Combobox.InputGroup>
<Combobox.Value v-slot="{ value: selectedValue }">
<Combobox.Chips>
<Combobox.Chip
v-for="item in selectedValue.slice(0, CHIP_LIMIT)"
:key="item"
aria-description="Press Backspace or Delete to remove"
>
{{ item }}
<Combobox.ChipRemove :aria-label="`Remove ${item}`" />
</Combobox.Chip>
<span v-if="selectedValue.length > CHIP_LIMIT">
+{{ selectedValue.length - CHIP_LIMIT }} more
</span>
<Combobox.Input
:aria-description="
selectedValue.length > 0
? `${selectedValue.length} selected. From the start of the input, press Left Arrow to focus the selected items`
: undefined
"
/>
</Combobox.Chips>
</Combobox.Value>
</Combobox.InputGroup>
<!-- ... -->
</Combobox.Root>
</template>Keeping the filter after selection
In multiple mode, a selection clears the filter that the user typed. When the input is outside the popup, that selection also closes the popup. To let the user pick more than one result of a query, cancel the change request that does this.
The request to cancel depends on where the input is. When the input is outside the popup, cancel the close request in openChange. That request has the reason item-press:
<script setup lang="ts">
import { Combobox } from '@vase-ui/vue/combobox';
function keepPopupOpen(open: boolean, eventDetails: Combobox.Root.OpenChangeEventDetails) {
if (!open && eventDetails.reason === 'item-press') {
eventDetails.cancel();
}
}
</script>
<template>
<Combobox.Root multiple @open-change="keepPopupOpen">
<!-- ... -->
</Combobox.Root>
</template>When the input is inside the popup, cancel the request that clears the input in inputValueChange. That request has eventDetails.isItemPress:
<script setup lang="ts">
import { Combobox } from '@vase-ui/vue/combobox';
function keepFilter(_inputValue: string, eventDetails: Combobox.Root.ChangeEventDetails) {
if (eventDetails.isItemPress) {
eventDetails.cancel();
}
}
</script>
<template>
<Combobox.Root multiple @input-value-change="keepFilter">
<!-- ... -->
</Combobox.Root>
</template>The typed filter still resets when the popup closes.
Input inside popup
<Combobox.Input> can be inside <Combobox.Popup>. The combobox is then a select popup with a search field.
<script setup lang="ts">
import { h } from 'vue';
import type { FunctionalComponent } from 'vue';
import { Combobox } from '@vase-ui/vue/combobox';
import styles from './index.module.css';
const ICON_PROPS = {
width: '16',
height: '16',
viewBox: '0 0 16 16',
style: { display: 'block' },
};
const CaretUpDownIcon: FunctionalComponent = (_, { attrs }) =>
h('svg', { ...ICON_PROPS, fill: 'currentColor', ...attrs }, [
h('path', { d: 'M11 10H5l3 3.5zm0-4H5l3-3.5z' }),
]);
const CheckIcon: FunctionalComponent = (_, { attrs }) =>
h('svg', { ...ICON_PROPS, fill: 'none', stroke: 'currentColor', ...attrs }, [
h('path', { d: 'm2.5 8.5 4 4 7-9' }),
]);
interface Country {
code: string;
value: string;
continent: string;
label: string;
}
const countries: Country[] = [
{ code: 'af', value: 'afghanistan', label: 'Afghanistan', continent: 'Asia' },
{ code: 'al', value: 'albania', label: 'Albania', continent: 'Europe' },
{ code: 'dz', value: 'algeria', label: 'Algeria', continent: 'Africa' },
{ code: 'ad', value: 'andorra', label: 'Andorra', continent: 'Europe' },
{ code: 'ao', value: 'angola', label: 'Angola', continent: 'Africa' },
{ code: 'ar', value: 'argentina', label: 'Argentina', continent: 'South America' },
{ code: 'am', value: 'armenia', label: 'Armenia', continent: 'Asia' },
{ code: 'au', value: 'australia', label: 'Australia', continent: 'Oceania' },
{ code: 'at', value: 'austria', label: 'Austria', continent: 'Europe' },
{ code: 'az', value: 'azerbaijan', label: 'Azerbaijan', continent: 'Asia' },
{ code: 'bs', value: 'bahamas', label: 'Bahamas', continent: 'North America' },
{ code: 'bh', value: 'bahrain', label: 'Bahrain', continent: 'Asia' },
{ code: 'bd', value: 'bangladesh', label: 'Bangladesh', continent: 'Asia' },
{ code: 'bb', value: 'barbados', label: 'Barbados', continent: 'North America' },
{ code: 'by', value: 'belarus', label: 'Belarus', continent: 'Europe' },
{ code: 'be', value: 'belgium', label: 'Belgium', continent: 'Europe' },
{ code: 'bz', value: 'belize', label: 'Belize', continent: 'North America' },
{ code: 'bj', value: 'benin', label: 'Benin', continent: 'Africa' },
{ code: 'bt', value: 'bhutan', label: 'Bhutan', continent: 'Asia' },
{ code: 'bo', value: 'bolivia', label: 'Bolivia', continent: 'South America' },
{
code: 'ba',
value: 'bosnia-and-herzegovina',
label: 'Bosnia and Herzegovina',
continent: 'Europe',
},
{ code: 'bw', value: 'botswana', label: 'Botswana', continent: 'Africa' },
{ code: 'br', value: 'brazil', label: 'Brazil', continent: 'South America' },
{ code: 'bn', value: 'brunei', label: 'Brunei', continent: 'Asia' },
{ code: 'bg', value: 'bulgaria', label: 'Bulgaria', continent: 'Europe' },
{ code: 'bf', value: 'burkina-faso', label: 'Burkina Faso', continent: 'Africa' },
{ code: 'bi', value: 'burundi', label: 'Burundi', continent: 'Africa' },
{ code: 'kh', value: 'cambodia', label: 'Cambodia', continent: 'Asia' },
{ code: 'cm', value: 'cameroon', label: 'Cameroon', continent: 'Africa' },
{ code: 'ca', value: 'canada', label: 'Canada', continent: 'North America' },
{ code: 'cv', value: 'cape-verde', label: 'Cape Verde', continent: 'Africa' },
{
code: 'cf',
value: 'central-african-republic',
label: 'Central African Republic',
continent: 'Africa',
},
{ code: 'td', value: 'chad', label: 'Chad', continent: 'Africa' },
{ code: 'cl', value: 'chile', label: 'Chile', continent: 'South America' },
{ code: 'cn', value: 'china', label: 'China', continent: 'Asia' },
{ code: 'co', value: 'colombia', label: 'Colombia', continent: 'South America' },
{ code: 'km', value: 'comoros', label: 'Comoros', continent: 'Africa' },
{ code: 'cg', value: 'congo', label: 'Congo', continent: 'Africa' },
{ code: 'cr', value: 'costa-rica', label: 'Costa Rica', continent: 'North America' },
{ code: 'hr', value: 'croatia', label: 'Croatia', continent: 'Europe' },
{ code: 'cu', value: 'cuba', label: 'Cuba', continent: 'North America' },
{ code: 'cy', value: 'cyprus', label: 'Cyprus', continent: 'Asia' },
{ code: 'cz', value: 'czech-republic', label: 'Czech Republic', continent: 'Europe' },
{ code: 'dk', value: 'denmark', label: 'Denmark', continent: 'Europe' },
{ code: 'dj', value: 'djibouti', label: 'Djibouti', continent: 'Africa' },
{ code: 'dm', value: 'dominica', label: 'Dominica', continent: 'North America' },
{
code: 'do',
value: 'dominican-republic',
label: 'Dominican Republic',
continent: 'North America',
},
{ code: 'ec', value: 'ecuador', label: 'Ecuador', continent: 'South America' },
{ code: 'eg', value: 'egypt', label: 'Egypt', continent: 'Africa' },
{ code: 'sv', value: 'el-salvador', label: 'El Salvador', continent: 'North America' },
{ code: 'gq', value: 'equatorial-guinea', label: 'Equatorial Guinea', continent: 'Africa' },
{ code: 'er', value: 'eritrea', label: 'Eritrea', continent: 'Africa' },
{ code: 'ee', value: 'estonia', label: 'Estonia', continent: 'Europe' },
{ code: 'et', value: 'ethiopia', label: 'Ethiopia', continent: 'Africa' },
{ code: 'fj', value: 'fiji', label: 'Fiji', continent: 'Oceania' },
{ code: 'fi', value: 'finland', label: 'Finland', continent: 'Europe' },
{ code: 'fr', value: 'france', label: 'France', continent: 'Europe' },
{ code: 'ga', value: 'gabon', label: 'Gabon', continent: 'Africa' },
{ code: 'gm', value: 'gambia', label: 'Gambia', continent: 'Africa' },
{ code: 'ge', value: 'georgia', label: 'Georgia', continent: 'Asia' },
{ code: 'de', value: 'germany', label: 'Germany', continent: 'Europe' },
{ code: 'gh', value: 'ghana', label: 'Ghana', continent: 'Africa' },
{ code: 'gr', value: 'greece', label: 'Greece', continent: 'Europe' },
{ code: 'gd', value: 'grenada', label: 'Grenada', continent: 'North America' },
{ code: 'gt', value: 'guatemala', label: 'Guatemala', continent: 'North America' },
{ code: 'gn', value: 'guinea', label: 'Guinea', continent: 'Africa' },
{ code: 'gw', value: 'guinea-bissau', label: 'Guinea-Bissau', continent: 'Africa' },
{ code: 'gy', value: 'guyana', label: 'Guyana', continent: 'South America' },
{ code: 'ht', value: 'haiti', label: 'Haiti', continent: 'North America' },
{ code: 'hn', value: 'honduras', label: 'Honduras', continent: 'North America' },
{ code: 'hu', value: 'hungary', label: 'Hungary', continent: 'Europe' },
{ code: 'is', value: 'iceland', label: 'Iceland', continent: 'Europe' },
{ code: 'in', value: 'india', label: 'India', continent: 'Asia' },
{ code: 'id', value: 'indonesia', label: 'Indonesia', continent: 'Asia' },
{ code: 'ir', value: 'iran', label: 'Iran', continent: 'Asia' },
{ code: 'iq', value: 'iraq', label: 'Iraq', continent: 'Asia' },
{ code: 'ie', value: 'ireland', label: 'Ireland', continent: 'Europe' },
{ code: 'il', value: 'israel', label: 'Israel', continent: 'Asia' },
{ code: 'it', value: 'italy', label: 'Italy', continent: 'Europe' },
{ code: 'jm', value: 'jamaica', label: 'Jamaica', continent: 'North America' },
{ code: 'jp', value: 'japan', label: 'Japan', continent: 'Asia' },
{ code: 'jo', value: 'jordan', label: 'Jordan', continent: 'Asia' },
{ code: 'kz', value: 'kazakhstan', label: 'Kazakhstan', continent: 'Asia' },
{ code: 'ke', value: 'kenya', label: 'Kenya', continent: 'Africa' },
{ code: 'kw', value: 'kuwait', label: 'Kuwait', continent: 'Asia' },
{ code: 'kg', value: 'kyrgyzstan', label: 'Kyrgyzstan', continent: 'Asia' },
{ code: 'la', value: 'laos', label: 'Laos', continent: 'Asia' },
{ code: 'lv', value: 'latvia', label: 'Latvia', continent: 'Europe' },
{ code: 'lb', value: 'lebanon', label: 'Lebanon', continent: 'Asia' },
{ code: 'ls', value: 'lesotho', label: 'Lesotho', continent: 'Africa' },
{ code: 'lr', value: 'liberia', label: 'Liberia', continent: 'Africa' },
{ code: 'ly', value: 'libya', label: 'Libya', continent: 'Africa' },
{ code: 'li', value: 'liechtenstein', label: 'Liechtenstein', continent: 'Europe' },
{ code: 'lt', value: 'lithuania', label: 'Lithuania', continent: 'Europe' },
{ code: 'lu', value: 'luxembourg', label: 'Luxembourg', continent: 'Europe' },
{ code: 'mg', value: 'madagascar', label: 'Madagascar', continent: 'Africa' },
{ code: 'mw', value: 'malawi', label: 'Malawi', continent: 'Africa' },
{ code: 'my', value: 'malaysia', label: 'Malaysia', continent: 'Asia' },
{ code: 'mv', value: 'maldives', label: 'Maldives', continent: 'Asia' },
{ code: 'ml', value: 'mali', label: 'Mali', continent: 'Africa' },
{ code: 'mt', value: 'malta', label: 'Malta', continent: 'Europe' },
{ code: 'mh', value: 'marshall-islands', label: 'Marshall Islands', continent: 'Oceania' },
{ code: 'mr', value: 'mauritania', label: 'Mauritania', continent: 'Africa' },
{ code: 'mu', value: 'mauritius', label: 'Mauritius', continent: 'Africa' },
{ code: 'mx', value: 'mexico', label: 'Mexico', continent: 'North America' },
{ code: 'fm', value: 'micronesia', label: 'Micronesia', continent: 'Oceania' },
{ code: 'md', value: 'moldova', label: 'Moldova', continent: 'Europe' },
{ code: 'mc', value: 'monaco', label: 'Monaco', continent: 'Europe' },
{ code: 'mn', value: 'mongolia', label: 'Mongolia', continent: 'Asia' },
{ code: 'me', value: 'montenegro', label: 'Montenegro', continent: 'Europe' },
{ code: 'ma', value: 'morocco', label: 'Morocco', continent: 'Africa' },
{ code: 'mz', value: 'mozambique', label: 'Mozambique', continent: 'Africa' },
{ code: 'mm', value: 'myanmar', label: 'Myanmar', continent: 'Asia' },
{ code: 'na', value: 'namibia', label: 'Namibia', continent: 'Africa' },
{ code: 'nr', value: 'nauru', label: 'Nauru', continent: 'Oceania' },
{ code: 'np', value: 'nepal', label: 'Nepal', continent: 'Asia' },
{ code: 'nl', value: 'netherlands', label: 'Netherlands', continent: 'Europe' },
{ code: 'nz', value: 'new-zealand', label: 'New Zealand', continent: 'Oceania' },
{ code: 'ni', value: 'nicaragua', label: 'Nicaragua', continent: 'North America' },
{ code: 'ne', value: 'niger', label: 'Niger', continent: 'Africa' },
{ code: 'ng', value: 'nigeria', label: 'Nigeria', continent: 'Africa' },
{ code: 'kp', value: 'north-korea', label: 'North Korea', continent: 'Asia' },
{ code: 'mk', value: 'north-macedonia', label: 'North Macedonia', continent: 'Europe' },
{ code: 'no', value: 'norway', label: 'Norway', continent: 'Europe' },
{ code: 'om', value: 'oman', label: 'Oman', continent: 'Asia' },
{ code: 'pk', value: 'pakistan', label: 'Pakistan', continent: 'Asia' },
{ code: 'pw', value: 'palau', label: 'Palau', continent: 'Oceania' },
{ code: 'ps', value: 'palestine', label: 'Palestine', continent: 'Asia' },
{ code: 'pa', value: 'panama', label: 'Panama', continent: 'North America' },
{ code: 'pg', value: 'papua-new-guinea', label: 'Papua New Guinea', continent: 'Oceania' },
{ code: 'py', value: 'paraguay', label: 'Paraguay', continent: 'South America' },
{ code: 'pe', value: 'peru', label: 'Peru', continent: 'South America' },
{ code: 'ph', value: 'philippines', label: 'Philippines', continent: 'Asia' },
{ code: 'pl', value: 'poland', label: 'Poland', continent: 'Europe' },
{ code: 'pt', value: 'portugal', label: 'Portugal', continent: 'Europe' },
{ code: 'qa', value: 'qatar', label: 'Qatar', continent: 'Asia' },
{ code: 'ro', value: 'romania', label: 'Romania', continent: 'Europe' },
{ code: 'ru', value: 'russia', label: 'Russia', continent: 'Europe' },
{ code: 'rw', value: 'rwanda', label: 'Rwanda', continent: 'Africa' },
{ code: 'ws', value: 'samoa', label: 'Samoa', continent: 'Oceania' },
{ code: 'sm', value: 'san-marino', label: 'San Marino', continent: 'Europe' },
{ code: 'sa', value: 'saudi-arabia', label: 'Saudi Arabia', continent: 'Asia' },
{ code: 'sn', value: 'senegal', label: 'Senegal', continent: 'Africa' },
{ code: 'rs', value: 'serbia', label: 'Serbia', continent: 'Europe' },
{ code: 'sc', value: 'seychelles', label: 'Seychelles', continent: 'Africa' },
{ code: 'sl', value: 'sierra-leone', label: 'Sierra Leone', continent: 'Africa' },
{ code: 'sg', value: 'singapore', label: 'Singapore', continent: 'Asia' },
{ code: 'sk', value: 'slovakia', label: 'Slovakia', continent: 'Europe' },
{ code: 'si', value: 'slovenia', label: 'Slovenia', continent: 'Europe' },
{ code: 'sb', value: 'solomon-islands', label: 'Solomon Islands', continent: 'Oceania' },
{ code: 'so', value: 'somalia', label: 'Somalia', continent: 'Africa' },
{ code: 'za', value: 'south-africa', label: 'South Africa', continent: 'Africa' },
{ code: 'kr', value: 'south-korea', label: 'South Korea', continent: 'Asia' },
{ code: 'ss', value: 'south-sudan', label: 'South Sudan', continent: 'Africa' },
{ code: 'es', value: 'spain', label: 'Spain', continent: 'Europe' },
{ code: 'lk', value: 'sri-lanka', label: 'Sri Lanka', continent: 'Asia' },
{ code: 'sd', value: 'sudan', label: 'Sudan', continent: 'Africa' },
{ code: 'sr', value: 'suriname', label: 'Suriname', continent: 'South America' },
{ code: 'se', value: 'sweden', label: 'Sweden', continent: 'Europe' },
{ code: 'ch', value: 'switzerland', label: 'Switzerland', continent: 'Europe' },
{ code: 'sy', value: 'syria', label: 'Syria', continent: 'Asia' },
{ code: 'tw', value: 'taiwan', label: 'Taiwan', continent: 'Asia' },
{ code: 'tj', value: 'tajikistan', label: 'Tajikistan', continent: 'Asia' },
{ code: 'tz', value: 'tanzania', label: 'Tanzania', continent: 'Africa' },
{ code: 'th', value: 'thailand', label: 'Thailand', continent: 'Asia' },
{ code: 'tl', value: 'timor-leste', label: 'Timor-Leste', continent: 'Asia' },
{ code: 'tg', value: 'togo', label: 'Togo', continent: 'Africa' },
{ code: 'to', value: 'tonga', label: 'Tonga', continent: 'Oceania' },
{
code: 'tt',
value: 'trinidad-and-tobago',
label: 'Trinidad and Tobago',
continent: 'North America',
},
{ code: 'tn', value: 'tunisia', label: 'Tunisia', continent: 'Africa' },
{ code: 'tr', value: 'turkey', label: 'Turkey', continent: 'Asia' },
{ code: 'tm', value: 'turkmenistan', label: 'Turkmenistan', continent: 'Asia' },
{ code: 'tv', value: 'tuvalu', label: 'Tuvalu', continent: 'Oceania' },
{ code: 'ug', value: 'uganda', label: 'Uganda', continent: 'Africa' },
{ code: 'ua', value: 'ukraine', label: 'Ukraine', continent: 'Europe' },
{ code: 'ae', value: 'united-arab-emirates', label: 'United Arab Emirates', continent: 'Asia' },
{ code: 'gb', value: 'united-kingdom', label: 'United Kingdom', continent: 'Europe' },
{ code: 'us', value: 'united-states', label: 'United States', continent: 'North America' },
{ code: 'uy', value: 'uruguay', label: 'Uruguay', continent: 'South America' },
{ code: 'uz', value: 'uzbekistan', label: 'Uzbekistan', continent: 'Asia' },
{ code: 'vu', value: 'vanuatu', label: 'Vanuatu', continent: 'Oceania' },
{ code: 'va', value: 'vatican-city', label: 'Vatican City', continent: 'Europe' },
{ code: 've', value: 'venezuela', label: 'Venezuela', continent: 'South America' },
{ code: 'vn', value: 'vietnam', label: 'Vietnam', continent: 'Asia' },
{ code: 'ye', value: 'yemen', label: 'Yemen', continent: 'Asia' },
{ code: 'zm', value: 'zambia', label: 'Zambia', continent: 'Africa' },
{ code: 'zw', value: 'zimbabwe', label: 'Zimbabwe', continent: 'Africa' },
];
const popupHiddenClass = styles.PopupHidden;
</script>
<template>
<div :class="styles.Field">
<Combobox.Root :items="countries">
<Combobox.Label :class="styles.Label">Country</Combobox.Label>
<Combobox.Trigger :class="styles.Trigger">
<Combobox.Value placeholder="Select country" />
<Combobox.Icon :class="styles.TriggerIcon">
<CaretUpDownIcon />
</Combobox.Icon>
</Combobox.Trigger>
<Combobox.Portal>
<Combobox.Positioner align="start" :side-offset="4">
<Transition
:enter-from-class="popupHiddenClass"
:leave-to-class="popupHiddenClass"
appear
>
<Combobox.Popup :class="styles.Popup" aria-label="Select country">
<Combobox.Input placeholder="e.g. United Kingdom" :class="styles.Input" />
<div :class="styles.Viewport">
<Combobox.Empty>
<div :class="styles.Empty">No countries found.</div>
</Combobox.Empty>
<Combobox.List :class="styles.List">
<template #item="{ item: country }">
<Combobox.Item v-slot="{ state }" :value="country" :class="styles.Item">
<span v-if="state.selected" :class="styles.ItemIndicator">
<CheckIcon />
</span>
<span :class="styles.ItemText">{{ country.label }}</span>
</Combobox.Item>
</template>
</Combobox.List>
</div>
</Combobox.Popup>
</Transition>
</Combobox.Positioner>
</Combobox.Portal>
</Combobox.Root>
</div>
</template>.Field {
display: flex;
flex-direction: column;
align-items: start;
gap: 0.25rem;
}
.Trigger {
box-sizing: border-box;
display: flex;
align-items: center;
justify-content: space-between;
gap: 0.75rem;
height: 2rem;
padding-left: 0.5rem;
padding-right: 0.25rem;
margin: 0;
outline: 0;
border: 1px solid oklch(14.5% 0 0deg);
font-family: inherit;
font-size: 0.875rem;
line-height: 1;
white-space: nowrap;
font-weight: 400;
color: oklch(14.5% 0 0deg);
cursor: default;
background-color: white;
-webkit-user-select: none;
user-select: none;
min-width: 10rem;
@media (prefers-color-scheme: dark) {
border: 1px solid white;
color: white;
background-color: oklch(14.5% 0 0deg);
}
@media (hover: hover) {
&:hover {
background-color: oklch(97% 0 0deg);
@media (prefers-color-scheme: dark) {
background-color: oklch(26.9% 0 0deg);
}
}
}
&:active {
background-color: oklch(92.2% 0 0deg);
@media (prefers-color-scheme: dark) {
background-color: oklch(37.1% 0 0deg);
}
}
&[aria-expanded='true'] {
background-color: oklch(97% 0 0deg);
@media (prefers-color-scheme: dark) {
background-color: oklch(26.9% 0 0deg);
}
}
&:focus-visible {
outline: 2px solid oklch(14.5% 0 0deg);
outline-offset: -1px;
@media (prefers-color-scheme: dark) {
outline-color: white;
}
}
&[data-placeholder] {
color: oklch(55.6% 0 0deg);
@media (prefers-color-scheme: dark) {
color: oklch(70.8% 0 0deg);
}
}
}
.TriggerIcon {
color: oklch(14.5% 0 0deg);
@media (prefers-color-scheme: dark) {
color: white;
}
}
.Input {
box-sizing: border-box;
padding: 0 0.5rem;
margin: 0;
border: 1px solid oklch(14.5% 0 0deg);
border-radius: 0;
min-width: 20rem;
width: 100%;
height: 2rem;
font-family: inherit;
font-size: 0.875rem;
line-height: 1.25rem;
font-weight: 400;
background-color: white;
color: oklch(14.5% 0 0deg);
outline: none;
@media (any-pointer: coarse) {
font-size: 1rem;
line-height: 1.5rem;
}
@media (prefers-color-scheme: dark) {
background-color: oklch(14.5% 0 0deg);
color: white;
border-color: white;
}
&::placeholder {
color: oklch(55.6% 0 0deg);
@media (prefers-color-scheme: dark) {
color: oklch(70.8% 0 0deg);
}
}
&:focus {
outline: 2px solid oklch(14.5% 0 0deg);
outline-offset: -2px;
@media (prefers-color-scheme: dark) {
outline-color: white;
}
}
}
.Label {
font-size: 0.875rem;
line-height: 1.25rem;
font-weight: 700;
color: oklch(14.5% 0 0deg);
cursor: default;
@media (prefers-color-scheme: dark) {
color: white;
}
}
.Positioner {
outline: 0;
}
.Popup {
--input-container-height: 2rem;
box-sizing: border-box;
background-color: white;
color: oklch(14.5% 0 0deg);
transform-origin: var(--transform-origin);
transition:
transform 150ms,
opacity 150ms;
max-width: var(--available-width);
max-height: 24.5rem;
box-shadow: 0.25rem 0.25rem 0 rgb(0 0 0 / 12%);
@media (prefers-color-scheme: dark) {
background-color: oklch(14.5% 0 0deg);
color: white;
box-shadow: none;
}
}
/* The enter-from and leave-to class of the `<Transition>` around the popup. */
.PopupHidden {
opacity: 0;
transform: scale(0.9);
}
.Viewport {
border-right: 1px solid oklch(14.5% 0 0deg);
border-bottom: 1px solid oklch(14.5% 0 0deg);
border-left: 1px solid oklch(14.5% 0 0deg);
@media (prefers-color-scheme: dark) {
border-color: white;
}
}
.List {
box-sizing: border-box;
overflow: auto;
scroll-padding-block: 0.25rem;
padding-block: 0.25rem;
overscroll-behavior: contain;
max-height: min(
calc(24.5rem - var(--input-container-height) - 2px),
calc(var(--available-height) - var(--input-container-height) - 2px)
);
&:empty {
padding: 0;
}
}
.Item {
box-sizing: border-box;
outline: 0;
cursor: default;
-webkit-user-select: none;
user-select: none;
min-width: var(--anchor-width);
padding-block: 0.5rem;
padding-left: 0.5rem;
padding-right: 0.5rem;
display: grid;
gap: 0.5rem;
align-items: center;
grid-template-columns: 1rem 1fr;
font-size: 0.875rem;
line-height: 1rem;
&[data-highlighted] {
z-index: 0;
position: relative;
color: white;
@media (prefers-color-scheme: dark) {
color: oklch(14.5% 0 0deg);
}
}
&[data-highlighted]::before {
content: '';
z-index: -1;
position: absolute;
inset-block: 0;
inset-inline: 0;
background-color: oklch(14.5% 0 0deg);
@media (prefers-color-scheme: dark) {
background-color: white;
}
}
}
.ItemText {
grid-column-start: 2;
}
.ItemIndicator {
grid-column-start: 1;
}
.Separator {
margin: 0.375rem 1rem;
height: 1px;
background-color: oklch(97% 0 0deg);
@media (prefers-color-scheme: dark) {
background-color: oklch(26.9% 0 0deg);
}
}
.Empty {
box-sizing: border-box;
font-size: 0.875rem;
line-height: 1rem;
color: oklch(55.6% 0 0deg);
padding: 1rem 1rem 1rem 0.5rem;
@media (prefers-color-scheme: dark) {
color: oklch(70.8% 0 0deg);
}
}<script setup lang="ts">
import { h } from 'vue';
import type { FunctionalComponent } from 'vue';
import { Combobox } from '@vase-ui/vue/combobox';
const ICON_PROPS = {
width: '16',
height: '16',
viewBox: '0 0 16 16',
style: { display: 'block' },
};
const CaretUpDownIcon: FunctionalComponent = (_, { attrs }) =>
h('svg', { ...ICON_PROPS, fill: 'currentColor', ...attrs }, [
h('path', { d: 'M11 10H5l3 3.5zm0-4H5l3-3.5z' }),
]);
const CheckIcon: FunctionalComponent = (_, { attrs }) =>
h('svg', { ...ICON_PROPS, fill: 'none', stroke: 'currentColor', ...attrs }, [
h('path', { d: 'm2.5 8.5 4 4 7-9' }),
]);
interface Country {
code: string;
value: string;
continent: string;
label: string;
}
const countries: Country[] = [
{ code: 'af', value: 'afghanistan', label: 'Afghanistan', continent: 'Asia' },
{ code: 'al', value: 'albania', label: 'Albania', continent: 'Europe' },
{ code: 'dz', value: 'algeria', label: 'Algeria', continent: 'Africa' },
{ code: 'ad', value: 'andorra', label: 'Andorra', continent: 'Europe' },
{ code: 'ao', value: 'angola', label: 'Angola', continent: 'Africa' },
{ code: 'ar', value: 'argentina', label: 'Argentina', continent: 'South America' },
{ code: 'am', value: 'armenia', label: 'Armenia', continent: 'Asia' },
{ code: 'au', value: 'australia', label: 'Australia', continent: 'Oceania' },
{ code: 'at', value: 'austria', label: 'Austria', continent: 'Europe' },
{ code: 'az', value: 'azerbaijan', label: 'Azerbaijan', continent: 'Asia' },
{ code: 'bs', value: 'bahamas', label: 'Bahamas', continent: 'North America' },
{ code: 'bh', value: 'bahrain', label: 'Bahrain', continent: 'Asia' },
{ code: 'bd', value: 'bangladesh', label: 'Bangladesh', continent: 'Asia' },
{ code: 'bb', value: 'barbados', label: 'Barbados', continent: 'North America' },
{ code: 'by', value: 'belarus', label: 'Belarus', continent: 'Europe' },
{ code: 'be', value: 'belgium', label: 'Belgium', continent: 'Europe' },
{ code: 'bz', value: 'belize', label: 'Belize', continent: 'North America' },
{ code: 'bj', value: 'benin', label: 'Benin', continent: 'Africa' },
{ code: 'bt', value: 'bhutan', label: 'Bhutan', continent: 'Asia' },
{ code: 'bo', value: 'bolivia', label: 'Bolivia', continent: 'South America' },
{
code: 'ba',
value: 'bosnia-and-herzegovina',
label: 'Bosnia and Herzegovina',
continent: 'Europe',
},
{ code: 'bw', value: 'botswana', label: 'Botswana', continent: 'Africa' },
{ code: 'br', value: 'brazil', label: 'Brazil', continent: 'South America' },
{ code: 'bn', value: 'brunei', label: 'Brunei', continent: 'Asia' },
{ code: 'bg', value: 'bulgaria', label: 'Bulgaria', continent: 'Europe' },
{ code: 'bf', value: 'burkina-faso', label: 'Burkina Faso', continent: 'Africa' },
{ code: 'bi', value: 'burundi', label: 'Burundi', continent: 'Africa' },
{ code: 'kh', value: 'cambodia', label: 'Cambodia', continent: 'Asia' },
{ code: 'cm', value: 'cameroon', label: 'Cameroon', continent: 'Africa' },
{ code: 'ca', value: 'canada', label: 'Canada', continent: 'North America' },
{ code: 'cv', value: 'cape-verde', label: 'Cape Verde', continent: 'Africa' },
{
code: 'cf',
value: 'central-african-republic',
label: 'Central African Republic',
continent: 'Africa',
},
{ code: 'td', value: 'chad', label: 'Chad', continent: 'Africa' },
{ code: 'cl', value: 'chile', label: 'Chile', continent: 'South America' },
{ code: 'cn', value: 'china', label: 'China', continent: 'Asia' },
{ code: 'co', value: 'colombia', label: 'Colombia', continent: 'South America' },
{ code: 'km', value: 'comoros', label: 'Comoros', continent: 'Africa' },
{ code: 'cg', value: 'congo', label: 'Congo', continent: 'Africa' },
{ code: 'cr', value: 'costa-rica', label: 'Costa Rica', continent: 'North America' },
{ code: 'hr', value: 'croatia', label: 'Croatia', continent: 'Europe' },
{ code: 'cu', value: 'cuba', label: 'Cuba', continent: 'North America' },
{ code: 'cy', value: 'cyprus', label: 'Cyprus', continent: 'Asia' },
{ code: 'cz', value: 'czech-republic', label: 'Czech Republic', continent: 'Europe' },
{ code: 'dk', value: 'denmark', label: 'Denmark', continent: 'Europe' },
{ code: 'dj', value: 'djibouti', label: 'Djibouti', continent: 'Africa' },
{ code: 'dm', value: 'dominica', label: 'Dominica', continent: 'North America' },
{
code: 'do',
value: 'dominican-republic',
label: 'Dominican Republic',
continent: 'North America',
},
{ code: 'ec', value: 'ecuador', label: 'Ecuador', continent: 'South America' },
{ code: 'eg', value: 'egypt', label: 'Egypt', continent: 'Africa' },
{ code: 'sv', value: 'el-salvador', label: 'El Salvador', continent: 'North America' },
{ code: 'gq', value: 'equatorial-guinea', label: 'Equatorial Guinea', continent: 'Africa' },
{ code: 'er', value: 'eritrea', label: 'Eritrea', continent: 'Africa' },
{ code: 'ee', value: 'estonia', label: 'Estonia', continent: 'Europe' },
{ code: 'et', value: 'ethiopia', label: 'Ethiopia', continent: 'Africa' },
{ code: 'fj', value: 'fiji', label: 'Fiji', continent: 'Oceania' },
{ code: 'fi', value: 'finland', label: 'Finland', continent: 'Europe' },
{ code: 'fr', value: 'france', label: 'France', continent: 'Europe' },
{ code: 'ga', value: 'gabon', label: 'Gabon', continent: 'Africa' },
{ code: 'gm', value: 'gambia', label: 'Gambia', continent: 'Africa' },
{ code: 'ge', value: 'georgia', label: 'Georgia', continent: 'Asia' },
{ code: 'de', value: 'germany', label: 'Germany', continent: 'Europe' },
{ code: 'gh', value: 'ghana', label: 'Ghana', continent: 'Africa' },
{ code: 'gr', value: 'greece', label: 'Greece', continent: 'Europe' },
{ code: 'gd', value: 'grenada', label: 'Grenada', continent: 'North America' },
{ code: 'gt', value: 'guatemala', label: 'Guatemala', continent: 'North America' },
{ code: 'gn', value: 'guinea', label: 'Guinea', continent: 'Africa' },
{ code: 'gw', value: 'guinea-bissau', label: 'Guinea-Bissau', continent: 'Africa' },
{ code: 'gy', value: 'guyana', label: 'Guyana', continent: 'South America' },
{ code: 'ht', value: 'haiti', label: 'Haiti', continent: 'North America' },
{ code: 'hn', value: 'honduras', label: 'Honduras', continent: 'North America' },
{ code: 'hu', value: 'hungary', label: 'Hungary', continent: 'Europe' },
{ code: 'is', value: 'iceland', label: 'Iceland', continent: 'Europe' },
{ code: 'in', value: 'india', label: 'India', continent: 'Asia' },
{ code: 'id', value: 'indonesia', label: 'Indonesia', continent: 'Asia' },
{ code: 'ir', value: 'iran', label: 'Iran', continent: 'Asia' },
{ code: 'iq', value: 'iraq', label: 'Iraq', continent: 'Asia' },
{ code: 'ie', value: 'ireland', label: 'Ireland', continent: 'Europe' },
{ code: 'il', value: 'israel', label: 'Israel', continent: 'Asia' },
{ code: 'it', value: 'italy', label: 'Italy', continent: 'Europe' },
{ code: 'jm', value: 'jamaica', label: 'Jamaica', continent: 'North America' },
{ code: 'jp', value: 'japan', label: 'Japan', continent: 'Asia' },
{ code: 'jo', value: 'jordan', label: 'Jordan', continent: 'Asia' },
{ code: 'kz', value: 'kazakhstan', label: 'Kazakhstan', continent: 'Asia' },
{ code: 'ke', value: 'kenya', label: 'Kenya', continent: 'Africa' },
{ code: 'kw', value: 'kuwait', label: 'Kuwait', continent: 'Asia' },
{ code: 'kg', value: 'kyrgyzstan', label: 'Kyrgyzstan', continent: 'Asia' },
{ code: 'la', value: 'laos', label: 'Laos', continent: 'Asia' },
{ code: 'lv', value: 'latvia', label: 'Latvia', continent: 'Europe' },
{ code: 'lb', value: 'lebanon', label: 'Lebanon', continent: 'Asia' },
{ code: 'ls', value: 'lesotho', label: 'Lesotho', continent: 'Africa' },
{ code: 'lr', value: 'liberia', label: 'Liberia', continent: 'Africa' },
{ code: 'ly', value: 'libya', label: 'Libya', continent: 'Africa' },
{ code: 'li', value: 'liechtenstein', label: 'Liechtenstein', continent: 'Europe' },
{ code: 'lt', value: 'lithuania', label: 'Lithuania', continent: 'Europe' },
{ code: 'lu', value: 'luxembourg', label: 'Luxembourg', continent: 'Europe' },
{ code: 'mg', value: 'madagascar', label: 'Madagascar', continent: 'Africa' },
{ code: 'mw', value: 'malawi', label: 'Malawi', continent: 'Africa' },
{ code: 'my', value: 'malaysia', label: 'Malaysia', continent: 'Asia' },
{ code: 'mv', value: 'maldives', label: 'Maldives', continent: 'Asia' },
{ code: 'ml', value: 'mali', label: 'Mali', continent: 'Africa' },
{ code: 'mt', value: 'malta', label: 'Malta', continent: 'Europe' },
{ code: 'mh', value: 'marshall-islands', label: 'Marshall Islands', continent: 'Oceania' },
{ code: 'mr', value: 'mauritania', label: 'Mauritania', continent: 'Africa' },
{ code: 'mu', value: 'mauritius', label: 'Mauritius', continent: 'Africa' },
{ code: 'mx', value: 'mexico', label: 'Mexico', continent: 'North America' },
{ code: 'fm', value: 'micronesia', label: 'Micronesia', continent: 'Oceania' },
{ code: 'md', value: 'moldova', label: 'Moldova', continent: 'Europe' },
{ code: 'mc', value: 'monaco', label: 'Monaco', continent: 'Europe' },
{ code: 'mn', value: 'mongolia', label: 'Mongolia', continent: 'Asia' },
{ code: 'me', value: 'montenegro', label: 'Montenegro', continent: 'Europe' },
{ code: 'ma', value: 'morocco', label: 'Morocco', continent: 'Africa' },
{ code: 'mz', value: 'mozambique', label: 'Mozambique', continent: 'Africa' },
{ code: 'mm', value: 'myanmar', label: 'Myanmar', continent: 'Asia' },
{ code: 'na', value: 'namibia', label: 'Namibia', continent: 'Africa' },
{ code: 'nr', value: 'nauru', label: 'Nauru', continent: 'Oceania' },
{ code: 'np', value: 'nepal', label: 'Nepal', continent: 'Asia' },
{ code: 'nl', value: 'netherlands', label: 'Netherlands', continent: 'Europe' },
{ code: 'nz', value: 'new-zealand', label: 'New Zealand', continent: 'Oceania' },
{ code: 'ni', value: 'nicaragua', label: 'Nicaragua', continent: 'North America' },
{ code: 'ne', value: 'niger', label: 'Niger', continent: 'Africa' },
{ code: 'ng', value: 'nigeria', label: 'Nigeria', continent: 'Africa' },
{ code: 'kp', value: 'north-korea', label: 'North Korea', continent: 'Asia' },
{ code: 'mk', value: 'north-macedonia', label: 'North Macedonia', continent: 'Europe' },
{ code: 'no', value: 'norway', label: 'Norway', continent: 'Europe' },
{ code: 'om', value: 'oman', label: 'Oman', continent: 'Asia' },
{ code: 'pk', value: 'pakistan', label: 'Pakistan', continent: 'Asia' },
{ code: 'pw', value: 'palau', label: 'Palau', continent: 'Oceania' },
{ code: 'ps', value: 'palestine', label: 'Palestine', continent: 'Asia' },
{ code: 'pa', value: 'panama', label: 'Panama', continent: 'North America' },
{ code: 'pg', value: 'papua-new-guinea', label: 'Papua New Guinea', continent: 'Oceania' },
{ code: 'py', value: 'paraguay', label: 'Paraguay', continent: 'South America' },
{ code: 'pe', value: 'peru', label: 'Peru', continent: 'South America' },
{ code: 'ph', value: 'philippines', label: 'Philippines', continent: 'Asia' },
{ code: 'pl', value: 'poland', label: 'Poland', continent: 'Europe' },
{ code: 'pt', value: 'portugal', label: 'Portugal', continent: 'Europe' },
{ code: 'qa', value: 'qatar', label: 'Qatar', continent: 'Asia' },
{ code: 'ro', value: 'romania', label: 'Romania', continent: 'Europe' },
{ code: 'ru', value: 'russia', label: 'Russia', continent: 'Europe' },
{ code: 'rw', value: 'rwanda', label: 'Rwanda', continent: 'Africa' },
{ code: 'ws', value: 'samoa', label: 'Samoa', continent: 'Oceania' },
{ code: 'sm', value: 'san-marino', label: 'San Marino', continent: 'Europe' },
{ code: 'sa', value: 'saudi-arabia', label: 'Saudi Arabia', continent: 'Asia' },
{ code: 'sn', value: 'senegal', label: 'Senegal', continent: 'Africa' },
{ code: 'rs', value: 'serbia', label: 'Serbia', continent: 'Europe' },
{ code: 'sc', value: 'seychelles', label: 'Seychelles', continent: 'Africa' },
{ code: 'sl', value: 'sierra-leone', label: 'Sierra Leone', continent: 'Africa' },
{ code: 'sg', value: 'singapore', label: 'Singapore', continent: 'Asia' },
{ code: 'sk', value: 'slovakia', label: 'Slovakia', continent: 'Europe' },
{ code: 'si', value: 'slovenia', label: 'Slovenia', continent: 'Europe' },
{ code: 'sb', value: 'solomon-islands', label: 'Solomon Islands', continent: 'Oceania' },
{ code: 'so', value: 'somalia', label: 'Somalia', continent: 'Africa' },
{ code: 'za', value: 'south-africa', label: 'South Africa', continent: 'Africa' },
{ code: 'kr', value: 'south-korea', label: 'South Korea', continent: 'Asia' },
{ code: 'ss', value: 'south-sudan', label: 'South Sudan', continent: 'Africa' },
{ code: 'es', value: 'spain', label: 'Spain', continent: 'Europe' },
{ code: 'lk', value: 'sri-lanka', label: 'Sri Lanka', continent: 'Asia' },
{ code: 'sd', value: 'sudan', label: 'Sudan', continent: 'Africa' },
{ code: 'sr', value: 'suriname', label: 'Suriname', continent: 'South America' },
{ code: 'se', value: 'sweden', label: 'Sweden', continent: 'Europe' },
{ code: 'ch', value: 'switzerland', label: 'Switzerland', continent: 'Europe' },
{ code: 'sy', value: 'syria', label: 'Syria', continent: 'Asia' },
{ code: 'tw', value: 'taiwan', label: 'Taiwan', continent: 'Asia' },
{ code: 'tj', value: 'tajikistan', label: 'Tajikistan', continent: 'Asia' },
{ code: 'tz', value: 'tanzania', label: 'Tanzania', continent: 'Africa' },
{ code: 'th', value: 'thailand', label: 'Thailand', continent: 'Asia' },
{ code: 'tl', value: 'timor-leste', label: 'Timor-Leste', continent: 'Asia' },
{ code: 'tg', value: 'togo', label: 'Togo', continent: 'Africa' },
{ code: 'to', value: 'tonga', label: 'Tonga', continent: 'Oceania' },
{
code: 'tt',
value: 'trinidad-and-tobago',
label: 'Trinidad and Tobago',
continent: 'North America',
},
{ code: 'tn', value: 'tunisia', label: 'Tunisia', continent: 'Africa' },
{ code: 'tr', value: 'turkey', label: 'Turkey', continent: 'Asia' },
{ code: 'tm', value: 'turkmenistan', label: 'Turkmenistan', continent: 'Asia' },
{ code: 'tv', value: 'tuvalu', label: 'Tuvalu', continent: 'Oceania' },
{ code: 'ug', value: 'uganda', label: 'Uganda', continent: 'Africa' },
{ code: 'ua', value: 'ukraine', label: 'Ukraine', continent: 'Europe' },
{ code: 'ae', value: 'united-arab-emirates', label: 'United Arab Emirates', continent: 'Asia' },
{ code: 'gb', value: 'united-kingdom', label: 'United Kingdom', continent: 'Europe' },
{ code: 'us', value: 'united-states', label: 'United States', continent: 'North America' },
{ code: 'uy', value: 'uruguay', label: 'Uruguay', continent: 'South America' },
{ code: 'uz', value: 'uzbekistan', label: 'Uzbekistan', continent: 'Asia' },
{ code: 'vu', value: 'vanuatu', label: 'Vanuatu', continent: 'Oceania' },
{ code: 'va', value: 'vatican-city', label: 'Vatican City', continent: 'Europe' },
{ code: 've', value: 'venezuela', label: 'Venezuela', continent: 'South America' },
{ code: 'vn', value: 'vietnam', label: 'Vietnam', continent: 'Asia' },
{ code: 'ye', value: 'yemen', label: 'Yemen', continent: 'Asia' },
{ code: 'zm', value: 'zambia', label: 'Zambia', continent: 'Africa' },
{ code: 'zw', value: 'zimbabwe', label: 'Zimbabwe', continent: 'Africa' },
];
const popupHiddenClass = 'scale-90 opacity-0';
</script>
<template>
<div class="flex flex-col items-start gap-1">
<Combobox.Root :items="countries">
<Combobox.Label
class="cursor-default text-sm leading-5 font-bold text-neutral-950 dark:text-white"
>Country</Combobox.Label
>
<Combobox.Trigger
class="flex h-8 min-w-40 cursor-default items-center justify-between gap-3 border border-neutral-950 bg-white pl-2 pr-1 text-sm leading-none whitespace-nowrap font-normal text-neutral-950 select-none hover:bg-neutral-100 active:bg-neutral-200 aria-expanded:bg-neutral-100 data-placeholder:text-neutral-500 focus-visible:outline-2 focus-visible:-outline-offset-1 focus-visible:outline-neutral-950 dark:data-placeholder:text-neutral-400 dark:focus-visible:outline-white dark:border-white dark:bg-neutral-950 dark:text-white dark:hover:bg-neutral-800 dark:active:bg-neutral-700 dark:aria-expanded:bg-neutral-800"
>
<Combobox.Value placeholder="Select country" />
<Combobox.Icon class="text-neutral-950 dark:text-white">
<CaretUpDownIcon />
</Combobox.Icon>
</Combobox.Trigger>
<Combobox.Portal>
<Combobox.Positioner align="start" :side-offset="4">
<Transition
:enter-from-class="popupHiddenClass"
:leave-to-class="popupHiddenClass"
appear
>
<Combobox.Popup
class="[--input-container-height:2rem] max-h-[24.5rem] max-w-[var(--available-width)] origin-[var(--transform-origin)] bg-white text-neutral-950 shadow-[0.25rem_0.25rem_0_rgb(0_0_0_/_12%)] transition-[scale,opacity] duration-150 dark:bg-neutral-950 dark:text-white dark:shadow-none"
aria-label="Select country"
>
<Combobox.Input
placeholder="e.g. United Kingdom"
class="h-8 w-full min-w-80 border border-neutral-950 bg-white px-2 text-sm font-normal text-neutral-950 placeholder:text-neutral-500 focus:outline-2 focus:-outline-offset-2 focus:outline-neutral-950 any-pointer-coarse:text-base dark:bg-neutral-950 dark:text-white dark:placeholder:text-neutral-400 dark:border-white dark:focus:outline-white"
/>
<div class="border-x border-b border-neutral-950 dark:border-white">
<Combobox.Empty>
<div
class="py-4 pr-4 pl-2 text-sm leading-4 text-neutral-500 dark:text-neutral-400"
>
No countries found.
</div>
</Combobox.Empty>
<Combobox.List
class="max-h-[min(calc(24.5rem-var(--input-container-height)-2px),calc(var(--available-height)-var(--input-container-height)-2px))] overflow-auto overscroll-contain py-1 scroll-py-1 empty:p-0"
>
<template #item="{ item: country }">
<Combobox.Item
v-slot="{ state }"
:value="country"
class="grid min-w-[var(--anchor-width)] cursor-default grid-cols-[1rem_1fr] items-center gap-2 p-2 text-sm leading-4 outline-hidden select-none data-highlighted:relative data-highlighted:z-0 data-highlighted:text-white data-highlighted:before:absolute data-highlighted:before:inset-0 data-highlighted:before:z-[-1] data-highlighted:before:bg-neutral-950 dark:data-highlighted:text-neutral-950 dark:data-highlighted:before:bg-white"
>
<span v-if="state.selected" class="col-start-1">
<CheckIcon />
</span>
<span class="col-start-2">{{ country.label }}</span>
</Combobox.Item>
</template>
</Combobox.List>
</div>
</Combobox.Popup>
</Transition>
</Combobox.Positioner>
</Combobox.Portal>
</Combobox.Root>
</div>
</template>In this pattern, use <Combobox.Label> to give the trigger a visible label:
<script setup lang="ts">
import { Combobox } from '@vase-ui/vue/combobox';
</script>
<template>
<Combobox.Root>
<Combobox.Label>Favorite fruit</Combobox.Label>
<!-- ... -->
</Combobox.Root>
</template><Combobox.Label> renders a <div>. With the input inside the popup, a click on the label focuses the trigger and does not open the popup.
With the input outside the popup, use a native <label> or <Field.Label> for the input. A click on <Combobox.Label> then focuses the input, and not the trigger.
Grouped
Use <Combobox.Group> and <Combobox.GroupLabel> to add headings that group related items in the popup.
The items prop describes the groups as an array of objects. Each object has an items array with the items of its group. Another property, such as value, can give the text of the heading:
<script setup lang="ts">
import { Combobox } from '@vase-ui/vue/combobox';
interface ProduceGroupItem {
value: string;
items: string[];
}
const groups: ProduceGroupItem[] = [
{
value: 'Fruits',
items: ['Apple', 'Banana', 'Orange'],
},
{
value: 'Vegetables',
items: ['Carrot', 'Lettuce', 'Spinach'],
},
];
</script>
<template>
<Combobox.Root :items="groups">
<Combobox.Input />
<Combobox.Portal>
<Combobox.Positioner>
<Combobox.Popup>
<Combobox.List>
<template #item="{ item: group }">
<Combobox.Group>
<Combobox.GroupLabel>{{ group.value }}</Combobox.GroupLabel>
<template v-for="item in group.items" :key="item.value">
<Combobox.Item :value="item">{{ item }}</Combobox.Item>
</template>
</Combobox.Group>
</template>
</Combobox.List>
</Combobox.Popup>
</Combobox.Positioner>
</Combobox.Portal>
</Combobox.Root>
</template><script setup lang="ts">
import { h, useId } from 'vue';
import type { FunctionalComponent } from 'vue';
import { Combobox } from '@vase-ui/vue/combobox';
import styles from './index.module.css';
const id = useId();
const ICON_PROPS = {
width: '16',
height: '16',
viewBox: '0 0 16 16',
style: { display: 'block' },
};
const CheckIcon: FunctionalComponent = (_, { attrs }) =>
h('svg', { ...ICON_PROPS, fill: 'none', stroke: 'currentColor', ...attrs }, [
h('path', { d: 'm2.5 8.5 4 4 7-9' }),
]);
const XIcon: FunctionalComponent = (_, { attrs }) =>
h(
'svg',
{
...ICON_PROPS,
fill: 'none',
stroke: 'currentColor',
'stroke-linecap': 'square',
'stroke-linejoin': 'round',
...attrs,
},
[h('path', { d: 'm4.5 4.5 7 7m-7 0 7-7' })],
);
const CaretDownIcon: FunctionalComponent = (_, { attrs }) =>
h('svg', { ...ICON_PROPS, fill: 'currentColor', ...attrs }, [h('path', { d: 'M12 6H4l4 4.5z' })]);
interface Produce {
id: string;
label: string;
group: 'Fruits' | 'Vegetables';
}
interface ProduceGroup {
value: string;
items: Produce[];
}
const produceData: Produce[] = [
{ id: 'fruit-apple', label: 'Apple', group: 'Fruits' },
{ id: 'fruit-banana', label: 'Banana', group: 'Fruits' },
{ id: 'fruit-mango', label: 'Mango', group: 'Fruits' },
{ id: 'fruit-kiwi', label: 'Kiwi', group: 'Fruits' },
{ id: 'fruit-grape', label: 'Grape', group: 'Fruits' },
{ id: 'fruit-orange', label: 'Orange', group: 'Fruits' },
{ id: 'fruit-strawberry', label: 'Strawberry', group: 'Fruits' },
{ id: 'fruit-watermelon', label: 'Watermelon', group: 'Fruits' },
{ id: 'veg-broccoli', label: 'Broccoli', group: 'Vegetables' },
{ id: 'veg-carrot', label: 'Carrot', group: 'Vegetables' },
{ id: 'veg-cauliflower', label: 'Cauliflower', group: 'Vegetables' },
{ id: 'veg-cucumber', label: 'Cucumber', group: 'Vegetables' },
{ id: 'veg-kale', label: 'Kale', group: 'Vegetables' },
{ id: 'veg-pepper', label: 'Bell pepper', group: 'Vegetables' },
{ id: 'veg-spinach', label: 'Spinach', group: 'Vegetables' },
{ id: 'veg-zucchini', label: 'Zucchini', group: 'Vegetables' },
];
function groupProduce(items: Produce[]): ProduceGroup[] {
const groups: Record<string, Produce[]> = {};
items.forEach((item) => {
(groups[item.group] ??= []).push(item);
});
const order = ['Fruits', 'Vegetables'];
return order.map((value) => ({ value, items: groups[value] ?? [] }));
}
const groupedProduce: ProduceGroup[] = groupProduce(produceData);
const popupHiddenClass = styles.PopupHidden;
</script>
<template>
<Combobox.Root :items="groupedProduce">
<div :class="styles.Label">
<label :for="id">Select produce</label>
<Combobox.InputGroup :class="styles.InputGroup">
<Combobox.Input placeholder="e.g. Mango" :class="styles.Input" :id="id" />
<div :class="styles.ActionButtons">
<Combobox.Clear :class="styles.Clear" aria-label="Clear selection">
<XIcon />
</Combobox.Clear>
<Combobox.Trigger :class="styles.Trigger" aria-label="Open popup">
<CaretDownIcon />
</Combobox.Trigger>
</div>
</Combobox.InputGroup>
</div>
<Combobox.Portal>
<Combobox.Positioner :class="styles.Positioner" :side-offset="4">
<Transition :enter-from-class="popupHiddenClass" :leave-to-class="popupHiddenClass" appear>
<Combobox.Popup :class="styles.Popup">
<Combobox.Empty>
<div :class="styles.Empty">No produce found.</div>
</Combobox.Empty>
<Combobox.List :class="styles.List">
<template #item="{ item: group }">
<Combobox.Group :class="styles.Group">
<Combobox.GroupLabel :class="styles.GroupLabel">
{{ group.value }}
</Combobox.GroupLabel>
<template v-for="item in group.items" :key="item.value">
<Combobox.Item v-slot="{ state }" :class="styles.Item" :value="item">
<span v-if="state.selected" :class="styles.ItemIndicator">
<CheckIcon />
</span>
<span :class="styles.ItemText">{{ item.label }}</span>
</Combobox.Item>
</template>
</Combobox.Group>
</template>
</Combobox.List>
</Combobox.Popup>
</Transition>
</Combobox.Positioner>
</Combobox.Portal>
</Combobox.Root>
</template>.InputGroup {
box-sizing: border-box;
position: relative;
width: 16rem;
height: 2rem;
border: 1px solid oklch(14.5% 0 0deg);
background-color: white;
@media (prefers-color-scheme: dark) {
border: 1px solid white;
background-color: oklch(14.5% 0 0deg);
}
&:focus-within {
outline: 2px solid oklch(14.5% 0 0deg);
outline-offset: -1px;
@media (prefers-color-scheme: dark) {
outline-color: white;
}
}
}
.InputGroup:has(.Clear) .Input {
padding: 0 calc(0.5rem + 2rem * 2) 0 0.5rem;
}
.Input {
box-sizing: border-box;
padding: 0 calc(0.5rem + 2rem) 0 0.5rem;
margin: 0;
border: none;
border-radius: 0;
width: 100%;
height: 100%;
font-family: inherit;
font-size: 0.875rem;
line-height: 1.25rem;
font-weight: 400;
background-color: white;
color: oklch(14.5% 0 0deg);
outline: none;
@media (any-pointer: coarse) {
font-size: 1rem;
line-height: 1.5rem;
}
@media (prefers-color-scheme: dark) {
background-color: oklch(14.5% 0 0deg);
color: white;
}
&::placeholder {
color: oklch(55.6% 0 0deg);
@media (prefers-color-scheme: dark) {
color: oklch(70.8% 0 0deg);
}
}
&:focus {
outline: none;
}
}
.Label {
display: flex;
flex-direction: column;
gap: 0.25rem;
font-size: 0.875rem;
line-height: 1.25rem;
font-weight: 700;
color: oklch(14.5% 0 0deg);
position: relative;
@media (prefers-color-scheme: dark) {
color: white;
}
}
.ActionButtons {
box-sizing: border-box;
position: absolute;
display: flex;
align-items: center;
justify-content: center;
bottom: 0;
height: 100%;
right: 0;
border: none;
color: oklch(55.6% 0 0deg);
padding: 0;
@media (prefers-color-scheme: dark) {
color: oklch(70.8% 0 0deg);
}
}
.Trigger,
.Clear {
box-sizing: border-box;
display: flex;
align-items: center;
justify-content: center;
width: 1.5rem;
height: 100%;
color: oklch(14.5% 0 0deg);
border: none;
padding: 0;
background: none;
@media (prefers-color-scheme: dark) {
color: white;
}
}
.Positioner {
outline: 0;
}
.Popup {
box-sizing: border-box;
background-color: white;
color: oklch(14.5% 0 0deg);
width: var(--anchor-width);
max-width: var(--available-width);
transition:
opacity 0.1s,
transform 0.1s;
transform-origin: var(--transform-origin);
border: 1px solid oklch(14.5% 0 0deg);
box-shadow: 0.25rem 0.25rem 0 rgb(0 0 0 / 12%);
@media (prefers-color-scheme: dark) {
background-color: oklch(14.5% 0 0deg);
color: white;
border: 1px solid white;
box-shadow: none;
}
}
/* The enter-from and leave-to class of the `<Transition>` around the popup. */
.PopupHidden {
opacity: 0;
transform: scale(0.95);
}
.List {
box-sizing: border-box;
overflow: auto;
overscroll-behavior: contain;
padding-block: 0.25rem;
scroll-padding-top: 0.25rem;
scroll-padding-bottom: 0.25rem;
max-height: min(22.5rem, var(--available-height));
outline: 0;
}
.Group {
display: block;
padding-bottom: 0.5rem;
&:last-child {
padding-bottom: 0;
}
}
.GroupLabel {
box-sizing: border-box;
-webkit-user-select: none;
user-select: none;
padding: 0.5rem 0.5rem 0.5rem 2rem;
font-size: 0.875rem;
line-height: 1rem;
color: oklch(55.6% 0 0deg);
@media (prefers-color-scheme: dark) {
color: oklch(70.8% 0 0deg);
}
}
.Item {
box-sizing: border-box;
outline: 0;
cursor: default;
-webkit-user-select: none;
user-select: none;
padding: 0.5rem;
display: grid;
grid-template-columns: 1rem 1fr;
gap: 0.5rem;
align-items: center;
font-size: 0.875rem;
line-height: 1rem;
&[data-highlighted] {
z-index: 0;
position: relative;
color: white;
@media (prefers-color-scheme: dark) {
color: oklch(14.5% 0 0deg);
}
}
&[data-highlighted]::before {
content: '';
z-index: -1;
position: absolute;
inset-block: 0;
inset-inline: 0;
background-color: oklch(14.5% 0 0deg);
@media (prefers-color-scheme: dark) {
background-color: white;
}
}
}
.ItemIndicator {
grid-column-start: 1;
}
.ItemText {
grid-column-start: 2;
}
.Empty {
box-sizing: border-box;
padding: 1rem 1rem 1rem 0.5rem;
font-size: 0.875rem;
line-height: 1rem;
color: oklch(55.6% 0 0deg);
@media (prefers-color-scheme: dark) {
color: oklch(70.8% 0 0deg);
}
}<script setup lang="ts">
import { h, useId } from 'vue';
import type { FunctionalComponent } from 'vue';
import { Combobox } from '@vase-ui/vue/combobox';
const id = useId();
const ICON_PROPS = {
width: '16',
height: '16',
viewBox: '0 0 16 16',
style: { display: 'block' },
};
const CheckIcon: FunctionalComponent = (_, { attrs }) =>
h('svg', { ...ICON_PROPS, fill: 'none', stroke: 'currentColor', ...attrs }, [
h('path', { d: 'm2.5 8.5 4 4 7-9' }),
]);
const XIcon: FunctionalComponent = (_, { attrs }) =>
h(
'svg',
{
...ICON_PROPS,
fill: 'none',
stroke: 'currentColor',
'stroke-linecap': 'square',
'stroke-linejoin': 'round',
...attrs,
},
[h('path', { d: 'm4.5 4.5 7 7m-7 0 7-7' })],
);
const CaretDownIcon: FunctionalComponent = (_, { attrs }) =>
h('svg', { ...ICON_PROPS, fill: 'currentColor', ...attrs }, [h('path', { d: 'M12 6H4l4 4.5z' })]);
interface Produce {
id: string;
label: string;
group: 'Fruits' | 'Vegetables';
}
interface ProduceGroup {
value: string;
items: Produce[];
}
const produceData: Produce[] = [
{ id: 'fruit-apple', label: 'Apple', group: 'Fruits' },
{ id: 'fruit-banana', label: 'Banana', group: 'Fruits' },
{ id: 'fruit-mango', label: 'Mango', group: 'Fruits' },
{ id: 'fruit-kiwi', label: 'Kiwi', group: 'Fruits' },
{ id: 'fruit-grape', label: 'Grape', group: 'Fruits' },
{ id: 'fruit-orange', label: 'Orange', group: 'Fruits' },
{ id: 'fruit-strawberry', label: 'Strawberry', group: 'Fruits' },
{ id: 'fruit-watermelon', label: 'Watermelon', group: 'Fruits' },
{ id: 'veg-broccoli', label: 'Broccoli', group: 'Vegetables' },
{ id: 'veg-carrot', label: 'Carrot', group: 'Vegetables' },
{ id: 'veg-cauliflower', label: 'Cauliflower', group: 'Vegetables' },
{ id: 'veg-cucumber', label: 'Cucumber', group: 'Vegetables' },
{ id: 'veg-kale', label: 'Kale', group: 'Vegetables' },
{ id: 'veg-pepper', label: 'Bell pepper', group: 'Vegetables' },
{ id: 'veg-spinach', label: 'Spinach', group: 'Vegetables' },
{ id: 'veg-zucchini', label: 'Zucchini', group: 'Vegetables' },
];
function groupProduce(items: Produce[]): ProduceGroup[] {
const groups: Record<string, Produce[]> = {};
items.forEach((item) => {
(groups[item.group] ??= []).push(item);
});
const order = ['Fruits', 'Vegetables'];
return order.map((value) => ({ value, items: groups[value] ?? [] }));
}
const groupedProduce: ProduceGroup[] = groupProduce(produceData);
const popupHiddenClass = 'scale-95 opacity-0';
</script>
<template>
<Combobox.Root :items="groupedProduce">
<div
class="relative flex flex-col gap-1 text-sm leading-5 font-bold text-neutral-950 dark:text-white"
>
<label :for="id">Select produce</label>
<Combobox.InputGroup
class="relative h-8 w-64 border border-neutral-950 bg-white dark:bg-neutral-950 focus-within:outline-2 focus-within:-outline-offset-1 focus-within:outline-neutral-950 dark:focus-within:outline-white dark:border-white [&>input]:pr-[calc(0.5rem+2rem)] has-[.combobox-clear]:[&>input]:pr-[calc(0.5rem+2rem*2)]"
>
<Combobox.Input
placeholder="e.g. Mango"
class="h-full w-full border-0 bg-white pl-2 dark:bg-neutral-950 text-sm any-pointer-coarse:text-base font-normal text-neutral-950 outline-none placeholder:text-neutral-500 dark:placeholder:text-neutral-400 dark:text-white"
:id="id"
/>
<div
class="absolute right-0 bottom-0 flex h-full items-center justify-center text-neutral-500 dark:text-neutral-400"
>
<Combobox.Clear
class="combobox-clear flex h-full w-6 items-center justify-center border-0 bg-transparent p-0 text-neutral-950 dark:text-white"
aria-label="Clear selection"
>
<XIcon />
</Combobox.Clear>
<Combobox.Trigger
class="flex h-full w-6 items-center justify-center border-0 bg-transparent p-0 text-neutral-950 dark:text-white"
aria-label="Open popup"
>
<CaretDownIcon />
</Combobox.Trigger>
</div>
</Combobox.InputGroup>
</div>
<Combobox.Portal>
<Combobox.Positioner class="outline-none" :side-offset="4">
<Transition :enter-from-class="popupHiddenClass" :leave-to-class="popupHiddenClass" appear>
<Combobox.Popup
class="w-[var(--anchor-width)] max-w-[var(--available-width)] origin-[var(--transform-origin)] border border-neutral-950 bg-white text-neutral-950 shadow-[0.25rem_0.25rem_0_rgb(0_0_0_/_12%)] transition-[scale,opacity] duration-100 dark:border-white dark:bg-neutral-950 dark:text-white dark:shadow-none"
>
<Combobox.Empty>
<div class="py-4 pr-4 pl-2 text-sm leading-4 text-neutral-500 dark:text-neutral-400">
No produce found.
</div>
</Combobox.Empty>
<Combobox.List
class="max-h-[min(22.5rem,var(--available-height))] overflow-auto overscroll-contain py-1 scroll-py-1 outline-0"
>
<template #item="{ item: group }">
<Combobox.Group class="block pb-2 last:pb-0">
<Combobox.GroupLabel
class="py-2 pr-2 pl-8 text-sm leading-4 text-neutral-500 select-none dark:text-neutral-400"
>
{{ group.value }}
</Combobox.GroupLabel>
<template v-for="item in group.items" :key="item.value">
<Combobox.Item
v-slot="{ state }"
class="grid cursor-default grid-cols-[1rem_1fr] items-center gap-2 p-2 text-sm leading-4 outline-none select-none data-highlighted:relative data-highlighted:z-0 data-highlighted:text-white data-highlighted:before:absolute data-highlighted:before:inset-0 data-highlighted:before:z-[-1] data-highlighted:before:bg-neutral-950 dark:data-highlighted:text-neutral-950 dark:data-highlighted:before:bg-white"
:value="item"
>
<span
v-if="state.selected"
class="col-start-1 flex items-center justify-center"
>
<CheckIcon />
</span>
<span class="col-start-2">{{ item.label }}</span>
</Combobox.Item>
</template>
</Combobox.Group>
</template>
</Combobox.List>
</Combobox.Popup>
</Transition>
</Combobox.Positioner>
</Combobox.Portal>
</Combobox.Root>
</template>Async search (single)
Load the items from a remote source when the input changes. The app does not need to load all items first. Keep the selected item in the items list, so that it stays available while new results arrive.
<script setup lang="ts">
import { computed, h, shallowRef, useId } from 'vue';
import type { FunctionalComponent } from 'vue';
import { Combobox } from '@vase-ui/vue/combobox';
import styles from './index.module.css';
const id = useId();
const searchResults = shallowRef<DirectoryUser[]>([]);
const selectedValue = shallowRef<DirectoryUser | null>(null);
const searchValue = shallowRef('');
const error = shallowRef<string | null>(null);
const isPending = shallowRef(false);
const { contains } = Combobox.useFilter();
let abortController: AbortController | null = null;
const trimmedSearchValue = computed(() => searchValue.value.trim());
const items = computed(() => {
const selected = selectedValue.value;
if (!selected || searchResults.value.some((user) => user.id === selected.id)) {
return searchResults.value;
}
return [...searchResults.value, selected];
});
const statusText = computed(() => {
if (error.value) {
return error.value;
}
if (trimmedSearchValue.value === '') {
return selectedValue.value ? null : 'Start typing to search people…';
}
if (searchResults.value.length === 0) {
return `No matches for "${trimmedSearchValue.value}".`;
}
return null;
});
const emptyMessage = computed(() => {
if (
trimmedSearchValue.value === '' ||
isPending.value ||
searchResults.value.length > 0 ||
error.value
) {
return null;
}
return 'Try a different search term.';
});
function handleOpenChange(open: boolean) {
if (!open && selectedValue.value) {
searchResults.value = [selectedValue.value];
}
}
function handleValueChange(nextSelectedValue: DirectoryUser | null) {
selectedValue.value = nextSelectedValue;
searchValue.value = '';
error.value = null;
}
async function handleInputValueChange(
nextSearchValue: string,
{ reason }: Combobox.Root.ChangeEventDetails,
) {
searchValue.value = nextSearchValue;
const controller = new AbortController();
abortController?.abort();
abortController = controller;
if (nextSearchValue === '') {
searchResults.value = [];
error.value = null;
isPending.value = false;
return;
}
if (reason === 'item-press') {
isPending.value = false;
return;
}
isPending.value = true;
error.value = null;
const result = await searchUsers(nextSearchValue, contains);
if (controller.signal.aborted) {
return;
}
searchResults.value = result.users;
error.value = result.error;
isPending.value = false;
}
const ICON_PROPS = {
width: '16',
height: '16',
viewBox: '0 0 16 16',
style: { display: 'block' },
};
const CheckIcon: FunctionalComponent = (_, { attrs }) =>
h('svg', { ...ICON_PROPS, fill: 'none', stroke: 'currentColor', ...attrs }, [
h('path', { d: 'm2.5 8.5 4 4 7-9' }),
]);
const XIcon: FunctionalComponent = (_, { attrs }) =>
h(
'svg',
{
...ICON_PROPS,
fill: 'none',
stroke: 'currentColor',
'stroke-linecap': 'square',
'stroke-linejoin': 'round',
...attrs,
},
[h('path', { d: 'm4.5 4.5 7 7m-7 0 7-7' })],
);
const CaretDownIcon: FunctionalComponent = (_, { attrs }) =>
h('svg', { ...ICON_PROPS, fill: 'currentColor', ...attrs }, [h('path', { d: 'M12 6H4l4 4.5z' })]);
interface DirectoryUser {
id: string;
name: string;
username: string;
email: string;
title: string;
}
async function searchUsers(
query: string,
filter: (item: string, query: string) => boolean,
): Promise<{ users: DirectoryUser[]; error: string | null }> {
// Simulate network delay
await new Promise((resolve) => {
setTimeout(resolve, Math.random() * 500 + 100);
});
// Simulate occasional network errors (1% chance)
if (Math.random() < 0.01 || query === 'will_error') {
return {
users: [],
error: 'Failed to fetch people. Please try again.',
};
}
const users = allUsers.filter((user) => {
return (
filter(user.name, query) ||
filter(user.username, query) ||
filter(user.email, query) ||
filter(user.title, query)
);
});
return {
users,
error: null,
};
}
const allUsers: DirectoryUser[] = [
{
id: 'leslie-alexander',
name: 'Leslie Alexander',
username: 'leslie',
email: 'leslie.alexander@example.com',
title: 'Product Manager',
},
{
id: 'kathryn-murphy',
name: 'Kathryn Murphy',
username: 'kathryn',
email: 'kathryn.murphy@example.com',
title: 'Marketing Lead',
},
{
id: 'courtney-henry',
name: 'Courtney Henry',
username: 'courtney',
email: 'courtney.henry@example.com',
title: 'Design Systems',
},
{
id: 'michael-foster',
name: 'Michael Foster',
username: 'michael',
email: 'michael.foster@example.com',
title: 'Engineering Manager',
},
{
id: 'lindsay-walton',
name: 'Lindsay Walton',
username: 'lindsay',
email: 'lindsay.walton@example.com',
title: 'Product Designer',
},
{
id: 'tom-cook',
name: 'Tom Cook',
username: 'tom',
email: 'tom.cook@example.com',
title: 'Frontend Engineer',
},
{
id: 'whitney-francis',
name: 'Whitney Francis',
username: 'whitney',
email: 'whitney.francis@example.com',
title: 'Customer Success',
},
{
id: 'jacob-jones',
name: 'Jacob Jones',
username: 'jacob',
email: 'jacob.jones@example.com',
title: 'Security Engineer',
},
{
id: 'arlene-mccoy',
name: 'Arlene McCoy',
username: 'arlene',
email: 'arlene.mccoy@example.com',
title: 'Data Analyst',
},
{
id: 'marvin-mckinney',
name: 'Marvin McKinney',
username: 'marvin',
email: 'marvin.mckinney@example.com',
title: 'QA Specialist',
},
{
id: 'eleanor-pena',
name: 'Eleanor Pena',
username: 'eleanor',
email: 'eleanor.pena@example.com',
title: 'Operations',
},
{
id: 'jerome-bell',
name: 'Jerome Bell',
username: 'jerome',
email: 'jerome.bell@example.com',
title: 'DevOps Engineer',
},
];
const popupHiddenClass = styles.PopupHidden;
const popupInstantClass = styles.PopupInstant;
</script>
<template>
<Combobox.Root
:items="items"
:item-to-string-label="(user: DirectoryUser) => user.name"
:is-item-equal-to-value="(item: DirectoryUser, value: DirectoryUser) => item.id === value.id"
:filter="null"
@update:open="handleOpenChange"
@value-change="handleValueChange"
@input-value-change="handleInputValueChange"
>
<div :class="styles.Label">
<label :for="id">Assign reviewer</label>
<Combobox.InputGroup :class="styles.InputGroup">
<Combobox.Input :id="id" placeholder="e.g. Michael" :class="styles.Input" />
<div :class="styles.ActionButtons">
<Combobox.Clear :class="styles.Clear" aria-label="Clear selection">
<XIcon />
</Combobox.Clear>
<Combobox.Trigger :class="styles.Trigger" aria-label="Open popup">
<CaretDownIcon />
</Combobox.Trigger>
</div>
</Combobox.InputGroup>
</div>
<Combobox.Portal>
<Combobox.Positioner :class="styles.Positioner" :side-offset="4">
<Transition
:enter-from-class="popupHiddenClass"
:leave-active-class="popupInstantClass"
appear
>
<Combobox.Popup :class="styles.Popup" :aria-busy="isPending || undefined">
<div :class="styles.Viewport">
<Combobox.Status>
<div v-if="isPending || statusText" :class="styles.Status">
<template v-if="isPending">
<span :class="styles.Spinner" aria-hidden="true" />
Searching…
</template>
<template v-else>{{ statusText }}</template>
</div>
</Combobox.Status>
<Combobox.Empty>
<div v-if="emptyMessage" :class="styles.Empty">{{ emptyMessage }}</div>
</Combobox.Empty>
<Combobox.List>
<template #item="{ item: user }">
<Combobox.Item v-slot="{ state }" :class="styles.Item" :value="user">
<span v-if="state.selected" :class="styles.ItemIndicator">
<CheckIcon />
</span>
<span :class="styles.ItemText">
<span :class="styles.ItemTitle">{{ user.name }}</span>
<span :class="styles.ItemEmail">{{ user.email }}</span>
<span :class="styles.ItemSubtitle">
<span>@{{ user.username }}</span>
<span>{{ user.title }}</span>
</span>
</span>
</Combobox.Item>
</template>
</Combobox.List>
</div>
</Combobox.Popup>
</Transition>
</Combobox.Positioner>
</Combobox.Portal>
</Combobox.Root>
</template>.Label {
display: flex;
flex-direction: column;
gap: 0.25rem;
font-size: 0.875rem;
line-height: 1.25rem;
font-weight: 700;
color: oklch(14.5% 0 0deg);
position: relative;
@media (prefers-color-scheme: dark) {
color: white;
}
}
.InputGroup {
box-sizing: border-box;
position: relative;
width: 16rem;
height: 2rem;
border: 1px solid oklch(14.5% 0 0deg);
background-color: white;
@media (prefers-color-scheme: dark) {
border: 1px solid white;
background-color: oklch(14.5% 0 0deg);
}
&:focus-within {
outline: 2px solid oklch(14.5% 0 0deg);
outline-offset: -1px;
@media (prefers-color-scheme: dark) {
outline-color: white;
}
}
@media (min-width: 32rem) {
width: 20rem;
}
&:has(.Clear) .Input {
padding: 0 calc(0.5rem + 2rem * 2) 0 0.5rem;
}
}
.Input {
box-sizing: border-box;
margin: 0;
width: 100%;
height: 100%;
padding: 0 calc(0.5rem + 2rem) 0 0.5rem;
border: none;
border-radius: 0;
font-family: inherit;
font-size: 0.875rem;
line-height: 1.25rem;
font-weight: 400;
background-color: white;
color: oklch(14.5% 0 0deg);
@media (any-pointer: coarse) {
font-size: 1rem;
line-height: 1.5rem;
}
@media (prefers-color-scheme: dark) {
background-color: oklch(14.5% 0 0deg);
color: white;
}
&::placeholder {
color: oklch(55.6% 0 0deg);
@media (prefers-color-scheme: dark) {
color: oklch(70.8% 0 0deg);
}
}
&:focus {
outline: none;
}
}
.ActionButtons {
box-sizing: border-box;
position: absolute;
display: flex;
align-items: center;
justify-content: center;
bottom: 0;
height: 100%;
right: 0;
border: none;
color: oklch(55.6% 0 0deg);
padding: 0;
@media (prefers-color-scheme: dark) {
color: oklch(70.8% 0 0deg);
}
}
.Trigger,
.Clear {
box-sizing: border-box;
display: flex;
align-items: center;
justify-content: center;
width: 1.5rem;
height: 100%;
color: oklch(14.5% 0 0deg);
border: none;
padding: 0;
background: none;
@media (prefers-color-scheme: dark) {
color: white;
}
}
.Positioner {
outline: 0;
}
.Popup {
box-sizing: border-box;
background-color: white;
color: oklch(14.5% 0 0deg);
width: var(--anchor-width);
max-width: var(--available-width);
transition:
opacity 0.1s,
transform 0.1s;
transform-origin: var(--transform-origin);
border: 1px solid oklch(14.5% 0 0deg);
box-shadow: 0.25rem 0.25rem 0 rgb(0 0 0 / 12%);
@media (prefers-color-scheme: dark) {
background-color: oklch(14.5% 0 0deg);
color: white;
border: 1px solid white;
box-shadow: none;
}
}
/* The enter-from class of the `<Transition>` around the popup. */
.PopupHidden {
opacity: 0;
transform: scale(0.95);
}
/* The leave class of the `<Transition>`: the popup closes with no animation. */
.PopupInstant {
transition: none;
}
.Viewport {
box-sizing: border-box;
max-height: min(var(--available-height), 22.5rem);
padding-block: 0.25rem;
overflow-y: auto;
overscroll-behavior: contain;
scroll-padding-block: 0.25rem;
}
.Status {
display: flex;
align-items: center;
gap: 0.5rem;
padding-block: 0.25rem;
padding-left: 0.5rem;
padding-right: 1.25rem;
font-size: 0.875rem;
line-height: 1.25rem;
color: oklch(55.6% 0 0deg);
@media (prefers-color-scheme: dark) {
color: oklch(70.8% 0 0deg);
}
}
.Spinner {
box-sizing: border-box;
width: 0.75rem;
height: 0.75rem;
border-radius: 10rem;
border: 1px solid currentColor;
border-right-color: transparent;
animation: comboboxSpinner 0.75s linear infinite;
}
@keyframes comboboxSpinner {
100% {
transform: rotate(360deg);
}
}
.Item {
box-sizing: border-box;
outline: 0;
cursor: default;
-webkit-user-select: none;
user-select: none;
padding-block: 0.5rem;
padding-inline: 0.5rem;
display: grid;
gap: 0.5rem;
align-items: flex-start;
grid-template-columns: 1rem 1fr;
font-size: 0.875rem;
line-height: 1.2rem;
@media (hover: hover) {
&[data-highlighted] {
z-index: 0;
position: relative;
color: oklch(14.5% 0 0deg);
@media (prefers-color-scheme: dark) {
color: white;
}
}
&[data-highlighted]::before {
content: '';
z-index: -1;
position: absolute;
inset-block: 0;
inset-inline: 0;
background-color: oklch(97% 0 0deg);
@media (prefers-color-scheme: dark) {
background-color: oklch(26.9% 0 0deg);
}
}
}
}
.ItemIndicator {
grid-column-start: 1;
margin-top: 0.25rem;
}
.ItemText {
grid-column-start: 2;
display: flex;
flex-direction: column;
gap: 0.25rem;
}
.ItemTitle {
font-size: 0.875rem;
line-height: 1.25rem;
font-weight: 700;
}
.ItemSubtitle {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
font-size: 0.75rem;
color: oklch(55.6% 0 0deg);
@media (prefers-color-scheme: dark) {
color: oklch(70.8% 0 0deg);
}
}
.ItemEmail {
font-size: 0.75rem;
}
.Empty {
box-sizing: border-box;
font-size: 0.875rem;
line-height: 1rem;
color: oklch(55.6% 0 0deg);
padding: 0.5rem 1rem 0.5rem 0.5rem;
@media (prefers-color-scheme: dark) {
color: oklch(70.8% 0 0deg);
}
}<script setup lang="ts">
import { computed, h, shallowRef, useId } from 'vue';
import type { FunctionalComponent } from 'vue';
import { Combobox } from '@vase-ui/vue/combobox';
const id = useId();
const searchResults = shallowRef<DirectoryUser[]>([]);
const selectedValue = shallowRef<DirectoryUser | null>(null);
const searchValue = shallowRef('');
const error = shallowRef<string | null>(null);
const isPending = shallowRef(false);
const { contains } = Combobox.useFilter();
let abortController: AbortController | null = null;
const trimmedSearchValue = computed(() => searchValue.value.trim());
const items = computed(() => {
const selected = selectedValue.value;
if (!selected || searchResults.value.some((user) => user.id === selected.id)) {
return searchResults.value;
}
return [...searchResults.value, selected];
});
const statusText = computed(() => {
if (error.value) {
return error.value;
}
if (trimmedSearchValue.value === '') {
return selectedValue.value ? null : 'Start typing to search people…';
}
if (searchResults.value.length === 0) {
return `No matches for "${trimmedSearchValue.value}".`;
}
return null;
});
const emptyMessage = computed(() => {
if (
trimmedSearchValue.value === '' ||
isPending.value ||
searchResults.value.length > 0 ||
error.value
) {
return null;
}
return 'Try a different search term.';
});
function handleOpenChange(open: boolean) {
if (!open && selectedValue.value) {
searchResults.value = [selectedValue.value];
}
}
function handleValueChange(nextSelectedValue: DirectoryUser | null) {
selectedValue.value = nextSelectedValue;
searchValue.value = '';
error.value = null;
}
async function handleInputValueChange(
nextSearchValue: string,
{ reason }: Combobox.Root.ChangeEventDetails,
) {
searchValue.value = nextSearchValue;
const controller = new AbortController();
abortController?.abort();
abortController = controller;
if (nextSearchValue === '') {
searchResults.value = [];
error.value = null;
isPending.value = false;
return;
}
if (reason === 'item-press') {
isPending.value = false;
return;
}
isPending.value = true;
error.value = null;
const result = await searchUsers(nextSearchValue, contains);
if (controller.signal.aborted) {
return;
}
searchResults.value = result.users;
error.value = result.error;
isPending.value = false;
}
const ICON_PROPS = {
width: '16',
height: '16',
viewBox: '0 0 16 16',
style: { display: 'block' },
};
const CheckIcon: FunctionalComponent = (_, { attrs }) =>
h('svg', { ...ICON_PROPS, fill: 'none', stroke: 'currentColor', ...attrs }, [
h('path', { d: 'm2.5 8.5 4 4 7-9' }),
]);
const XIcon: FunctionalComponent = (_, { attrs }) =>
h(
'svg',
{
...ICON_PROPS,
fill: 'none',
stroke: 'currentColor',
'stroke-linecap': 'square',
'stroke-linejoin': 'round',
...attrs,
},
[h('path', { d: 'm4.5 4.5 7 7m-7 0 7-7' })],
);
const CaretDownIcon: FunctionalComponent = (_, { attrs }) =>
h('svg', { ...ICON_PROPS, fill: 'currentColor', ...attrs }, [h('path', { d: 'M12 6H4l4 4.5z' })]);
interface DirectoryUser {
id: string;
name: string;
username: string;
email: string;
title: string;
}
async function searchUsers(
query: string,
filter: (item: string, query: string) => boolean,
): Promise<{ users: DirectoryUser[]; error: string | null }> {
// Simulate network delay
await new Promise((resolve) => {
setTimeout(resolve, Math.random() * 500 + 100);
});
// Simulate occasional network errors (1% chance)
if (Math.random() < 0.01 || query === 'will_error') {
return {
users: [],
error: 'Failed to fetch people. Please try again.',
};
}
const users = allUsers.filter((user) => {
return (
filter(user.name, query) ||
filter(user.username, query) ||
filter(user.email, query) ||
filter(user.title, query)
);
});
return {
users,
error: null,
};
}
const allUsers: DirectoryUser[] = [
{
id: 'leslie-alexander',
name: 'Leslie Alexander',
username: 'leslie',
email: 'leslie.alexander@example.com',
title: 'Product Manager',
},
{
id: 'kathryn-murphy',
name: 'Kathryn Murphy',
username: 'kathryn',
email: 'kathryn.murphy@example.com',
title: 'Marketing Lead',
},
{
id: 'courtney-henry',
name: 'Courtney Henry',
username: 'courtney',
email: 'courtney.henry@example.com',
title: 'Design Systems',
},
{
id: 'michael-foster',
name: 'Michael Foster',
username: 'michael',
email: 'michael.foster@example.com',
title: 'Engineering Manager',
},
{
id: 'lindsay-walton',
name: 'Lindsay Walton',
username: 'lindsay',
email: 'lindsay.walton@example.com',
title: 'Product Designer',
},
{
id: 'tom-cook',
name: 'Tom Cook',
username: 'tom',
email: 'tom.cook@example.com',
title: 'Frontend Engineer',
},
{
id: 'whitney-francis',
name: 'Whitney Francis',
username: 'whitney',
email: 'whitney.francis@example.com',
title: 'Customer Success',
},
{
id: 'jacob-jones',
name: 'Jacob Jones',
username: 'jacob',
email: 'jacob.jones@example.com',
title: 'Security Engineer',
},
{
id: 'arlene-mccoy',
name: 'Arlene McCoy',
username: 'arlene',
email: 'arlene.mccoy@example.com',
title: 'Data Analyst',
},
{
id: 'marvin-mckinney',
name: 'Marvin McKinney',
username: 'marvin',
email: 'marvin.mckinney@example.com',
title: 'QA Specialist',
},
{
id: 'eleanor-pena',
name: 'Eleanor Pena',
username: 'eleanor',
email: 'eleanor.pena@example.com',
title: 'Operations',
},
{
id: 'jerome-bell',
name: 'Jerome Bell',
username: 'jerome',
email: 'jerome.bell@example.com',
title: 'DevOps Engineer',
},
];
const popupHiddenClass = 'scale-95 opacity-0';
const popupInstantClass = 'transition-none';
</script>
<template>
<Combobox.Root
:items="items"
:item-to-string-label="(user: DirectoryUser) => user.name"
:is-item-equal-to-value="(item: DirectoryUser, value: DirectoryUser) => item.id === value.id"
:filter="null"
@update:open="handleOpenChange"
@value-change="handleValueChange"
@input-value-change="handleInputValueChange"
>
<div
class="relative flex flex-col gap-1 text-sm leading-5 font-bold text-neutral-950 dark:text-white"
>
<label :for="id">Assign reviewer</label>
<Combobox.InputGroup
class="relative h-8 w-64 border border-neutral-950 bg-white dark:bg-neutral-950 focus-within:outline-2 focus-within:-outline-offset-1 focus-within:outline-neutral-950 dark:focus-within:outline-white dark:border-white md:w-80 [&>input]:pr-[calc(0.5rem+2rem)] has-[.combobox-clear]:[&>input]:pr-[calc(0.5rem+2rem*2)]"
>
<Combobox.Input
:id="id"
placeholder="e.g. Michael"
class="h-full w-full border-0 bg-white pl-2 dark:bg-neutral-950 text-sm any-pointer-coarse:text-base font-normal text-neutral-950 outline-none placeholder:text-neutral-500 dark:placeholder:text-neutral-400 dark:text-white"
/>
<div
class="absolute right-0 bottom-0 flex h-full items-center justify-center text-neutral-500 dark:text-neutral-400"
>
<Combobox.Clear
class="combobox-clear flex h-full w-6 items-center justify-center border-0 bg-transparent p-0 text-neutral-950 dark:text-white"
aria-label="Clear selection"
>
<XIcon />
</Combobox.Clear>
<Combobox.Trigger
class="flex h-full w-6 items-center justify-center border-0 bg-transparent p-0 text-neutral-950 dark:text-white"
aria-label="Open popup"
>
<CaretDownIcon />
</Combobox.Trigger>
</div>
</Combobox.InputGroup>
</div>
<Combobox.Portal>
<Combobox.Positioner class="outline-none" :side-offset="4">
<Transition
:enter-from-class="popupHiddenClass"
:leave-active-class="popupInstantClass"
appear
>
<Combobox.Popup
class="w-[var(--anchor-width)] max-w-[var(--available-width)] origin-[var(--transform-origin)] border border-neutral-950 bg-white text-neutral-950 shadow-[0.25rem_0.25rem_0_rgb(0_0_0_/_12%)] transition-[scale,opacity] dark:border-white dark:bg-neutral-950 dark:text-white dark:shadow-none"
:aria-busy="isPending || undefined"
>
<div
class="max-h-[min(var(--available-height),22.5rem)] overflow-y-auto overscroll-contain py-1 scroll-pt-1 scroll-pb-1"
>
<Combobox.Status>
<div
v-if="isPending || statusText"
class="flex items-center gap-2 py-1 pr-5 pl-2 text-sm leading-5 text-neutral-500 dark:text-neutral-400"
>
<template v-if="isPending">
<span
class="inline-block size-3 animate-spin rounded-full border border-current border-r-transparent"
aria-hidden="true"
/>
Searching…
</template>
<template v-else>{{ statusText }}</template>
</div>
</Combobox.Status>
<Combobox.Empty>
<div
v-if="emptyMessage"
class="py-2 pr-4 pl-2 text-sm leading-4 text-neutral-500 dark:text-neutral-400"
>
{{ emptyMessage }}
</div>
</Combobox.Empty>
<Combobox.List>
<template #item="{ item: user }">
<Combobox.Item
v-slot="{ state }"
class="grid cursor-default grid-cols-[1rem_1fr] items-start gap-2 px-2 py-2 text-sm leading-[1.2rem] outline-none select-none [@media(hover:hover)]:data-highlighted:relative [@media(hover:hover)]:data-highlighted:z-0 [@media(hover:hover)]:data-highlighted:text-neutral-950 [@media(hover:hover)]:data-highlighted:before:absolute [@media(hover:hover)]:data-highlighted:before:inset-0 [@media(hover:hover)]:data-highlighted:before:z-[-1] [@media(hover:hover)]:data-highlighted:before:bg-neutral-100 dark:[@media(hover:hover)]:data-highlighted:text-white dark:[@media(hover:hover)]:data-highlighted:before:bg-neutral-800"
:value="user"
>
<span v-if="state.selected" class="col-start-1 mt-1">
<CheckIcon />
</span>
<span class="col-start-2 flex flex-col gap-1">
<span class="text-sm leading-5 font-bold">{{ user.name }}</span>
<span class="text-xs">{{ user.email }}</span>
<span
class="flex flex-wrap gap-2 text-xs text-neutral-500 dark:text-neutral-400"
>
<span>@{{ user.username }}</span>
<span>{{ user.title }}</span>
</span>
</span>
</Combobox.Item>
</template>
</Combobox.List>
</div>
</Combobox.Popup>
</Transition>
</Combobox.Positioner>
</Combobox.Portal>
</Combobox.Root>
</template>Async search (multiple)
Load the items from a remote source when the input changes, and allow more than one selected item. The app does not need to load all items first. The selected items stay in the list while new matches arrive.
<script setup lang="ts">
import { computed, h, shallowRef, useId } from 'vue';
import type { FunctionalComponent } from 'vue';
import { Combobox } from '@vase-ui/vue/combobox';
import styles from './index.module.css';
const id = useId();
const searchResults = shallowRef<DirectoryUser[]>([]);
const selectedValues = shallowRef<DirectoryUser[]>([]);
const searchValue = shallowRef('');
const error = shallowRef<string | null>(null);
const blockStartStatus = shallowRef(false);
const isPending = shallowRef(false);
const { contains } = Combobox.useFilter();
let abortController: AbortController | null = null;
const trimmedSearchValue = computed(() => searchValue.value.trim());
const items = computed(() => {
if (selectedValues.value.length === 0) {
return searchResults.value;
}
const merged = [...searchResults.value];
selectedValues.value.forEach((user) => {
if (!searchResults.value.some((result) => result.id === user.id)) {
merged.push(user);
}
});
return merged;
});
const statusText = computed(() => {
if (error.value) {
return error.value;
}
if (trimmedSearchValue.value === '' && !blockStartStatus.value) {
return selectedValues.value.length > 0 ? null : 'Start typing to search people…';
}
if (searchResults.value.length === 0 && !blockStartStatus.value) {
return `No matches for "${trimmedSearchValue.value}".`;
}
return null;
});
const emptyMessage = computed(() => {
if (
trimmedSearchValue.value === '' ||
isPending.value ||
searchResults.value.length > 0 ||
error.value
) {
return null;
}
return 'Try a different search term.';
});
function handleOpenChange(open: boolean) {
if (!open) {
searchResults.value = selectedValues.value;
blockStartStatus.value = false;
}
}
function handleValueChange(nextSelectedValues: DirectoryUser[]) {
selectedValues.value = nextSelectedValues;
searchValue.value = '';
error.value = null;
if (nextSelectedValues.length === 0) {
searchResults.value = [];
blockStartStatus.value = false;
} else {
blockStartStatus.value = true;
}
}
async function handleInputValueChange(
nextSearchValue: string,
{ reason }: Combobox.Root.ChangeEventDetails,
) {
searchValue.value = nextSearchValue;
const controller = new AbortController();
abortController?.abort();
abortController = controller;
if (nextSearchValue === '') {
searchResults.value = selectedValues.value;
error.value = null;
blockStartStatus.value = false;
isPending.value = false;
return;
}
if (reason === 'item-press') {
isPending.value = false;
return;
}
isPending.value = true;
error.value = null;
const result = await searchUsers(nextSearchValue, contains);
if (controller.signal.aborted) {
return;
}
searchResults.value = result.users;
error.value = result.error;
isPending.value = false;
}
const ICON_PROPS = {
width: '16',
height: '16',
viewBox: '0 0 16 16',
style: { display: 'block' },
};
const CheckIcon: FunctionalComponent = (_, { attrs }) =>
h('svg', { ...ICON_PROPS, fill: 'none', stroke: 'currentColor', ...attrs }, [
h('path', { d: 'm2.5 8.5 4 4 7-9' }),
]);
const XIcon: FunctionalComponent = (_, { attrs }) =>
h(
'svg',
{
...ICON_PROPS,
fill: 'none',
stroke: 'currentColor',
'stroke-linecap': 'square',
'stroke-linejoin': 'round',
...attrs,
},
[h('path', { d: 'm4.5 4.5 7 7m-7 0 7-7' })],
);
interface DirectoryUser {
id: string;
name: string;
username: string;
email: string;
title: string;
}
async function searchUsers(
query: string,
filter: (item: string, query: string) => boolean,
): Promise<{ users: DirectoryUser[]; error: string | null }> {
// Simulate network delay
await new Promise((resolve) => {
setTimeout(resolve, Math.random() * 500 + 100);
});
// Simulate occasional network errors (1% chance)
if (Math.random() < 0.01 || query === 'will_error') {
return {
users: [],
error: 'Failed to fetch people. Please try again.',
};
}
const users = allUsers.filter((user) => {
return (
filter(user.name, query) ||
filter(user.username, query) ||
filter(user.email, query) ||
filter(user.title, query)
);
});
return {
users,
error: null,
};
}
const allUsers: DirectoryUser[] = [
{
id: 'leslie-alexander',
name: 'Leslie Alexander',
username: 'leslie',
email: 'leslie.alexander@example.com',
title: 'Product Manager',
},
{
id: 'kathryn-murphy',
name: 'Kathryn Murphy',
username: 'kathryn',
email: 'kathryn.murphy@example.com',
title: 'Marketing Lead',
},
{
id: 'courtney-henry',
name: 'Courtney Henry',
username: 'courtney',
email: 'courtney.henry@example.com',
title: 'Design Systems',
},
{
id: 'michael-foster',
name: 'Michael Foster',
username: 'michael',
email: 'michael.foster@example.com',
title: 'Engineering Manager',
},
{
id: 'lindsay-walton',
name: 'Lindsay Walton',
username: 'lindsay',
email: 'lindsay.walton@example.com',
title: 'Product Designer',
},
{
id: 'tom-cook',
name: 'Tom Cook',
username: 'tom',
email: 'tom.cook@example.com',
title: 'Frontend Engineer',
},
{
id: 'whitney-francis',
name: 'Whitney Francis',
username: 'whitney',
email: 'whitney.francis@example.com',
title: 'Customer Success',
},
{
id: 'jacob-jones',
name: 'Jacob Jones',
username: 'jacob',
email: 'jacob.jones@example.com',
title: 'Security Engineer',
},
{
id: 'arlene-mccoy',
name: 'Arlene McCoy',
username: 'arlene',
email: 'arlene.mccoy@example.com',
title: 'Data Analyst',
},
{
id: 'marvin-mckinney',
name: 'Marvin McKinney',
username: 'marvin',
email: 'marvin.mckinney@example.com',
title: 'QA Specialist',
},
{
id: 'eleanor-pena',
name: 'Eleanor Pena',
username: 'eleanor',
email: 'eleanor.pena@example.com',
title: 'Operations',
},
{
id: 'jerome-bell',
name: 'Jerome Bell',
username: 'jerome',
email: 'jerome.bell@example.com',
title: 'DevOps Engineer',
},
];
const popupHiddenClass = styles.PopupHidden;
</script>
<template>
<Combobox.Root
:items="items"
:item-to-string-label="(user: DirectoryUser) => user.name"
:is-item-equal-to-value="(item: DirectoryUser, value: DirectoryUser) => item.id === value.id"
multiple
:filter="null"
@update:open="handleOpenChange"
@value-change="handleValueChange"
@input-value-change="handleInputValueChange"
>
<div :class="styles.Container">
<label :class="styles.Label" :for="id">Assign reviewers</label>
<Combobox.InputGroup :class="styles.InputGroup">
<Combobox.Value v-slot="{ value }">
<Combobox.Chips
:class="styles.Chips"
:aria-label="value.length > 0 ? 'Selected reviewers' : undefined"
>
<Combobox.Chip
v-for="user in value"
:key="user.id"
:class="styles.Chip"
:aria-label="user.name"
aria-description="Press Backspace or Delete to remove"
>
{{ user.name }}
<Combobox.ChipRemove :class="styles.ChipRemove" :aria-label="`Remove ${user.name}`">
<XIcon />
</Combobox.ChipRemove>
</Combobox.Chip>
<Combobox.Input
:id="id"
:placeholder="value.length > 0 ? '' : 'e.g. Michael'"
:aria-description="
value.length > 0
? `${value.length} selected. From the start of the input, press Left Arrow to focus the selected items`
: undefined
"
:class="styles.Input"
/>
</Combobox.Chips>
</Combobox.Value>
</Combobox.InputGroup>
</div>
<Combobox.Portal>
<Combobox.Positioner :class="styles.Positioner" :side-offset="4">
<Transition :enter-from-class="popupHiddenClass" :leave-to-class="popupHiddenClass" appear>
<Combobox.Popup :class="styles.Popup" :aria-busy="isPending || undefined">
<div :class="styles.Viewport">
<Combobox.Status>
<div v-if="isPending || statusText" :class="styles.Status">
<template v-if="isPending">
<span :class="styles.Spinner" aria-hidden="true" />
Searching…
</template>
<template v-else>{{ statusText }}</template>
</div>
</Combobox.Status>
<Combobox.Empty>
<div v-if="emptyMessage" :class="styles.Empty">{{ emptyMessage }}</div>
</Combobox.Empty>
<Combobox.List>
<template #item="{ item: user }">
<Combobox.Item v-slot="{ state }" :class="styles.Item" :value="user">
<span v-if="state.selected" :class="styles.ItemIndicator">
<CheckIcon />
</span>
<span :class="styles.ItemText">
<span :class="styles.ItemTitle">{{ user.name }}</span>
<span :class="styles.ItemEmail">{{ user.email }}</span>
<span :class="styles.ItemSubtitle">
<span>@{{ user.username }}</span>
<span>{{ user.title }}</span>
</span>
</span>
</Combobox.Item>
</template>
</Combobox.List>
</div>
</Combobox.Popup>
</Transition>
</Combobox.Positioner>
</Combobox.Portal>
</Combobox.Root>
</template>.Container {
max-width: 28rem;
display: flex;
flex-direction: column;
gap: 0.25rem;
}
.Label {
display: flex;
flex-direction: column;
gap: 0.25rem;
font-size: 0.875rem;
line-height: 1.25rem;
font-weight: 700;
color: oklch(14.5% 0 0deg);
@media (prefers-color-scheme: dark) {
color: white;
}
}
.InputGroup {
box-sizing: border-box;
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 0.125rem;
border: 1px solid oklch(14.5% 0 0deg);
background-color: white;
min-height: 2rem;
padding: 0.25rem 0.5rem;
width: 16rem;
cursor: text;
@media (min-width: 32rem) {
width: 22rem;
}
@media (prefers-color-scheme: dark) {
border: 1px solid white;
background-color: oklch(14.5% 0 0deg);
}
&:has(.Chip) {
padding-inline: 0.25rem;
}
&:focus-within {
outline: 2px solid oklch(14.5% 0 0deg);
outline-offset: -1px;
@media (prefers-color-scheme: dark) {
outline-color: white;
}
}
}
.Chips {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 0.25rem;
width: 100%;
}
.Chip {
box-sizing: border-box;
display: flex;
align-items: center;
min-height: calc(1.5rem - 2px);
background-color: oklch(97% 0 0deg);
color: oklch(14.5% 0 0deg);
font-size: 0.875rem;
line-height: 1;
padding: 0 0.2rem 0 0.4rem;
overflow: hidden;
gap: 0.25rem;
outline: 0;
cursor: default;
@media (prefers-color-scheme: dark) {
background-color: oklch(26.9% 0 0deg);
color: white;
}
&:focus-within {
background-color: oklch(14.5% 0 0deg);
color: white;
@media (prefers-color-scheme: dark) {
background-color: white;
color: oklch(14.5% 0 0deg);
}
}
@media (hover: hover) {
&[data-highlighted] {
background-color: oklch(14.5% 0 0deg);
color: white;
@media (prefers-color-scheme: dark) {
background-color: white;
color: oklch(14.5% 0 0deg);
}
}
}
}
.ChipRemove {
box-sizing: border-box;
width: 1rem;
height: 1rem;
padding: 0;
border: none;
background: none;
display: flex;
align-items: center;
justify-content: center;
color: inherit;
@media (hover: hover) {
&:hover {
background-color: oklch(92.2% 0 0deg);
@media (prefers-color-scheme: dark) {
background-color: oklch(37.1% 0 0deg);
}
}
}
}
.Chip:focus-within .ChipRemove {
@media (hover: hover) {
&:hover {
background-color: oklch(37.1% 0 0deg);
@media (prefers-color-scheme: dark) {
background-color: oklch(92.2% 0 0deg);
}
}
}
}
.Input {
flex: 1;
box-sizing: border-box;
padding: 0;
margin: 0;
border: none;
border-radius: 0;
height: calc(1.5rem - 2px);
font-family: inherit;
font-size: 0.875rem;
line-height: 1.25rem;
font-weight: 400;
background-color: white;
color: oklch(14.5% 0 0deg);
min-width: 3rem;
@media (any-pointer: coarse) {
font-size: 1rem;
line-height: 1.5rem;
}
@media (prefers-color-scheme: dark) {
background-color: oklch(14.5% 0 0deg);
color: white;
}
&::placeholder {
color: oklch(55.6% 0 0deg);
@media (prefers-color-scheme: dark) {
color: oklch(70.8% 0 0deg);
}
}
&:focus {
outline: none;
}
}
.Positioner {
outline: 0;
z-index: 50;
}
.Popup {
box-sizing: border-box;
background-color: white;
color: oklch(14.5% 0 0deg);
width: var(--anchor-width);
max-width: var(--available-width);
transition:
opacity 0.1s,
transform 0.1s;
transform-origin: var(--transform-origin);
border: 1px solid oklch(14.5% 0 0deg);
box-shadow: 0.25rem 0.25rem 0 rgb(0 0 0 / 12%);
@media (prefers-color-scheme: dark) {
background-color: oklch(14.5% 0 0deg);
color: white;
border: 1px solid white;
box-shadow: none;
}
}
/* The enter-from and leave-to class of the `<Transition>` around the popup. */
.PopupHidden {
opacity: 0;
transform: scale(0.95);
}
.Viewport {
box-sizing: border-box;
max-height: min(var(--available-height), 24.5rem);
padding-block: 0.25rem;
overflow-y: auto;
overscroll-behavior: contain;
scroll-padding-block: 0.25rem;
}
.Status {
display: flex;
align-items: center;
gap: 0.5rem;
padding-block: 0.25rem;
padding-left: 0.5rem;
padding-right: 1.25rem;
font-size: 0.875rem;
line-height: 1.25rem;
color: oklch(55.6% 0 0deg);
@media (prefers-color-scheme: dark) {
color: oklch(70.8% 0 0deg);
}
}
.Spinner {
box-sizing: border-box;
width: 0.75rem;
height: 0.75rem;
border-radius: 10rem;
border: 1px solid currentColor;
border-right-color: transparent;
animation: comboboxSpinner 0.75s linear infinite;
}
@keyframes comboboxSpinner {
100% {
transform: rotate(360deg);
}
}
.Empty {
box-sizing: border-box;
font-size: 0.875rem;
line-height: 1rem;
color: oklch(55.6% 0 0deg);
padding: 0.5rem 1rem 0.5rem 0.5rem;
@media (prefers-color-scheme: dark) {
color: oklch(70.8% 0 0deg);
}
}
.Item {
box-sizing: border-box;
outline: 0;
cursor: default;
-webkit-user-select: none;
user-select: none;
padding-block: 0.5rem;
padding-inline: 0.5rem;
display: grid;
gap: 0.5rem;
align-items: flex-start;
grid-template-columns: 1rem 1fr;
font-size: 0.875rem;
line-height: 1.2rem;
@media (hover: hover) {
&[data-highlighted] {
z-index: 0;
position: relative;
color: oklch(14.5% 0 0deg);
@media (prefers-color-scheme: dark) {
color: white;
}
}
&[data-highlighted]::before {
content: '';
z-index: -1;
position: absolute;
inset-block: 0;
inset-inline: 0;
background-color: oklch(97% 0 0deg);
@media (prefers-color-scheme: dark) {
background-color: oklch(26.9% 0 0deg);
}
}
}
}
.ItemIndicator {
grid-column-start: 1;
margin-top: 0.25rem;
}
.ItemText {
grid-column-start: 2;
display: flex;
flex-direction: column;
gap: 0.25rem;
}
.ItemTitle {
font-size: 0.875rem;
line-height: 1.25rem;
font-weight: 700;
}
.ItemSubtitle {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
font-size: 0.75rem;
color: oklch(55.6% 0 0deg);
@media (prefers-color-scheme: dark) {
color: oklch(70.8% 0 0deg);
}
}
.ItemEmail {
font-size: 0.75rem;
}<script setup lang="ts">
import { computed, h, shallowRef, useId } from 'vue';
import type { FunctionalComponent } from 'vue';
import { Combobox } from '@vase-ui/vue/combobox';
const id = useId();
const searchResults = shallowRef<DirectoryUser[]>([]);
const selectedValues = shallowRef<DirectoryUser[]>([]);
const searchValue = shallowRef('');
const error = shallowRef<string | null>(null);
const blockStartStatus = shallowRef(false);
const isPending = shallowRef(false);
const { contains } = Combobox.useFilter();
let abortController: AbortController | null = null;
const trimmedSearchValue = computed(() => searchValue.value.trim());
const items = computed(() => {
if (selectedValues.value.length === 0) {
return searchResults.value;
}
const merged = [...searchResults.value];
selectedValues.value.forEach((user) => {
if (!searchResults.value.some((result) => result.id === user.id)) {
merged.push(user);
}
});
return merged;
});
const statusText = computed(() => {
if (error.value) {
return error.value;
}
if (trimmedSearchValue.value === '' && !blockStartStatus.value) {
return selectedValues.value.length > 0 ? null : 'Start typing to search people…';
}
if (searchResults.value.length === 0 && !blockStartStatus.value) {
return `No matches for "${trimmedSearchValue.value}".`;
}
return null;
});
const emptyMessage = computed(() => {
if (
trimmedSearchValue.value === '' ||
isPending.value ||
searchResults.value.length > 0 ||
error.value
) {
return null;
}
return 'Try a different search term.';
});
function handleOpenChange(open: boolean) {
if (!open) {
searchResults.value = selectedValues.value;
blockStartStatus.value = false;
}
}
function handleValueChange(nextSelectedValues: DirectoryUser[]) {
selectedValues.value = nextSelectedValues;
searchValue.value = '';
error.value = null;
if (nextSelectedValues.length === 0) {
searchResults.value = [];
blockStartStatus.value = false;
} else {
blockStartStatus.value = true;
}
}
async function handleInputValueChange(
nextSearchValue: string,
{ reason }: Combobox.Root.ChangeEventDetails,
) {
searchValue.value = nextSearchValue;
const controller = new AbortController();
abortController?.abort();
abortController = controller;
if (nextSearchValue === '') {
searchResults.value = selectedValues.value;
error.value = null;
blockStartStatus.value = false;
isPending.value = false;
return;
}
if (reason === 'item-press') {
isPending.value = false;
return;
}
isPending.value = true;
error.value = null;
const result = await searchUsers(nextSearchValue, contains);
if (controller.signal.aborted) {
return;
}
searchResults.value = result.users;
error.value = result.error;
isPending.value = false;
}
const ICON_PROPS = {
width: '16',
height: '16',
viewBox: '0 0 16 16',
style: { display: 'block' },
};
const CheckIcon: FunctionalComponent = (_, { attrs }) =>
h('svg', { ...ICON_PROPS, fill: 'none', stroke: 'currentColor', ...attrs }, [
h('path', { d: 'm2.5 8.5 4 4 7-9' }),
]);
const XIcon: FunctionalComponent = (_, { attrs }) =>
h(
'svg',
{
...ICON_PROPS,
fill: 'none',
stroke: 'currentColor',
'stroke-linecap': 'square',
'stroke-linejoin': 'round',
...attrs,
},
[h('path', { d: 'm4.5 4.5 7 7m-7 0 7-7' })],
);
interface DirectoryUser {
id: string;
name: string;
username: string;
email: string;
title: string;
}
async function searchUsers(
query: string,
filter: (item: string, query: string) => boolean,
): Promise<{ users: DirectoryUser[]; error: string | null }> {
// Simulate network delay
await new Promise((resolve) => {
setTimeout(resolve, Math.random() * 500 + 100);
});
// Simulate occasional network errors (1% chance)
if (Math.random() < 0.01 || query === 'will_error') {
return {
users: [],
error: 'Failed to fetch people. Please try again.',
};
}
const users = allUsers.filter((user) => {
return (
filter(user.name, query) ||
filter(user.username, query) ||
filter(user.email, query) ||
filter(user.title, query)
);
});
return {
users,
error: null,
};
}
const allUsers: DirectoryUser[] = [
{
id: 'leslie-alexander',
name: 'Leslie Alexander',
username: 'leslie',
email: 'leslie.alexander@example.com',
title: 'Product Manager',
},
{
id: 'kathryn-murphy',
name: 'Kathryn Murphy',
username: 'kathryn',
email: 'kathryn.murphy@example.com',
title: 'Marketing Lead',
},
{
id: 'courtney-henry',
name: 'Courtney Henry',
username: 'courtney',
email: 'courtney.henry@example.com',
title: 'Design Systems',
},
{
id: 'michael-foster',
name: 'Michael Foster',
username: 'michael',
email: 'michael.foster@example.com',
title: 'Engineering Manager',
},
{
id: 'lindsay-walton',
name: 'Lindsay Walton',
username: 'lindsay',
email: 'lindsay.walton@example.com',
title: 'Product Designer',
},
{
id: 'tom-cook',
name: 'Tom Cook',
username: 'tom',
email: 'tom.cook@example.com',
title: 'Frontend Engineer',
},
{
id: 'whitney-francis',
name: 'Whitney Francis',
username: 'whitney',
email: 'whitney.francis@example.com',
title: 'Customer Success',
},
{
id: 'jacob-jones',
name: 'Jacob Jones',
username: 'jacob',
email: 'jacob.jones@example.com',
title: 'Security Engineer',
},
{
id: 'arlene-mccoy',
name: 'Arlene McCoy',
username: 'arlene',
email: 'arlene.mccoy@example.com',
title: 'Data Analyst',
},
{
id: 'marvin-mckinney',
name: 'Marvin McKinney',
username: 'marvin',
email: 'marvin.mckinney@example.com',
title: 'QA Specialist',
},
{
id: 'eleanor-pena',
name: 'Eleanor Pena',
username: 'eleanor',
email: 'eleanor.pena@example.com',
title: 'Operations',
},
{
id: 'jerome-bell',
name: 'Jerome Bell',
username: 'jerome',
email: 'jerome.bell@example.com',
title: 'DevOps Engineer',
},
];
const popupHiddenClass = 'scale-95 opacity-0';
</script>
<template>
<Combobox.Root
:items="items"
:item-to-string-label="(user: DirectoryUser) => user.name"
:is-item-equal-to-value="(item: DirectoryUser, value: DirectoryUser) => item.id === value.id"
multiple
:filter="null"
@update:open="handleOpenChange"
@value-change="handleValueChange"
@input-value-change="handleInputValueChange"
>
<div class="max-w-md flex flex-col gap-1">
<label
class="flex flex-col gap-1 text-sm leading-5 font-bold text-neutral-950 dark:text-white"
:for="id"
>Assign reviewers</label
>
<Combobox.InputGroup
class="flex min-h-8 w-64 cursor-text flex-wrap items-center gap-0.5 border border-neutral-950 bg-white dark:bg-neutral-950 px-2 py-1 focus-within:outline-2 focus-within:-outline-offset-1 focus-within:outline-neutral-950 dark:focus-within:outline-white has-[button]:px-1 dark:border-white min-[32rem]:w-[22rem]"
>
<Combobox.Value v-slot="{ value }">
<Combobox.Chips
class="flex w-full flex-wrap items-center gap-1"
:aria-label="value.length > 0 ? 'Selected reviewers' : undefined"
>
<Combobox.Chip
v-for="user in value"
:key="user.id"
class="group flex min-h-[calc(1.5rem-2px)] cursor-default items-center gap-1 overflow-hidden bg-neutral-100 py-0 pr-[0.2rem] pl-[0.4rem] text-sm leading-none text-neutral-950 outline-none focus-within:bg-neutral-950 focus-within:text-white [@media(hover:hover)]:data-highlighted:bg-neutral-950 [@media(hover:hover)]:data-highlighted:text-white dark:bg-neutral-800 dark:text-white dark:focus-within:bg-white dark:focus-within:text-neutral-950 dark:[@media(hover:hover)]:data-highlighted:bg-white dark:[@media(hover:hover)]:data-highlighted:text-neutral-950"
:aria-label="user.name"
aria-description="Press Backspace or Delete to remove"
>
{{ user.name }}
<Combobox.ChipRemove
class="flex size-4 items-center justify-center border-0 bg-transparent p-0 text-inherit hover:bg-neutral-200 group-focus-within:hover:bg-neutral-700 dark:hover:bg-neutral-700 dark:group-focus-within:hover:bg-neutral-200"
:aria-label="`Remove ${user.name}`"
>
<XIcon />
</Combobox.ChipRemove>
</Combobox.Chip>
<Combobox.Input
:id="id"
:placeholder="value.length > 0 ? '' : 'e.g. Michael'"
:aria-description="
value.length > 0
? `${value.length} selected. From the start of the input, press Left Arrow to focus the selected items`
: undefined
"
class="h-[calc(1.5rem-2px)] min-w-12 flex-1 border-0 bg-white p-0 text-sm any-pointer-coarse:text-base dark:bg-neutral-950 font-normal text-neutral-950 outline-none placeholder:text-neutral-500 dark:placeholder:text-neutral-400 dark:text-white"
/>
</Combobox.Chips>
</Combobox.Value>
</Combobox.InputGroup>
</div>
<Combobox.Portal>
<Combobox.Positioner class="outline-none" :side-offset="4">
<Transition :enter-from-class="popupHiddenClass" :leave-to-class="popupHiddenClass" appear>
<Combobox.Popup
class="w-[var(--anchor-width)] max-w-[var(--available-width)] origin-[var(--transform-origin)] border border-neutral-950 bg-white text-neutral-950 shadow-[0.25rem_0.25rem_0_rgb(0_0_0_/_12%)] transition-[scale,opacity] duration-100 dark:border-white dark:bg-neutral-950 dark:text-white dark:shadow-none"
:aria-busy="isPending || undefined"
>
<div
class="max-h-[min(var(--available-height),24.5rem)] overflow-y-auto overscroll-contain py-1 scroll-pt-1 scroll-pb-1"
>
<Combobox.Status>
<div
v-if="isPending || statusText"
class="flex items-center gap-2 py-1 pr-5 pl-2 text-sm leading-5 text-neutral-500 dark:text-neutral-400"
>
<template v-if="isPending">
<span
class="inline-block size-3 animate-[spin_0.75s_linear_infinite] rounded-full border border-current border-r-transparent"
aria-hidden="true"
/>
Searching…
</template>
<template v-else>{{ statusText }}</template>
</div>
</Combobox.Status>
<Combobox.Empty>
<div
v-if="emptyMessage"
class="py-2 pr-4 pl-2 text-sm leading-4 text-neutral-500 dark:text-neutral-400"
>
{{ emptyMessage }}
</div>
</Combobox.Empty>
<Combobox.List>
<template #item="{ item: user }">
<Combobox.Item
v-slot="{ state }"
class="grid cursor-default grid-cols-[1rem_1fr] items-start gap-2 px-2 py-2 text-sm leading-[1.2rem] outline-none select-none [@media(hover:hover)]:data-highlighted:relative [@media(hover:hover)]:data-highlighted:z-0 [@media(hover:hover)]:data-highlighted:text-neutral-950 [@media(hover:hover)]:data-highlighted:before:absolute [@media(hover:hover)]:data-highlighted:before:inset-0 [@media(hover:hover)]:data-highlighted:before:z-[-1] [@media(hover:hover)]:data-highlighted:before:bg-neutral-100 dark:[@media(hover:hover)]:data-highlighted:text-white dark:[@media(hover:hover)]:data-highlighted:before:bg-neutral-800"
:value="user"
>
<span v-if="state.selected" class="col-start-1 mt-1">
<CheckIcon />
</span>
<span class="col-start-2 flex flex-col gap-1">
<span class="text-sm leading-5 font-bold">{{ user.name }}</span>
<span class="text-xs">{{ user.email }}</span>
<span
class="flex flex-wrap gap-2 text-xs text-neutral-500 dark:text-neutral-400"
>
<span>@{{ user.username }}</span>
<span>{{ user.title }}</span>
</span>
</span>
</Combobox.Item>
</template>
</Combobox.List>
</div>
</Combobox.Popup>
</Transition>
</Combobox.Positioner>
</Combobox.Portal>
</Combobox.Root>
</template>Virtualized
Use a virtualization library, such as @tanstack/vue-virtual, to handle a large data set.
<script setup lang="ts">
import { useTemplateRef } from 'vue';
import { Combobox } from '@vase-ui/vue/combobox';
import styles from './index.module.css';
import VirtualizedList from './VirtualizedList.vue';
const list = useTemplateRef<InstanceType<typeof VirtualizedList>>('list');
function scrollToHighlightedItem(
item: VirtualizedItem | undefined,
{ reason, index }: Combobox.Root.HighlightEventDetails,
) {
const virtualizer = list.value?.virtualizer;
if (!item || !virtualizer) {
return;
}
const isStart = index === 0;
const isEnd = index === virtualizer.options.count - 1;
const shouldScroll = reason === 'none' || (reason === 'keyboard' && (isStart || isEnd));
if (shouldScroll) {
queueMicrotask(() => {
virtualizer.scrollToIndex(index, { align: isEnd ? 'start' : 'end' });
});
}
}
interface VirtualizedItem {
id: string;
name: string;
}
function getItemLabel(item: VirtualizedItem) {
return item.name;
}
const virtualizedItems: VirtualizedItem[] = Array.from({ length: 10000 }, (_, index) => {
const id = String(index + 1);
const indexLabel = id.padStart(4, '0');
return { id, name: `Item ${indexLabel}` };
});
</script>
<template>
<Combobox.Root
virtualized
:items="virtualizedItems"
:item-to-string-label="getItemLabel"
@item-highlighted="scrollToHighlightedItem"
>
<label :class="styles.Label">
Search 10,000 items
<Combobox.Input :class="styles.Input" />
</label>
<Combobox.Portal>
<Combobox.Positioner :class="styles.Positioner" :side-offset="4">
<Combobox.Popup :class="styles.Popup">
<Combobox.Empty>
<div :class="styles.Empty">No items found.</div>
</Combobox.Empty>
<Combobox.List :class="styles.List">
<VirtualizedList ref="list" />
</Combobox.List>
</Combobox.Popup>
</Combobox.Positioner>
</Combobox.Portal>
</Combobox.Root>
</template><script setup lang="ts">
import { computed, h, shallowRef } from 'vue';
import type { FunctionalComponent } from 'vue';
import { useVirtualizer } from '@tanstack/vue-virtual';
import { Combobox } from '@vase-ui/vue/combobox';
import styles from './index.module.css';
interface VirtualizedItem {
id: string;
name: string;
}
const filteredItems = Combobox.useFilteredItems<VirtualizedItem>();
const scrollElement = shallowRef<HTMLDivElement | null>(null);
const virtualizer = useVirtualizer(
computed(() => ({
count: filteredItems.value.length,
getScrollElement: () => scrollElement.value,
estimateSize: () => 32,
overscan: 20,
paddingStart: 4,
paddingEnd: 4,
scrollPaddingEnd: 4,
scrollPaddingStart: 4,
})),
);
const totalSize = computed(() => virtualizer.value.getTotalSize());
const rows = computed(() =>
virtualizer.value.getVirtualItems().flatMap((virtualItem) => {
const item = filteredItems.value[virtualItem.index];
return item ? [{ virtualItem, item }] : [];
}),
);
// Vue calls a function ref again on each patch, and `measure()` makes the next patch.
function setScrollElement(element: unknown) {
if (element === scrollElement.value) {
return;
}
scrollElement.value = element as HTMLDivElement | null;
if (element) {
virtualizer.value.measure();
}
}
// A part gives its element through the exposed `element`.
function measureItem(item: unknown) {
virtualizer.value.measureElement(
(item as { element: HTMLElement | null } | null)?.element ?? null,
);
}
const ICON_PROPS = {
width: '16',
height: '16',
viewBox: '0 0 16 16',
style: { display: 'block' },
};
const CheckIcon: FunctionalComponent = (_, { attrs }) =>
h('svg', { ...ICON_PROPS, fill: 'none', stroke: 'currentColor', ...attrs }, [
h('path', { d: 'm2.5 8.5 4 4 7-9' }),
]);
defineExpose({ virtualizer });
</script>
<template>
<div
v-if="filteredItems.length > 0"
:ref="setScrollElement"
role="presentation"
:class="styles.Scroller"
:style="{ '--total-size': `${totalSize}px` }"
>
<div
role="presentation"
:class="styles.VirtualizedPlaceholder"
:style="{ height: `${totalSize}px` }"
>
<Combobox.Item
v-slot="{ state }"
v-for="{ virtualItem, item } in rows"
:key="virtualItem.index"
:ref="measureItem"
:index="virtualItem.index"
:data-index="virtualItem.index"
:value="item"
:class="styles.Item"
:aria-setsize="filteredItems.length"
:aria-posinset="virtualItem.index + 1"
:style="{
position: 'absolute',
top: 0,
left: 0,
width: '100%',
height: `${virtualItem.size}px`,
transform: `translateY(${virtualItem.start}px)`,
}"
>
<span v-if="state.selected" :class="styles.ItemIndicator">
<CheckIcon />
</span>
<span :class="styles.ItemText">{{ item.name }}</span>
</Combobox.Item>
</div>
</div>
</template>.Input {
box-sizing: border-box;
padding: 0 0.5rem;
margin: 0;
border-radius: 0;
border: 1px solid oklch(14.5% 0 0deg);
width: 16rem;
height: 2rem;
font-family: inherit;
font-size: 0.875rem;
line-height: 1.25rem;
font-weight: 400;
background-color: white;
color: oklch(14.5% 0 0deg);
outline: none;
@media (any-pointer: coarse) {
font-size: 1rem;
line-height: 1.5rem;
}
@media (prefers-color-scheme: dark) {
border: 1px solid white;
background-color: oklch(14.5% 0 0deg);
color: white;
}
&:focus {
outline: 2px solid oklch(14.5% 0 0deg);
outline-offset: -1px;
@media (prefers-color-scheme: dark) {
outline-color: white;
}
}
}
.Label {
display: flex;
flex-direction: column;
gap: 0.25rem;
font-size: 0.875rem;
line-height: 1.25rem;
font-weight: 700;
color: oklch(14.5% 0 0deg);
@media (prefers-color-scheme: dark) {
color: white;
}
}
.Positioner {
outline: 0;
}
.Popup {
box-sizing: border-box;
background-color: white;
color: oklch(14.5% 0 0deg);
width: var(--anchor-width);
max-width: var(--available-width);
border: 1px solid oklch(14.5% 0 0deg);
box-shadow: 0.25rem 0.25rem 0 rgb(0 0 0 / 12%);
@media (prefers-color-scheme: dark) {
background-color: oklch(14.5% 0 0deg);
color: white;
border: 1px solid white;
box-shadow: none;
}
}
.Scroller {
box-sizing: border-box;
height: min(22.5rem, var(--total-size));
max-height: var(--available-height);
overflow: auto;
overscroll-behavior: contain;
scroll-padding-block: 0.25rem;
}
.VirtualizedPlaceholder {
width: 100%;
position: relative;
}
.List {
box-sizing: border-box;
padding: 0;
}
.Item {
box-sizing: border-box;
outline: 0;
cursor: default;
-webkit-user-select: none;
user-select: none;
padding-block: 0.5rem;
padding-left: 0.5rem;
padding-right: 0.5rem;
display: grid;
gap: 0.5rem;
align-items: center;
grid-template-columns: 1rem 1fr;
font-size: 0.875rem;
line-height: 1rem;
&[data-highlighted] {
z-index: 0;
position: relative;
color: white;
@media (prefers-color-scheme: dark) {
color: oklch(14.5% 0 0deg);
}
}
&[data-highlighted]::before {
content: '';
z-index: -1;
position: absolute;
inset-block: 0;
inset-inline: 0;
background-color: oklch(14.5% 0 0deg);
@media (prefers-color-scheme: dark) {
background-color: white;
}
}
}
.ItemText {
grid-column-start: 2;
}
.ItemIndicator {
grid-column-start: 1;
}
.Empty {
box-sizing: border-box;
font-size: 0.875rem;
line-height: 1rem;
color: oklch(55.6% 0 0deg);
padding: 0.75rem 0.5rem;
@media (prefers-color-scheme: dark) {
color: oklch(70.8% 0 0deg);
}
}<script setup lang="ts">
import { shallowRef, useTemplateRef } from 'vue';
import { Combobox } from '@vase-ui/vue/combobox';
import VirtualizedList from './VirtualizedList.vue';
const open = shallowRef(false);
const list = useTemplateRef<InstanceType<typeof VirtualizedList>>('list');
function scrollToHighlightedItem(
item: VirtualizedItem | undefined,
{ reason, index }: Combobox.Root.HighlightEventDetails,
) {
const virtualizer = list.value?.virtualizer;
if (!item || !virtualizer) {
return;
}
const isStart = index === 0;
const isEnd = index === virtualizer.options.count - 1;
const shouldScroll = reason === 'none' || (reason === 'keyboard' && (isStart || isEnd));
if (shouldScroll) {
queueMicrotask(() => {
virtualizer.scrollToIndex(index, { align: isEnd ? 'start' : 'end' });
});
}
}
interface VirtualizedItem {
id: string;
name: string;
}
function getItemLabel(item: VirtualizedItem) {
return item.name;
}
const virtualizedItems: VirtualizedItem[] = Array.from({ length: 10000 }, (_, index) => {
const id = String(index + 1);
const indexLabel = id.padStart(4, '0');
return { id, name: `Item ${indexLabel}` };
});
</script>
<template>
<Combobox.Root
virtualized
:items="virtualizedItems"
v-model:open="open"
:item-to-string-label="getItemLabel"
@item-highlighted="scrollToHighlightedItem"
>
<label class="flex flex-col gap-1 text-sm leading-5 font-bold text-neutral-950 dark:text-white">
Search 10,000 items
<Combobox.Input
class="h-8 w-64 border border-neutral-950 bg-white dark:bg-neutral-950 px-2 text-sm any-pointer-coarse:text-base font-normal text-neutral-950 focus:outline-2 focus:-outline-offset-1 focus:outline-neutral-950 dark:focus:outline-white dark:border-white dark:text-white"
/>
</label>
<Combobox.Portal>
<Combobox.Positioner class="outline-none" :side-offset="4">
<Combobox.Popup
class="w-[var(--anchor-width)] max-w-[var(--available-width)] border border-neutral-950 bg-white text-neutral-950 shadow-[0.25rem_0.25rem_0_rgb(0_0_0_/_12%)] dark:border-white dark:bg-neutral-950 dark:text-white dark:shadow-none"
>
<Combobox.Empty>
<div class="py-3 px-2 text-sm leading-4 text-neutral-500 dark:text-neutral-400">
No items found.
</div>
</Combobox.Empty>
<Combobox.List class="p-0">
<VirtualizedList ref="list" :open="open" />
</Combobox.List>
</Combobox.Popup>
</Combobox.Positioner>
</Combobox.Portal>
</Combobox.Root>
</template><script setup lang="ts">
import { computed, h, shallowRef } from 'vue';
import type { FunctionalComponent } from 'vue';
import { useVirtualizer } from '@tanstack/vue-virtual';
import { Combobox } from '@vase-ui/vue/combobox';
interface VirtualizedItem {
id: string;
name: string;
}
const props = defineProps<{ open: boolean }>();
const filteredItems = Combobox.useFilteredItems<VirtualizedItem>();
const scrollElement = shallowRef<HTMLDivElement | null>(null);
const virtualizer = useVirtualizer(
computed(() => ({
enabled: props.open,
count: filteredItems.value.length,
getScrollElement: () => scrollElement.value,
estimateSize: () => 32,
overscan: 20,
paddingStart: 4,
paddingEnd: 4,
scrollPaddingEnd: 4,
scrollPaddingStart: 4,
})),
);
const totalSize = computed(() => virtualizer.value.getTotalSize());
const rows = computed(() =>
virtualizer.value.getVirtualItems().flatMap((virtualItem) => {
const item = filteredItems.value[virtualItem.index];
return item ? [{ virtualItem, item }] : [];
}),
);
// Vue calls a function ref again on each patch, and `measure()` makes the next patch.
function setScrollElement(element: unknown) {
if (element === scrollElement.value) {
return;
}
scrollElement.value = element as HTMLDivElement | null;
if (element) {
virtualizer.value.measure();
}
}
// A part gives its element through the exposed `element`.
function measureItem(item: unknown) {
virtualizer.value.measureElement(
(item as { element: HTMLElement | null } | null)?.element ?? null,
);
}
const ICON_PROPS = {
width: '16',
height: '16',
viewBox: '0 0 16 16',
style: { display: 'block' },
};
const CheckIcon: FunctionalComponent = (_, { attrs }) =>
h('svg', { ...ICON_PROPS, fill: 'none', stroke: 'currentColor', ...attrs }, [
h('path', { d: 'm2.5 8.5 4 4 7-9' }),
]);
defineExpose({ virtualizer });
</script>
<template>
<div
v-if="filteredItems.length > 0"
:ref="setScrollElement"
role="presentation"
class="h-[min(22.5rem,var(--total-size))] max-h-[var(--available-height)] overflow-auto overscroll-contain scroll-py-1"
:style="{ '--total-size': `${totalSize}px` }"
>
<div role="presentation" class="relative w-full" :style="{ height: `${totalSize}px` }">
<Combobox.Item
v-slot="{ state }"
v-for="{ virtualItem, item } in rows"
:key="virtualItem.index"
:ref="measureItem"
:index="virtualItem.index"
:data-index="virtualItem.index"
:value="item"
class="grid cursor-default grid-cols-[1rem_1fr] items-center gap-2 p-2 text-sm leading-4 outline-none select-none data-highlighted:relative data-highlighted:z-0 data-highlighted:text-white data-highlighted:before:absolute data-highlighted:before:inset-0 data-highlighted:before:z-[-1] data-highlighted:before:bg-neutral-950 dark:data-highlighted:text-neutral-950 dark:data-highlighted:before:bg-white"
:aria-setsize="filteredItems.length"
:aria-posinset="virtualItem.index + 1"
:style="{
position: 'absolute',
top: 0,
left: 0,
width: '100%',
height: `${virtualItem.size}px`,
transform: `translateY(${virtualItem.start}px)`,
}"
>
<span v-if="state.selected" class="col-start-1">
<CheckIcon />
</span>
<span class="col-start-2">{{ item.name }}</span>
</Combobox.Item>
</div>
</div>
</template>Memoizing items
A child component that takes the item as a prop is a simpler alternative to virtualization for a short list. Vue renders a child component again only when its props, its slots or the reactive values of its render change. A typed character then renders only the items that change. The open is not faster, because the popup mounts each item. For a long list, use virtualization.
<script lang="ts">
export interface Fruit {
id: string;
label: string;
}
</script>
<script setup lang="ts">
import { Combobox } from '@vase-ui/vue/combobox';
defineProps<{ item: Fruit }>();
</script>
<template>
<Combobox.Item v-slot="{ state }" :value="item">
<span v-if="state.selected">✓</span>
<span>{{ item.label }}</span>
</Combobox.Item>
</template><script setup lang="ts">
import { Combobox } from '@vase-ui/vue/combobox';
import FruitItem from './FruitItem.vue';
import type { Fruit } from './FruitItem.vue';
const fruits: Fruit[] = [
{ id: 'apple', label: 'Apple' },
{ id: 'banana', label: 'Banana' },
];
</script>
<template>
<Combobox.Root :items="fruits">
<Combobox.Input />
<Combobox.Portal>
<Combobox.Positioner>
<Combobox.Popup>
<Combobox.List>
<template #item="{ item }">
<FruitItem :item="item" />
</template>
</Combobox.List>
</Combobox.Popup>
</Combobox.Positioner>
</Combobox.Portal>
</Combobox.Root>
</template>API reference
Combobox.Root
Groups the parts of the combobox, and holds the inputs of its form.
Renders a <div> element.
Props
| Prop | Type | Default | Description |
|---|---|---|---|
autocomplete | string | undefined | The autofill purpose of the hidden text input, such as 'country-name'. The input has no
name, so a browser reads its purpose from this attribute. Without multiple, an autofill selects
the item whose value or label is the filled text. The labels come from items. With no items,
they come from the Combobox.Item parts, and the root keeps the popup in the DOM from the first
fill. | |
autoHighlight | boolean | undefined | false | The first item gets the highlight after each typed text that is not empty. |
defaultInputValue | string | undefined | The text at the mount and at a native reset of the form, when the text is uncontrolled. With neither, the text of a single combobox is the label of its value. | |
defaultOpen | boolean | undefined | false | The popup is open at the mount of an uncontrolled root. |
defaultValue | ComboboxValue<Value, Multiple> | null | undefined | The value of an uncontrolled root, at the mount and at a native reset of the form. | |
disabled | boolean | undefined | false | The user cannot change the value, and the form gets no value. |
filter | ((item: Item, query: string, itemToString?: FilterItemToString | undefined) => boolean) | null | undefined | Keeps an item for the query, the text with no space at the ends. null keeps each item. The
default is contains of useFilter. | |
filteredItems | readonly Item[] | readonly Group<Item>[] | undefined | The items to show, in place of the result of filter. Keep the form of items. | |
form | string | undefined | The id of the form of the value. | |
grid | boolean | undefined | false | Arrow keys move in the rows and columns of Row parts. |
highlightItemOnHover | boolean | undefined | true | A move of the pointer highlights its item. |
inline | boolean | undefined | false | The list is in place, with no popup. The input is the control and has aria-expanded. |
inputValue | string | undefined | The text of the input. v-model:input-value binds it. | |
isItemEqualToValue | ((itemValue: Value, value: Value) => boolean) | undefined | Compares the value of an item with a selected value. The default is Object.is. | |
items | ComboboxItems<Item, any> | undefined | The data of the items. With items, the root filters the data, and the item slot of
List renders each item that the filter keeps. | |
itemToStringLabel | ((itemValue: Value) => string) | undefined | The label of a value. An object with label gives its label. | |
itemToStringValue | ((itemValue: Value) => string) | undefined | The text of a value in the form data. An object with value and label gives its value. | |
limit | number | undefined | -1 | The largest number of items to show. -1 shows each item. |
locale | Intl.LocalesArgument | The locale of the default filter. Else the nearest LocaleProvider, else 'en-US'. | |
loopFocus | boolean | undefined | true | The arrow keys go from the last item to the input and to the first item. |
modal | boolean | undefined | false | The open popup locks the scroll of the page and blocks the pointer outside it. |
modelValue | ComboboxValue<Value, Multiple> | null | undefined | The selected value. v-model binds it. With multiple, null is no value. | |
multiple | Multiple | undefined | false | The user selects more than one value. The form data then has one entry for each selected value. |
name | string | undefined | The name of the value in the form data. | |
open | boolean | undefined | The popup is open. v-model:open binds it. | |
openOnInputClick | boolean | undefined | true | A press on the input opens the popup. |
readonly | boolean | undefined | false | The user can browse the items, and cannot change the value. |
required | boolean | undefined | false | The form needs a value. |
virtualized | boolean | undefined | false | The developer renders a window of the items. The arrow keys count on the filtered items, and
the list sets no scroll position. In a grid, the mounted Row with the most items gives the
number of columns. |
as | keyof HTMLElementTagNameMap | Component | GenericComponent | undefined | A tag or a component that the part renders in place of its own element, with the same
attributes and content. The element slot wins over it. |
Slots
| Slot | Slot props | Description |
|---|---|---|
default | The content of the part. |
Events
| Event | Arguments | Description |
|---|---|---|
valueChange | [value: Multiple extends true ? Value[] : Value | null, details: ComboboxRootChangeEventDetails] | The user changes the value. details.cancel() keeps the value as it was. An action that gives
the value that the root has sends no event, such as a pick of the selected item without
multiple. |
update:modelValue | [value: Multiple extends true ? Value[] : Value | null] | Comes after valueChange, unless a listener cancels the change. v-model uses it. |
inputValueChange | [text: string, details: ComboboxRootChangeEventDetails] | The text of the input changes. details.cancel() keeps the text as it was. An action that gives
the text that the input has sends no event. |
update:inputValue | [text: string] | Comes after inputValueChange, unless a listener cancels it. v-model:input-value uses it. |
openChange | [open: boolean, details: ComboboxRootOpenChangeEventDetails] | The popup opens or closes. details.cancel() keeps it as it was. |
update:open | [open: boolean] | Comes after openChange, unless a listener cancels the change. v-model:open uses it. |
itemHighlighted | [value: Value | undefined, details: ComboboxRootHighlightEventDetails] | An item gets the highlight, or no item has it (undefined, with the index -1). |
Exposed
| Member | Type | Description |
|---|---|---|
close | () => void | Closes the popup with the reason 'imperative-action'. |
element | HTMLElement | null | The element of the part, or null while it is not mounted. |
inputElement | HTMLInputElement | null | The visually hidden text input of the form, while the root renders one. |
Combobox.Label
Names the control of the combobox.
Renders a <div> element.
Props
| Prop | Type | Default | Description |
|---|---|---|---|
id | string | undefined | The id of the label. The default is a generated id. | |
as | keyof HTMLElementTagNameMap | Component | GenericComponent | undefined | A tag or a component that the part renders in place of its own element, with the same
attributes and content. The element slot wins over it. |
Slots
| Slot | Slot props | Description |
|---|---|---|
default | state: ComboboxLabelState | The content of the part. |
element | props: Record<string, unknown>elementRef: (target: unknown) => voidstate: ComboboxLabelState | Renders your element in place of the element of the part. Bind props with v-bind and elementRef with :ref. |
Exposed
| Member | Type | Description |
|---|---|---|
element | HTMLElement | null | The element of the part, or null while it is not mounted. |
Selectors
| Selector | Description |
|---|---|
[data-disabled] | The combobox is disabled. |
[data-valid] | In a Field.Root, the value is valid. |
[data-invalid] | In a Field.Root, the value is invalid. |
[data-touched] | In a Field.Root, the focus left the control one time or more. |
[data-dirty] | In a Field.Root, the value differs from the first value. |
[data-filled] | In a Field.Root, the combobox has a value. |
Combobox.Value
The label of the value. Renders no element.
Props
| Prop | Type | Default | Description |
|---|---|---|---|
placeholder | string | (() => VNodeChild) | undefined | The text with no value, or a function that gives nodes. |
Slots
| Slot | Slot props | Description |
|---|---|---|
default | value: any | Formats the value. With multiple, the value is a list that the part can share: read it only. |
Combobox.Icon
An icon that shows that the popup opens.
Renders a <span> element.
Props
| Prop | Type | Default | Description |
|---|---|---|---|
as | keyof HTMLElementTagNameMap | Component | GenericComponent | undefined | A tag or a component that the part renders in place of its own element, with the same
attributes and content. The element slot wins over it. |
Slots
| Slot | Slot props | Description |
|---|---|---|
default | state: ComboboxIconState | The content of the part. |
element | props: Record<string, unknown>elementRef: (target: unknown) => voidstate: ComboboxIconState | Renders your element in place of the element of the part. Bind props with v-bind and elementRef with :ref. |
Exposed
| Member | Type | Description |
|---|---|---|
element | HTMLElement | null | The element of the part, or null while it is not mounted. |
Combobox.Input
The text input that filters the items.
Renders an <input> element.
Props
| Prop | Type | Default | Description |
|---|---|---|---|
disabled | boolean | undefined | false | The user cannot use the input. |
id | string | undefined | The id of the input. The default is the control id of the field, else a generated id. In the
popup, the default is a generated id. |
Slots
| Slot | Slot props | Description |
|---|---|---|
element | props: Record<string, unknown>elementRef: (target: unknown) => voidstate: ComboboxInputState | Renders your element in place of the element of the part. Bind props with v-bind and elementRef with :ref. |
Exposed
| Member | Type | Description |
|---|---|---|
element | TextElement | null | The element of the part, or null while it is not mounted. |
Selectors
| Selector | Description |
|---|---|
[aria-expanded="true"] | The popup is open, the list is inline, or the input is in the popup. |
[data-popup-side] | The side of the anchor that the open popup is on. |
[data-list-empty] | The list has no item to show. |
:disabled | The input or the combobox is disabled. |
:read-only | The combobox is read-only. |
[aria-required="true"] | The combobox is required, and the input is the control. |
[aria-invalid="true"] | In a Field.Root, the input is the control, and the value is invalid. |
[data-valid] | In a Field.Root, the input is the control, and the value is valid. |
[data-touched] | In a Field.Root, the input is the control, and the focus left it one time or more. |
[data-dirty] | In a Field.Root, the input is the control, and the value differs from the first value. |
[data-filled] | In a Field.Root, the input is the control, and the combobox has a value. |
Combobox.InputGroup
Groups the input and its buttons.
Renders a <div> element.
Props
| Prop | Type | Default | Description |
|---|---|---|---|
as | keyof HTMLElementTagNameMap | Component | GenericComponent | undefined | A tag or a component that the part renders in place of its own element, with the same
attributes and content. The element slot wins over it. |
Slots
| Slot | Slot props | Description |
|---|---|---|
default | state: ComboboxInputGroupState | The content of the part. |
element | props: Record<string, unknown>elementRef: (target: unknown) => voidstate: ComboboxInputGroupState | Renders your element in place of the element of the part. Bind props with v-bind and elementRef with :ref. |
Exposed
| Member | Type | Description |
|---|---|---|
element | HTMLElement | null | The element of the part, or null while it is not mounted. |
Selectors
| Selector | Description |
|---|---|
[data-popup-open] | The popup is open. |
[data-popup-side] | The side of the anchor that the open popup is on. |
[data-list-empty] | The list has no item to show. |
[data-readonly] | The combobox is read-only. |
[data-placeholder] | The combobox has no value. |
[data-disabled] | The combobox is disabled. |
[data-valid] | In a Field.Root, the value is valid. |
[data-invalid] | In a Field.Root, the value is invalid. |
[data-touched] | In a Field.Root, the focus left the control one time or more. |
[data-dirty] | In a Field.Root, the value differs from the first value. |
[data-filled] | In a Field.Root, the combobox has a value. |
Combobox.Clear
A button that clears the value and the text.
Renders a <button> element.
Without keepMounted, it is in the DOM only while the combobox has a value.
Props
| Prop | Type | Default | Description |
|---|---|---|---|
disabled | boolean | undefined | false | The user cannot press the button. |
keepMounted | boolean | undefined | false | The button stays in the DOM with hidden while there is nothing to clear. |
as | keyof HTMLElementTagNameMap | Component | GenericComponent | undefined | A tag or a component that the part renders in place of its own element, with the same
attributes and content. The element slot wins over it. |
Slots
| Slot | Slot props | Description |
|---|---|---|
default | state: ComboboxClearState | The content of the part. |
element | props: Record<string, unknown>elementRef: (target: unknown) => voidstate: ComboboxClearState | Renders your element in place of the element of the part. Bind props with v-bind and elementRef with :ref. |
Exposed
| Member | Type | Description |
|---|---|---|
element | HTMLElement | null | The element of the part, or null while it is not mounted. |
Selectors
| Selector | Description |
|---|---|
[data-popup-open] | The popup is open. |
[hidden] | There is nothing to clear, and keepMounted keeps the button in the DOM. |
:disabled | The element is a native button, and the button, the combobox or a fieldset around it is disabled. |
[aria-disabled="true"] | The element is not a native button, and the button or the combobox is disabled. |
Combobox.Trigger
A button that opens the popup.
Renders a <button> element.
When the trigger is the control, a key on the closed trigger of a single combobox selects the
next item whose label starts with the typed text. The labels come from items, else from the
mounted items, or from the items that were mounted at the last close.
Props
| Prop | Type | Default | Description |
|---|---|---|---|
disabled | boolean | undefined | false | The user cannot press the trigger. |
id | string | undefined | The id of the trigger. When the trigger is the control, the default is the control id of the
field, else a generated id. Beside an input, the default is a generated id. | |
as | keyof HTMLElementTagNameMap | Component | GenericComponent | undefined | A tag or a component that the part renders in place of its own element, with the same
attributes and content. The element slot wins over it. |
Slots
| Slot | Slot props | Description |
|---|---|---|
default | state: ComboboxTriggerState | The content of the part. |
element | props: Record<string, unknown>elementRef: (target: unknown) => voidstate: ComboboxTriggerState | Renders your element in place of the element of the part. Bind props with v-bind and elementRef with :ref. |
Exposed
| Member | Type | Description |
|---|---|---|
element | HTMLElement | null | The element of the part, or null while it is not mounted. |
Selectors
| Selector | Description |
|---|---|
[aria-expanded="true"] | The popup is open. |
[data-popup-side] | The side of the anchor that the open popup is on. |
[data-list-empty] | The list has no item to show. |
[data-readonly] | The combobox is read-only. |
[data-required] | The combobox is required. |
[data-placeholder] | The combobox has no value. |
:disabled | The trigger is a native button, and the trigger, the combobox or a fieldset around the trigger is disabled. |
[aria-disabled="true"] | The trigger is another element, and the trigger or the combobox is disabled. |
[aria-invalid="true"] | In a Field.Root, the trigger is the control, and the value is invalid. |
[data-invalid] | In a Field.Root, the trigger is beside the input, and the value is invalid. |
[data-valid] | In a Field.Root, the value is valid. |
[data-touched] | In a Field.Root, the focus left the control one time or more. |
[data-dirty] | In a Field.Root, the value differs from the first value. |
[data-filled] | In a Field.Root, the combobox has a value. |
Combobox.Chips
The container of the chips of a multiple combobox.
Renders a <div> element.
Props
| Prop | Type | Default | Description |
|---|---|---|---|
as | keyof HTMLElementTagNameMap | Component | GenericComponent | undefined | A tag or a component that the part renders in place of its own element, with the same
attributes and content. The element slot wins over it. |
Slots
| Slot | Slot props | Description |
|---|---|---|
default | state: ComboboxChipsState | The content of the part. |
element | props: Record<string, unknown>elementRef: (target: unknown) => voidstate: ComboboxChipsState | Renders your element in place of the element of the part. Bind props with v-bind and elementRef with :ref. |
Exposed
| Member | Type | Description |
|---|---|---|
element | HTMLElement | null | The element of the part, or null while it is not mounted. |
Combobox.Chip
A selected value of a multiple combobox.
Renders a <div> element.
Props
| Prop | Type | Default | Description |
|---|---|---|---|
as | keyof HTMLElementTagNameMap | Component | GenericComponent | undefined | A tag or a component that the part renders in place of its own element, with the same
attributes and content. The element slot wins over it. |
Slots
| Slot | Slot props | Description |
|---|---|---|
default | state: ComboboxChipState | The content of the part. |
element | props: Record<string, unknown>elementRef: (target: unknown) => voidstate: ComboboxChipState | Renders your element in place of the element of the part. Bind props with v-bind and elementRef with :ref. |
Exposed
| Member | Type | Description |
|---|---|---|
element | HTMLElement | null | The element of the part, or null while it is not mounted. |
Selectors
| Selector | Description |
|---|---|
[data-disabled] | The combobox is disabled. |
[data-readonly] | The combobox is read-only. |
Combobox.ChipRemove
A button that removes the value of its chip.
Renders a <button> element.
Props
| Prop | Type | Default | Description |
|---|---|---|---|
disabled | boolean | undefined | false | The user cannot press the button. |
as | keyof HTMLElementTagNameMap | Component | GenericComponent | undefined | A tag or a component that the part renders in place of its own element, with the same
attributes and content. The element slot wins over it. |
Slots
| Slot | Slot props | Description |
|---|---|---|
default | state: ComboboxChipRemoveState | The content of the part. |
element | props: Record<string, unknown>elementRef: (target: unknown) => voidstate: ComboboxChipRemoveState | Renders your element in place of the element of the part. Bind props with v-bind and elementRef with :ref. |
Exposed
| Member | Type | Description |
|---|---|---|
element | HTMLElement | null | The element of the part, or null while it is not mounted. |
Selectors
| Selector | Description |
|---|---|
:disabled | The element is a native button, and the button, the combobox or a fieldset around it is disabled. |
[aria-disabled="true"] | The element is not a native button, and the button or the combobox is disabled. |
Combobox.List
The list of the items.
Renders a <div> element.
Props
| Prop | Type | Default | Description |
|---|---|---|---|
id | string | undefined | The id of the list. The default is a generated id. | |
as | keyof HTMLElementTagNameMap | Component | GenericComponent | undefined | A tag or a component that the part renders in place of its own element, with the same
attributes and content. The element slot wins over it. |
Slots
| Slot | Slot props | Description |
|---|---|---|
default | state: ComboboxListState | The content of the part. |
item | item: anyindex: number | Renders each item that the filter keeps. |
element | props: Record<string, unknown>elementRef: (target: unknown) => voidstate: ComboboxListState | Renders your element in place of the element of the part. Bind props with v-bind and elementRef with :ref. |
Exposed
| Member | Type | Description |
|---|---|---|
element | HTMLElement | null | The element of the part, or null while it is not mounted. |
Selectors
| Selector | Description |
|---|---|
[data-empty] | The list has no item to show. |
Combobox.Portal
Moves its content to another place of the DOM, <body> by default.
Renders a visually hidden <span> in place while the moved popup is open. Its aria-owns names
the popup, so a screen reader reads the popup after the input or the trigger.
With keepMounted, the closed popup keeps its list and the text of an input in it until the next
open. A root with no items keeps the popup in the DOM from the first fill of the browser.
Props
| Prop | Type | Default | Description |
|---|---|---|---|
defer | boolean | undefined | false | Moves the content after the other content of the same update mounted. |
disabled | boolean | undefined | false | Renders the content in place, also on the server. |
keepMounted | boolean | undefined | false | The closed popup stays in the DOM, with hidden and inert. |
to | PortalTarget | undefined | The target of the content. With no value, the target of the nearest portal above, else
body. While it is null, the portal renders nothing. |
Slots
| Slot | Slot props | Description |
|---|---|---|
default | The content of the part. |
Combobox.Backdrop
An overlay under the popup.
Renders a <div> element.
Props
| Prop | Type | Default | Description |
|---|---|---|---|
as | keyof HTMLElementTagNameMap | Component | GenericComponent | undefined | A tag or a component that the part renders in place of its own element, with the same
attributes and content. The element slot wins over it. |
Slots
| Slot | Slot props | Description |
|---|---|---|
default | state: ComboboxBackdropState | The content of the part. |
element | props: Record<string, unknown>elementRef: (target: unknown) => voidstate: ComboboxBackdropState | Renders your element in place of the element of the part. Bind props with v-bind and elementRef with :ref. |
Exposed
| Member | Type | Description |
|---|---|---|
element | HTMLElement | null | The element of the part, or null while it is not mounted. |
Selectors
| Selector | Description |
|---|---|
[hidden] | The combobox is closed, and keepMounted of the portal or a fill of the browser keeps the backdrop in the DOM. |
Combobox.Positioner
Places the popup at its anchor.
Renders a <div> element.
Props
| Prop | Type | Default | Description |
|---|---|---|---|
align | Align | undefined | 'center' | The alignment of the popup on the side. |
alignOffset | number | OffsetFunction | undefined | 0 | The offset on the align axis in pixels, or a function that gives it. |
anchor | Anchor | (() => Anchor) | The element to place the popup against: an element, a virtual element, a template ref of a part, or a function that gives one. With no value, the active trigger. | |
arrowPadding | number | undefined | 5 | The smallest space between the arrow and an inner edge of its nearest positioned ancestor, in pixels. |
collisionAvoidance | CollisionAvoidance | undefined | How the popup avoids the edge of the boundary. | |
collisionBoundary | Boundary | undefined | 'clipping-ancestors' | The area that holds the popup: an element, elements, or a rectangle. |
collisionPadding | Padding | undefined | 5 | The space between the popup and the edge of the boundary, in pixels. |
disableAnchorTracking | boolean | undefined | false | The popup does not follow a move of its anchor. |
positionMethod | "absolute" | "fixed" | undefined | 'absolute' | The CSS position of the positioner. |
side | Side | undefined | 'bottom' | The side of the anchor for the popup. It can change to avoid a collision. inline-start and
inline-end follow the CSS direction of the positioner: give the positioner dir when the
target of its portal has another direction. |
sideOffset | number | OffsetFunction | undefined | 0 | The distance from the anchor in pixels, or a function that gives it. |
sticky | boolean | undefined | false | The popup stays in the view after its anchor scrolls out of it. |
as | keyof HTMLElementTagNameMap | Component | GenericComponent | undefined | A tag or a component that the part renders in place of its own element, with the same
attributes and content. The element slot wins over it. |
Slots
| Slot | Slot props | Description |
|---|---|---|
default | state: ComboboxPositionerState | The content of the part. |
element | props: Record<string, unknown>elementRef: (target: unknown) => voidstate: ComboboxPositionerState | Renders your element in place of the element of the part. Bind props with v-bind and elementRef with :ref. |
Exposed
| Member | Type | Description |
|---|---|---|
element | HTMLElement | null | The element of the part, or null while it is not mounted. |
Selectors
| Selector | Description |
|---|---|
[data-side] | The side of the anchor that the popup is on: top, bottom, left, right, inline-start or inline-end. |
[data-align] | The alignment of the popup on its side: start, center or end. |
[data-anchor-hidden] | The anchor is out of view. |
[data-empty] | The list has no item to show. |
CSS variables
| Variable | Description |
|---|---|
--anchor-width | The width of the anchor, in pixels. |
--anchor-height | The height of the anchor, in pixels. |
--available-width | The width that the popup can fill before it overflows the boundary, in pixels. |
--available-height | The height that the popup can fill before it overflows the boundary, in pixels. |
--transform-origin | The point that the popup grows from, for the transform-origin of the popup. It is at the arrow, on the edge of the anchor. With no arrow, it is at the aligned edge of the popup or at the center of the anchor. |
Combobox.Popup
The container of the list.
Renders a <div> element.
Props
| Prop | Type | Default | Description |
|---|---|---|---|
finalFocus | FocusTarget | undefined | The element that gets the focus at the close. By default: the trigger that is the control, else the element that had the focus before the open. After an open by code, that element comes before the trigger. An input that is the control keeps the focus. | |
id | string | undefined | The id of the popup. The default is a generated id. | |
initialFocus | FocusTarget | undefined | The element that gets the focus at the open, while the trigger is the control. By default: the input in the popup; after a touch, the popup. | |
as | keyof HTMLElementTagNameMap | Component | GenericComponent | undefined | A tag or a component that the part renders in place of its own element, with the same
attributes and content. The element slot wins over it. |
Slots
| Slot | Slot props | Description |
|---|---|---|
default | state: ComboboxPopupState | The content of the part. |
element | props: Record<string, unknown>elementRef: (target: unknown) => voidstate: ComboboxPopupState | Renders your element in place of the element of the part. Bind props with v-bind and elementRef with :ref. |
Exposed
| Member | Type | Description |
|---|---|---|
element | HTMLElement | null | The element of the part, or null while it is not mounted. |
Selectors
| Selector | Description |
|---|---|
[data-side] | The side of the anchor that the popup is on: top, bottom, left, right, inline-start or inline-end. |
[data-align] | The alignment of the popup on its side: start, center or end. |
[data-anchor-hidden] | The anchor is out of view. |
[data-empty] | The list has no item to show. |
[hidden] | The combobox is closed, and keepMounted of the portal or a fill of the browser keeps the popup in the DOM. |
Combobox.Arrow
An element that points to the center of the anchor.
Renders a <div> element.
Its place is in the padding box of its nearest positioned ancestor: the popup when the popup has a position, else the positioner.
Props
| Prop | Type | Default | Description |
|---|---|---|---|
as | keyof HTMLElementTagNameMap | Component | GenericComponent | undefined | A tag or a component that the part renders in place of its own element, with the same
attributes and content. The element slot wins over it. |
Slots
| Slot | Slot props | Description |
|---|---|---|
default | state: ComboboxArrowState | The content of the part. |
element | props: Record<string, unknown>elementRef: (target: unknown) => voidstate: ComboboxArrowState | Renders your element in place of the element of the part. Bind props with v-bind and elementRef with :ref. |
Exposed
| Member | Type | Description |
|---|---|---|
element | HTMLElement | null | The element of the part, or null while it is not mounted. |
Selectors
| Selector | Description |
|---|---|
[data-side] | The side of the anchor that the popup is on. |
[data-align] | The alignment of the popup on its side: start, center or end. |
[data-uncentered] | The arrow cannot point to the center of the anchor. |
Combobox.Status
Tells a screen reader the status of the list, such as a load.
Renders a <div> element.
Props
| Prop | Type | Default | Description |
|---|---|---|---|
as | keyof HTMLElementTagNameMap | Component | GenericComponent | undefined | A tag or a component that the part renders in place of its own element, with the same
attributes and content. The element slot wins over it. |
Slots
| Slot | Slot props | Description |
|---|---|---|
default | state: ComboboxStatusState | The content of the part. |
element | props: Record<string, unknown>elementRef: (target: unknown) => voidstate: ComboboxStatusState | Renders your element in place of the element of the part. Bind props with v-bind and elementRef with :ref. |
Exposed
| Member | Type | Description |
|---|---|---|
element | HTMLElement | null | The element of the part, or null while it is not mounted. |
Combobox.Empty
The text of an empty list.
Renders a <div> element.
Props
| Prop | Type | Default | Description |
|---|---|---|---|
as | keyof HTMLElementTagNameMap | Component | GenericComponent | undefined | A tag or a component that the part renders in place of its own element, with the same
attributes and content. The element slot wins over it. |
Slots
| Slot | Slot props | Description |
|---|---|---|
default | state: ComboboxEmptyState | The content of the part. |
element | props: Record<string, unknown>elementRef: (target: unknown) => voidstate: ComboboxEmptyState | Renders your element in place of the element of the part. Bind props with v-bind and elementRef with :ref. |
Exposed
| Member | Type | Description |
|---|---|---|
element | HTMLElement | null | The element of the part, or null while it is not mounted. |
Combobox.Row
A row of items in a grid.
Renders a <div> element.
Props
| Prop | Type | Default | Description |
|---|---|---|---|
as | keyof HTMLElementTagNameMap | Component | GenericComponent | undefined | A tag or a component that the part renders in place of its own element, with the same
attributes and content. The element slot wins over it. |
Slots
| Slot | Slot props | Description |
|---|---|---|
default | state: ComboboxRowState | The content of the part. |
element | props: Record<string, unknown>elementRef: (target: unknown) => voidstate: ComboboxRowState | Renders your element in place of the element of the part. Bind props with v-bind and elementRef with :ref. |
Exposed
| Member | Type | Description |
|---|---|---|
element | HTMLElement | null | The element of the part, or null while it is not mounted. |
Combobox.Item
An item of the list.
Renders a <div> element.
Props
| Prop | Type | Default | Description |
|---|---|---|---|
disabled | boolean | undefined | false | The user cannot pick the item. The arrow keys still reach it. |
id | string | undefined | The id of the item. The default is a generated id. | |
index | number | undefined | The place of the item in the filtered items, for a list that renders a window of them. | |
value | any | null | The value of a pick. |
as | keyof HTMLElementTagNameMap | Component | GenericComponent | undefined | A tag or a component that the part renders in place of its own element, with the same
attributes and content. The element slot wins over it. |
Slots
| Slot | Slot props | Description |
|---|---|---|
default | state: ComboboxItemState | The content of the part. |
element | props: Record<string, unknown>elementRef: (target: unknown) => voidstate: ComboboxItemState | Renders your element in place of the element of the part. Bind props with v-bind and elementRef with :ref. |
Exposed
| Member | Type | Description |
|---|---|---|
element | HTMLElement | null | The element of the part, or null while it is not mounted. |
Selectors
| Selector | Description |
|---|---|
[data-highlighted] | The item has the highlight. |
[aria-selected="true"] | The item is selected. |
[aria-disabled="true"] | The item or the combobox is disabled. |
Combobox.Group
Groups related items.
Renders a <div> element.
Props
| Prop | Type | Default | Description |
|---|---|---|---|
as | keyof HTMLElementTagNameMap | Component | GenericComponent | undefined | A tag or a component that the part renders in place of its own element, with the same
attributes and content. The element slot wins over it. |
Slots
| Slot | Slot props | Description |
|---|---|---|
default | state: ComboboxGroupState | The content of the part. |
element | props: Record<string, unknown>elementRef: (target: unknown) => voidstate: ComboboxGroupState | Renders your element in place of the element of the part. Bind props with v-bind and elementRef with :ref. |
Exposed
| Member | Type | Description |
|---|---|---|
element | HTMLElement | null | The element of the part, or null while it is not mounted. |
Combobox.GroupLabel
Names a group.
Renders a <div> element.
Props
| Prop | Type | Default | Description |
|---|---|---|---|
id | string | undefined | The id of the label, which names its group. The default is a generated id. | |
as | keyof HTMLElementTagNameMap | Component | GenericComponent | undefined | A tag or a component that the part renders in place of its own element, with the same
attributes and content. The element slot wins over it. |
Slots
| Slot | Slot props | Description |
|---|---|---|
default | state: ComboboxGroupLabelState | The content of the part. |
element | props: Record<string, unknown>elementRef: (target: unknown) => voidstate: ComboboxGroupLabelState | Renders your element in place of the element of the part. Bind props with v-bind and elementRef with :ref. |
Exposed
| Member | Type | Description |
|---|---|---|
element | HTMLElement | null | The element of the part, or null while it is not mounted. |
Combobox.Separator
Separates groups of items.
Renders a <div> element.
Props
| Prop | Type | Default | Description |
|---|---|---|---|
orientation | Orientation | undefined | 'horizontal' | The orientation of the separator. |
as | keyof HTMLElementTagNameMap | Component | GenericComponent | undefined | A tag or a component that the part renders in place of its own element, with the same
attributes and content. The element slot wins over it. |
Slots
| Slot | Slot props | Description |
|---|---|---|
default | state: ComboboxSeparatorState | The content of the part. |
element | props: Record<string, unknown>elementRef: (target: unknown) => voidstate: ComboboxSeparatorState | Renders your element in place of the element of the part. Bind props with v-bind and elementRef with :ref. |
Exposed
| Member | Type | Description |
|---|---|---|
element | HTMLElement | null | The element of the part, or null while it is not mounted. |
Selectors
| Selector | Description |
|---|---|
[data-orientation] | The orientation of the separator: horizontal or vertical. |
useFilter
Returns a filter that matches items with a query through Intl.Collator, for a list that you filter yourself.
Parameters
| Parameter | Type | Description |
|---|---|---|
options? | MaybeRefOrGetter<ComboboxFilterOptions> |
Return value
Filter
useFilteredItems
Returns the items that the filter of Combobox.Root keeps, for a component inside the root.
Return value
ComputedRef<T[]>
createItems
Makes a collection for the items prop of Combobox.Root, with the selection value and the label of each item.
Parameters
| Parameter | Type | Description |
|---|---|---|
data | (ComboboxItemsData<Item> & RejectGroupShapedItems<Item>) | undefined | |
options | CreateComboboxItemsOptions<Item, Value> |
Return value
ComboboxItemCollection<Item, Value>
Differences from Base UI
Vase UI ports Combobox from Base UI 1.9.0.
API
| Base UI | Vase UI |
|---|---|
Combobox.Root | The root renders a <div> that holds the inputs of its form, so it takes as. @after-enter and @after-leave of a <Transition> run after the animations, in place of openChangeComplete and the unmount action. A template ref gives inputElement, close() and element, in place of inputRef and actionsRef. readonly and autocomplete have the names of the native attributes. Input and Trigger take id, because they have the role. form names the form of the hidden inputs, as the native attribute does. multiple has no declared default, because withDefaults refuses a default for the generic type Multiple & boolean, and Vue gives an absent Boolean prop false. No part sends close-press, because the popup has no hidden dismiss buttons. |
Combobox.Label | :focus, :focus-visible and :focus-within select the focus, so the state has no focused, and the part has no data-focused. |
Combobox.Input | :focus, :focus-visible and :focus-within select the focus, so the state has no focused, and the part has no data-focused. |
Combobox.InputGroup | :focus, :focus-visible and :focus-within select the focus, so the state has no focused, and the part has no data-focused. |
Combobox.Clear | The button reads its element, so it needs no nativeButton. A <Transition> animates it, so its state has no transitionStatus. |
Combobox.Trigger | The trigger reads its element, so it needs no nativeButton. :focus, :focus-visible and :focus-within select the focus, so the state has no focused, and the part has no data-focused. |
Combobox.ChipRemove | The button reads its element, so it needs no nativeButton. |
Combobox.Portal | A <Teleport> moves the content, and to names its target. The only element of the portal in place is the visually hidden element that owns a popup with the input, so the portal takes no as and has no element slot. It takes defer and disabled of <Teleport>. |
Combobox.Backdrop | A <Transition> around the backdrop animates it, so its state has no transitionStatus. |
Combobox.Popup | A <Transition> around the popup animates it, and a kept popup has hidden, so its state has no transitionStatus. |
Combobox.Collection | v-for over the items of a group, and the item slot of List, render the items. The part is cut. |
Combobox.Item | The item reads its element, so it needs no nativeButton. |
Combobox.ItemIndicator | The default slot of Item gives state.selected. A v-if or a v-show on an element of the developer shows the mark, and [aria-selected="true"] selects a selected item. The part is cut. |
Combobox.Group | v-for over the items of the group renders them, so the group takes no items. |
Added in Vase UI
| Part | Member | Why |
|---|---|---|
Combobox.Root | as prop | The root renders a <div> that holds the inputs of its form. as gives it another tag or a component. |
Combobox.Root | readonly prop | The name of the native attribute. A read-only root opens and moves the highlight, and the user cannot change its value. |
Combobox.Root | autocomplete prop | The name of the native attribute. It is the autofill purpose of the hidden text input. |
Combobox.Root | element exposed member | A template ref of a part gives its element. |
Combobox.List | item slot | The slot renders each filtered item with { item, index }, in place of the function child of the list. |
Combobox.Portal | defer prop | The portal is a <Teleport>, and it takes the props of <Teleport>: defer waits for the other content of the update. |
Combobox.Portal | disabled prop | A disabled portal renders its content in place, also on the server (VUE-128). |
Combobox.Empty | empty state field | The state says that the list is empty, for an element of the developer in the element slot. |
Combobox.Chip | readonly state field | A chip has no role that takes aria-readonly, so a chip of a read-only root has readonly in its state and the attribute data-readonly, where Base UI writes aria-readonly. |
Return types
| Function | Vase UI returns | Why |
|---|---|---|
Combobox.createItems | ComboboxItemCollection<Item, Value> | The function is generic in Value, so the result has the type argument Value of the call. Base UI documents ComboboxPrimitiveValue in that place. |
Combobox.useFilter | Filter | The composable returns Filter. ComboboxFilter, the name that Base UI documents, is the same type. |
Combobox.useFilteredItems | ComputedRef<T[]> | setup runs one time, so the composable returns a ComputedRef that follows each change of the filtered items. A plain array does not follow them. |
Behavior
| Vase UI | Evidence |
|---|---|
When Combobox.Popup, Dialog.Popup or Drawer.Popup closes, the focus returns at the close, before the exit animation ends. During the exit, the focus is not in the popup that closes, and no focusable content is under aria-hidden. The focus also returns to the trigger of an outer popup when a popup inside it, such as a nested dialog or a menu, closes in the same update or during the exit of the outer popup. Base UI returns the focus when the popup unmounts, after its exit animation. |
|
| A pick with the mouse during an IME composition leaves no stale text in the input. | |
Typeahead on a closed trigger does not select a mounted item that is disabled. The trigger reads the disabled state of the mounted items only, so a label that comes from items while the list is not mounted still matches. | |
A native reset of the form gives a control the v-model value of its mount, or else the default value that it has at the reset, as a native control does. The control emits only update:modelValue, also when v-model controls it. Its field is then not dirty, and it has data-filled only when that value is not empty. | |
The label of an item can be a function that returns the content of the label, so one label can show in the value part and in its item at the same time. The text of such an item is the result of itemToStringLabel, or the text of its value. Base UI takes a React element as a label, and the text of that item is [object Object]. A label function that returns vnodes needs the virtual DOM runtime of Vue. An application in Vapor mode has it with the vaporInteropPlugin. With no plugin, a label is text, and the slot of the Value part and of the item gives other content. |
|
With no locale, the filters of Combobox.useFilter, Autocomplete.useFilter, Combobox.Root and Autocomplete.Root use the locale of the nearest LocaleProvider, else en-US, on the server and in the browser. A list that a server filtered then hydrates with no mismatch, and it does not change after the mount. With no locale, Base UI uses the runtime locale in each render, so a server and a browser can filter a list in different ways. |
|
Combobox.createItems gives getValue and getLabel the leaf item of grouped data, and the result has the type of the leaf item. This holds with TypeScript 5.9 and 6.0. With these versions, the order of the members of the data type of Base UI gives the group as the item, so such a call does not type-check there. TypeScript 7.0 accepts both orders. | |
An open trigger of Dialog, Alert Dialog, Drawer, Popover, Menu, Select, Combobox or Autocomplete has no aria-controls while no popup or list element that it can name is mounted. An open NavigationMenu.Trigger has aria-controls with the id of its NavigationMenu.Content, only while that element is in the document. The server HTML of an open root thus has none. The trigger gives no aria-controls="" for an element with an empty id. It also names no popup part while KeepAlive holds that part, also when the part mounts in a held branch. Base UI differs. Its triggers of Dialog, Alert Dialog, Drawer, Popover and Menu name the default id of the popup while no popup element is mounted, also in the server HTML. Its Combobox.Trigger names the default id of the popup while no popup is mounted, and when a custom element of the popup has no id. No element has that id. Its Select.Trigger, Combobox.Trigger and NavigationMenu.Trigger give aria-controls="" for an element with an empty id. |
|
An expanded Combobox.Input or Autocomplete.Input names the list in aria-controls only while a list element is in the document. A trigger beside the input does the same. Base UI renders aria-controls="" on the input for a list with an empty id, and names the default id of the list while no list is mounted. |
|
When Combobox.Input or Autocomplete.Input renders an element that is not an <input>, such as a <textarea>, the browser keeps more of its caret keys. While the popup is closed, ArrowDown and ArrowUp move the caret between the lines and do not open the popup. Such an element has no role="combobox" while the popup is closed, as in Base UI. While the popup is open, or when the list is inline, the two keys move the highlight. Home and End go to the browser in each state, also when the input is in the popup. Base UI opens the popup for ArrowDown and ArrowUp. For Home and End, it moves the caret to the start or the end of the whole text. When the input is in the popup, it also moves the highlight to the first or the last item. |
|
When Combobox.Input or Autocomplete.Input is in the popup, or the list is inline, Home and End edit the text, also with a modifier key. They do what they do in an input outside the popup: Home and End move the caret to the start or the end, and Shift+Home and Shift+End select the text. The highlight does not move. In Base UI, the list navigation also takes the two keys in that state, because the input is then not its reference. It moves the highlight to the first or the last item and prevents the default action. Shift+Home and Shift+End thus select no text. With mode="both" of Autocomplete, the input then also shows the text of that item. |
|
A click on Combobox.Label focuses the control of its root: the input, or the trigger while the input is inside the popup. The id of the trigger element does not matter. Base UI finds the trigger by an id: the control id of the field, or the id of the trigger element with no field. A custom element of the trigger can give another id. In a field, the click then focuses nothing when that id differs from the control id of the field. With no field, the click focuses nothing when the id is empty. |
|
Combobox.Input in Combobox.Chips moves the focus to a chip only when the value is an array. With a value that is not an array, the input keeps the focus and the default action of the arrow key. That key is ArrowLeft in LTR and ArrowRight in RTL. The null value of a combobox with no multiple prop is such a value. Base UI reads selectedValue.length of each value. It throws a TypeError for a null value. For a string value that is not empty, it prevents the default action of the key at the start of the input. Combobox.Chip removes its value for Backspace and Delete only when the value is an array. Combobox.ChipRemove removes the value for a click, Enter and Space only when the value is an array. With each other value, the part ignores the event. The value does not change, and the part does not prevent the default action or stop the event. In Base UI, the chip reads selectedValue.length and throws a TypeError for a null value. For a string value, it stops the event and throws a TypeError at selectedValue.filter. The remove button reads selectedValue[index] and throws a TypeError for a null value. For a string value, it throws a TypeError at selectedValue.filter. |
|
A touch outside an open popup closes it only at a tap. A tap ends with pointerup in less than 1 s and moves 8 px or less. Chromium on Android sends click for a move of 8 px and not for 8.1 px, the smallest limit of the measured browsers. A touch that scrolls the page ends with pointercancel and closes nothing, as a native popover stays open in Chromium and WebKit. A drag of more than 8 px on an element that does not scroll also closes nothing. A tap on a backdrop, or on the element that a modal popup puts over the page, closes the popup and gives the page under it no click. In Base UI, a touch that scrolls the page closes a Popover, a Menu or a Select. | |
An arrow points at the center of its anchor. Its place is in the padding box of its nearest positioned ancestor, so the borders of a popup with a position do not move it. arrowPadding keeps the same space from each inner edge of that box. In the Popover demo of Base UI, the popup has position: relative and a 1 px border, and the arrow is 1.5 px off the center of its trigger. | |
--transform-origin is in the pixels of the popup, from its border box: the arrow or the aligned edge or the center of the anchor, on the edge of the anchor. A margin of the popup, a padding of the positioner, a margin that collapses through the popup and a zoom of the popup do not move it. A Select popup over the trigger grows from the middle of the value, also after it grows while the user scrolls the list. In the Popover demo of Base UI, a 16 px margin on the popup moves the origin 16 px off the edge of the trigger. | |
An arrow in a popup with a CSS zoom points at the center of its anchor. Its place and arrowPadding are in the pixels of its nearest positioned ancestor. A Select popup over the trigger with a zoom puts the text of the selected item over the text of the value. In the Popover demo of Base UI, a zoom: 2 on the popup moves the arrow 225 px off the center of the trigger. | |
A control in a field keeps the id of the developer in the server HTML when no Field.Label of the field renders before it, and a label that renders after the control has that id in for. When a label renders before the control, the control has the generated id of the field until the hydration, because that label names the generated id. Then the control takes its id, and the label follows. In each order, the label names the control in the server HTML. Base UI gives each control in a field the generated id until the hydration, also where no label needs it. |
|
At a close, the text of Combobox goes back in the same update: to the label of the value in an input that is the control, and to no text in other inputs. The popup that leaves in a <Transition> keeps the items that it showed, and its input is inert. An open during the leave starts as each open does: with the text of the close, with each item, and with the highlight on the selected item. A text that the user types during the leave is a new query. A close that the parent does not apply changes no text and no filter. So the result of a close and a new open does not depend on the duration of the exit animation. Base UI resets the text of a single combobox when the exit animation ends. An open during the animation keeps the typed text and its filter, and an open after the animation does not. Base UI also empties the text of a multiple combobox at a close that the parent does not apply. |
|
modal of Combobox.Root locks the scroll of the page and blocks the pointer outside the popup. It sets no focus trap. Tab from the last tab stop of the popup closes the popup and moves the focus on, as in Select and Menu. Each user thus has a way out of the popup with no close button. A modal Popover traps the focus only with a Popover.Close part, for the same reason. Base UI keeps the focus in a modal popup that holds the input: Tab from the last tab stop goes back to the input. Its way out for a touch screen reader is a hidden button with the fixed name "Dismiss". |
|
While the popup of Combobox or Autocomplete is open, the rest of the page stays in the accessibility tree, also with modal. The combobox pattern of the WAI-ARIA Authoring Practices hides no content. A screen reader user can read the page and can reach the trigger and the clear button. An element with aria-owns at the place of the portal puts the popup after the input in the reading order. Base UI gives aria-hidden to each element outside the input group and the popup. Its way out for a touch screen reader is a hidden button with the fixed name "Dismiss". |
|
With items, a fill of the browser matches the form text and the label of each item of items. The label is the text that the input shows and that the filter reads: label of an object item, or the result of itemToStringLabel. The root mounts no list for the match. Base UI mounts the closed list when no form text and no label matches, and it then reads the rendered text of each item. |
|
When the focus leaves the input of Combobox while its popup is closed, the text goes back as at a close: to the label of the value, or to no text with multiple. After the user leaves the input, it thus shows no text that is not the value, also when the parent keeps a value that the user emptied. Base UI keeps that text until the items change or the popup closes. |
|
A button part knows the element of a component in as or of the element slot only at the mount, and it needs no prop that says what the element is. Until the mount, the element has the attributes that suit a <button> and each other element: type="button", role="button", a tab stop, and the disabled state of both. So in the server HTML, Tab reaches a <div> before a lazy hydration, and a <button> does not submit its form. At the mount, the part keeps the attributes of its element. Base UI needs nativeButton set to false for an element that is not a <button>. |
|
The handbook gives the differences that all components share: Styling, Animation, Composition, Customization, Forms and TypeScript.