Skip to content

Select

A select element to choose from a list of options.

Demo

This requires the following components to be installed:

This requires the following composables to be installed:

This requires the following utils to be installed:

This requires the following types to be installed:

This requires the following theme to be installed:

Component

Select.vue
vue
<script lang="ts">
import type { AvatarProps } from '@/ui/components/Avatar.vue'
import type { ChipProps } from '@/ui/components/Chip.vue'
import type { InputProps } from '@/ui/components/Input.vue'
import type { UseComponentIconsProps } from '@/ui/composables/useComponentIcons'
import type { ArrayOrNested, ComponentConfig, GetItemKeys, GetItemValue, GetModelValue, GetModelValueEmits, NestedItem } from '@/ui/utils/utils'
import type { AcceptableValue, SelectArrowProps, SelectContentEmits, SelectContentProps, SelectRootEmits, SelectRootProps } from 'reka-ui'
import type { EmitsToProps } from 'vue'
import Avatar from '@/ui/components/Avatar.vue'
import Chip from '@/ui/components/Chip.vue'
import Icon from '@/ui/components/Icon.vue'
import { useButtonGroup } from '@/ui/composables/useButtonGroup'
import { useComponentIcons } from '@/ui/composables/useComponentIcons'
import { useFormField } from '@/ui/composables/useFormField'
import { usePortal } from '@/ui/composables/usePortal'
import { checkIcon, chevronDownIcon } from '@/ui/icons'
import theme from '@/ui/theme/select'
import { compare } from '@/ui/utils/compare'
import { get } from '@/ui/utils/get'
import { isArrayOfArray } from '@/ui/utils/is-array-of-array'
import { reactivePick } from '@vueuse/shared'
import defu from 'defu'
import { SelectItem as RekaSelectItem, SelectArrow, SelectContent, SelectGroup, SelectItemIndicator, SelectItemText, SelectLabel, SelectPortal, SelectRoot, SelectSeparator, SelectTrigger, SelectViewport, useForwardPropsEmits } from 'reka-ui'
import { tv } from 'tailwind-variants'
import { computed, toRef } from 'vue'

type Select = ComponentConfig<typeof theme>

interface SelectItemBase {
  label?: string
  icon?: string
  avatar?: AvatarProps
  chip?: ChipProps
  type?: 'label' | 'separator' | 'item'
  value?: string | number
  disabled?: boolean
  onSelect?: (e?: Event) => void
  [key: string]: any
}
export type SelectItem = SelectItemBase | AcceptableValue | boolean

export interface SelectProps<T extends ArrayOrNested<SelectItem> = ArrayOrNested<SelectItem>, VK extends GetItemKeys<T> = 'value', M extends boolean = false> extends Omit<SelectRootProps<T>, 'dir' | 'multiple' | 'modelValue' | 'defaultValue' | 'by'>, UseComponentIconsProps {
  id?: string
  placeholder?: string
  color?: Select['variants']['color']
  variant?: Select['variants']['variant']
  size?: Select['variants']['size']
  trailingIcon?: string
  selectedIcon?: string
  content?: Omit<SelectContentProps, 'as' | 'asChild' | 'forceMount'> & Partial<EmitsToProps<SelectContentEmits>>
  arrow?: boolean | Omit<SelectArrowProps, 'as' | 'asChild'>
  portal?: boolean | string | HTMLElement
  valueKey?: VK
  labelKey?: keyof NestedItem<T>
  items?: T
  defaultValue?: GetModelValue<T, VK, M>
  modelValue?: GetModelValue<T, VK, M>
  multiple?: M & boolean
  highlight?: boolean
  class?: any
  ui?: Select['slots']
}

export type SelectEmits<A extends ArrayOrNested<SelectItem>, VK extends GetItemKeys<A> | undefined, M extends boolean> = Omit<SelectRootEmits, 'update:modelValue'> & {
  change: [payload: Event]
  blur: [payload: FocusEvent]
  focus: [payload: FocusEvent]
} & GetModelValueEmits<A, VK, M>

type SlotProps<T extends SelectItem> = (props: { item: T, index: number }) => any

export interface SelectSlots<
  A extends ArrayOrNested<SelectItem> = ArrayOrNested<SelectItem>,
  VK extends GetItemKeys<A> | undefined = undefined,
  M extends boolean = false,
  T extends NestedItem<A> = NestedItem<A>,
> {
  'leading': (props: {
    modelValue?: GetModelValue<A, VK, M>
    open: boolean
    ui: { [K in keyof Required<Select['slots']>]: (props?: Record<string, any>) => string }
  }) => any
  'default': (props: {
    modelValue?: GetModelValue<A, VK, M>
    open: boolean
  }) => any
  'trailing': (props: {
    modelValue?: GetModelValue<A, VK, M>
    open: boolean
    ui: { [K in keyof Required<Select['slots']>]: (props?: Record<string, any>) => string }
  }) => any
  'item': SlotProps<T>
  'item-leading': SlotProps<T>
  'item-label': SlotProps<T>
  'item-trailing': SlotProps<T>
  'content-top': (props?: object) => any
  'content-bottom': (props?: object) => any
}
</script>

<script setup lang="ts" generic="T extends ArrayOrNested<SelectItem>, VK extends GetItemKeys<T> = 'value', M extends boolean = false">
defineOptions({ inheritAttrs: false })

const props = withDefaults(defineProps<SelectProps<T, VK, M>>(), {
  valueKey: 'value' as never,
  labelKey: 'label' as never,
  portal: true,
})
const emits = defineEmits<SelectEmits<T, VK, M>>()
const slots = defineSlots<SelectSlots<T, VK, M>>()

const rootProps = useForwardPropsEmits(reactivePick(props, 'open', 'defaultOpen', 'disabled', 'autocomplete', 'required', 'multiple'), emits)
const portalProps = usePortal(toRef(() => props.portal))
const contentProps = toRef(() => defu(props.content, { side: 'bottom', sideOffset: 8, collisionPadding: 8, position: 'popper' }) as SelectContentProps)
const arrowProps = toRef(() => props.arrow as SelectArrowProps)

const { size: formGroupSize, color, id, name, highlight, disabled, ariaAttrs } = useFormField<InputProps>(props)
const { orientation, size: buttonGroupSize } = useButtonGroup<InputProps>(props)
const { isLeading, isTrailing, leadingIconName, trailingIconName } = useComponentIcons(toRef(() => defu(props, { trailingIcon: chevronDownIcon })))

const selectSize = computed(() => buttonGroupSize.value || formGroupSize.value)

const ui = computed(() => tv(theme)({
  color: color.value,
  variant: props.variant,
  size: selectSize?.value,
  loading: props.loading,
  highlight: highlight.value,
  leading: isLeading.value || !!props.avatar || !!slots.leading,
  trailing: isTrailing.value || !!slots.trailing,
  buttonGroup: orientation.value,
}))

const groups = computed<SelectItem[][]>(() =>
  props.items?.length
    ? isArrayOfArray(props.items)
      ? props.items
      : [props.items]
    : [],
)
const items = computed(() => groups.value.flatMap(group => group) as T[])

function displayValue(value?: GetItemValue<T, VK> | GetItemValue<T, VK>[]): string {
  if (props.multiple && Array.isArray(value)) {
    return value.map(v => displayValue(v)).filter(Boolean).join(', ')
  }

  const item = items.value.find(item => compare(typeof item === 'object' ? get(item as Record<string, any>, props.valueKey as string) : item, value))
  return item && (typeof item === 'object' ? get(item, props.labelKey as string) : item)
}

function onUpdate(value: any) {
  // @ts-expect-error - 'target' does not exist in type 'EventInit'
  const event = new Event('change', { target: { value } })
  emits('change', event)
}
function onUpdateOpen(value: boolean) {
  if (!value) {
    const event = new FocusEvent('blur')
    emits('blur', event)
  }
  else {
    const event = new FocusEvent('focus')
    emits('focus', event)
  }
}

function isSelectItem(item: SelectItem): item is SelectItemBase {
  return typeof item === 'object' && item !== null
}
</script>

<!-- eslint-disable vue/no-template-shadow -->
<template>
  <SelectRoot
    v-slot="{ modelValue, open }"
    :name="name"
    v-bind="rootProps"
    :autocomplete="autocomplete"
    :disabled="disabled"
    :default-value="(defaultValue as (AcceptableValue | AcceptableValue[]))"
    :model-value="(modelValue as (AcceptableValue | AcceptableValue[]))"
    @update:model-value="onUpdate"
    @update:open="onUpdateOpen"
  >
    <SelectTrigger :id="id" :class="ui.base({ class: [props.class, props.ui?.base] })" v-bind="{ ...$attrs, ...ariaAttrs }">
      <span v-if="isLeading || !!avatar || !!slots.leading" :class="ui.leading({ class: props.ui?.leading })">
        <slot name="leading" :model-value="(modelValue as GetModelValue<T, VK, M>)" :open="open" :ui="ui">
          <Icon v-if="isLeading && leadingIconName" :name="leadingIconName" :class="ui.leadingIcon({ class: props.ui?.leadingIcon })" />
          <Avatar v-else-if="!!avatar" :size="((props.ui?.itemLeadingAvatarSize || ui.itemLeadingAvatarSize()) as AvatarProps['size'])" v-bind="avatar" :class="ui.itemLeadingAvatar({ class: props.ui?.itemLeadingAvatar })" />
        </slot>
      </span>

      <slot :model-value="(modelValue as GetModelValue<T, VK, M>)" :open="open">
        <template v-for="displayedModelValue in [displayValue(modelValue as GetModelValue<T, VK, M>)]" :key="displayedModelValue">
          <span v-if="displayedModelValue" :class="ui.value({ class: props.ui?.value })">
            {{ displayedModelValue }}
          </span>
          <span v-else :class="ui.placeholder({ class: props.ui?.placeholder })">
            {{ placeholder ?? '&nbsp;' }}
          </span>
        </template>
      </slot>

      <span v-if="isTrailing || !!slots.trailing" :class="ui.trailing({ class: props.ui?.trailing })">
        <slot name="trailing" :model-value="(modelValue as GetModelValue<T, VK, M>)" :open="open" :ui="ui">
          <Icon v-if="trailingIconName" :name="trailingIconName" :class="ui.trailingIcon({ class: props.ui?.trailingIcon })" />
        </slot>
      </span>
    </SelectTrigger>

    <SelectPortal v-bind="portalProps">
      <SelectContent :class="ui.content({ class: props.ui?.content })" v-bind="contentProps">
        <slot name="content-top" />

        <SelectViewport :class="ui.viewport({ class: props.ui?.viewport })">
          <SelectGroup v-for="(group, groupIndex) in groups" :key="`group-${groupIndex}`" :class="ui.group({ class: props.ui?.group })">
            <template v-for="(item, index) in group" :key="`group-${groupIndex}-${index}`">
              <SelectLabel v-if="isSelectItem(item) && item.type === 'label'" :class="ui.label({ class: props.ui?.label })">
                {{ get(item, props.labelKey as string) }}
              </SelectLabel>

              <SelectSeparator v-else-if="isSelectItem(item) && item.type === 'separator'" :class="ui.separator({ class: props.ui?.separator })" />

              <RekaSelectItem
                v-else
                :class="ui.item({ class: props.ui?.item })"
                :disabled="isSelectItem(item) && item.disabled"
                :value="isSelectItem(item) ? get(item, props.valueKey as string) : item"
                @select="isSelectItem(item) && item.onSelect?.($event)"
              >
                <slot name="item" :item="(item as NestedItem<T>)" :index="index">
                  <slot name="item-leading" :item="(item as NestedItem<T>)" :index="index">
                    <Icon v-if="isSelectItem(item) && item.icon" :name="item.icon" :class="ui.itemLeadingIcon({ class: props.ui?.itemLeadingIcon })" />
                    <Avatar v-else-if="isSelectItem(item) && item.avatar" :size="((props.ui?.itemLeadingAvatarSize || ui.itemLeadingAvatarSize()) as AvatarProps['size'])" v-bind="item.avatar" :class="ui.itemLeadingAvatar({ class: props.ui?.itemLeadingAvatar })" />
                    <Chip
                      v-else-if="isSelectItem(item) && item.chip"
                      :size="((props.ui?.itemLeadingChipSize || ui.itemLeadingChipSize()) as ChipProps['size'])"
                      inset
                      standalone
                      v-bind="item.chip"
                      :class="ui.itemLeadingChip({ class: props.ui?.itemLeadingChip })"
                    />
                  </slot>

                  <SelectItemText :class="ui.itemLabel({ class: props.ui?.itemLabel })">
                    <slot name="item-label" :item="(item as NestedItem<T>)" :index="index">
                      {{ isSelectItem(item) ? get(item, props.labelKey as string) : item }}
                    </slot>
                  </SelectItemText>

                  <span :class="ui.itemTrailing({ class: props.ui?.itemTrailing })">
                    <slot name="item-trailing" :item="(item as NestedItem<T>)" :index="index" />

                    <SelectItemIndicator as-child>
                      <Icon :name="checkIcon" :class="ui.itemTrailingIcon({ class: props.ui?.itemTrailingIcon })" />
                    </SelectItemIndicator>
                  </span>
                </slot>
              </RekaSelectItem>
            </template>
          </SelectGroup>
        </SelectViewport>

        <slot name="content-bottom" />

        <SelectArrow v-if="!!arrow" v-bind="arrowProps" :class="ui.arrow({ class: props.ui?.arrow })" />
      </SelectContent>
    </SelectPortal>
  </SelectRoot>
</template>
Select.vue
vue
<script lang="ts">
import type { AvatarProps } from '@/UI/Components/Avatar.vue'
import type { ChipProps } from '@/UI/Components/Chip.vue'
import type { InputProps } from '@/UI/Components/Input.vue'
import type { UseComponentIconsProps } from '@/UI/Composables/useComponentIcons'
import type { ArrayOrNested, ComponentConfig, GetItemKeys, GetItemValue, GetModelValue, GetModelValueEmits, NestedItem } from '@/UI/Utils/utils'
import type { AcceptableValue, SelectArrowProps, SelectContentEmits, SelectContentProps, SelectRootEmits, SelectRootProps } from 'reka-ui'
import type { EmitsToProps } from 'vue'
import Avatar from '@/UI/Components/Avatar.vue'
import Chip from '@/UI/Components/Chip.vue'
import Icon from '@/UI/Components/Icon.vue'
import { useButtonGroup } from '@/UI/Composables/useButtonGroup'
import { useComponentIcons } from '@/UI/Composables/useComponentIcons'
import { useFormField } from '@/UI/Composables/useFormField'
import { usePortal } from '@/UI/Composables/usePortal'
import { checkIcon, chevronDownIcon } from '@/UI/icons'
import theme from '@/UI/Theme/select'
import { compare } from '@/UI/Utils/compare'
import { get } from '@/UI/Utils/get'
import { isArrayOfArray } from '@/UI/Utils/is-array-of-array'
import { reactivePick } from '@vueuse/shared'
import defu from 'defu'
import { SelectItem as RekaSelectItem, SelectArrow, SelectContent, SelectGroup, SelectItemIndicator, SelectItemText, SelectLabel, SelectPortal, SelectRoot, SelectSeparator, SelectTrigger, SelectViewport, useForwardPropsEmits } from 'reka-ui'
import { tv } from 'tailwind-variants'
import { computed, toRef } from 'vue'

type Select = ComponentConfig<typeof theme>

interface SelectItemBase {
  label?: string
  icon?: string
  avatar?: AvatarProps
  chip?: ChipProps
  type?: 'label' | 'separator' | 'item'
  value?: string | number
  disabled?: boolean
  onSelect?: (e?: Event) => void
  [key: string]: any
}
export type SelectItem = SelectItemBase | AcceptableValue | boolean

export interface SelectProps<T extends ArrayOrNested<SelectItem> = ArrayOrNested<SelectItem>, VK extends GetItemKeys<T> = 'value', M extends boolean = false> extends Omit<SelectRootProps<T>, 'dir' | 'multiple' | 'modelValue' | 'defaultValue' | 'by'>, UseComponentIconsProps {
  id?: string
  placeholder?: string
  color?: Select['variants']['color']
  variant?: Select['variants']['variant']
  size?: Select['variants']['size']
  trailingIcon?: string
  selectedIcon?: string
  content?: Omit<SelectContentProps, 'as' | 'asChild' | 'forceMount'> & Partial<EmitsToProps<SelectContentEmits>>
  arrow?: boolean | Omit<SelectArrowProps, 'as' | 'asChild'>
  portal?: boolean | string | HTMLElement
  valueKey?: VK
  labelKey?: keyof NestedItem<T>
  items?: T
  defaultValue?: GetModelValue<T, VK, M>
  modelValue?: GetModelValue<T, VK, M>
  multiple?: M & boolean
  highlight?: boolean
  class?: any
  ui?: Select['slots']
}

export type SelectEmits<A extends ArrayOrNested<SelectItem>, VK extends GetItemKeys<A> | undefined, M extends boolean> = Omit<SelectRootEmits, 'update:modelValue'> & {
  change: [payload: Event]
  blur: [payload: FocusEvent]
  focus: [payload: FocusEvent]
} & GetModelValueEmits<A, VK, M>

type SlotProps<T extends SelectItem> = (props: { item: T, index: number }) => any

export interface SelectSlots<
  A extends ArrayOrNested<SelectItem> = ArrayOrNested<SelectItem>,
  VK extends GetItemKeys<A> | undefined = undefined,
  M extends boolean = false,
  T extends NestedItem<A> = NestedItem<A>,
> {
  'leading': (props: {
    modelValue?: GetModelValue<A, VK, M>
    open: boolean
    ui: { [K in keyof Required<Select['slots']>]: (props?: Record<string, any>) => string }
  }) => any
  'default': (props: {
    modelValue?: GetModelValue<A, VK, M>
    open: boolean
  }) => any
  'trailing': (props: {
    modelValue?: GetModelValue<A, VK, M>
    open: boolean
    ui: { [K in keyof Required<Select['slots']>]: (props?: Record<string, any>) => string }
  }) => any
  'item': SlotProps<T>
  'item-leading': SlotProps<T>
  'item-label': SlotProps<T>
  'item-trailing': SlotProps<T>
  'content-top': (props?: object) => any
  'content-bottom': (props?: object) => any
}
</script>

<script setup lang="ts" generic="T extends ArrayOrNested<SelectItem>, VK extends GetItemKeys<T> = 'value', M extends boolean = false">
defineOptions({ inheritAttrs: false })

const props = withDefaults(defineProps<SelectProps<T, VK, M>>(), {
  valueKey: 'value' as never,
  labelKey: 'label' as never,
  portal: true,
})
const emits = defineEmits<SelectEmits<T, VK, M>>()
const slots = defineSlots<SelectSlots<T, VK, M>>()

const rootProps = useForwardPropsEmits(reactivePick(props, 'open', 'defaultOpen', 'disabled', 'autocomplete', 'required', 'multiple'), emits)
const portalProps = usePortal(toRef(() => props.portal))
const contentProps = toRef(() => defu(props.content, { side: 'bottom', sideOffset: 8, collisionPadding: 8, position: 'popper' }) as SelectContentProps)
const arrowProps = toRef(() => props.arrow as SelectArrowProps)

const { size: formGroupSize, color, id, name, highlight, disabled, ariaAttrs } = useFormField<InputProps>(props)
const { orientation, size: buttonGroupSize } = useButtonGroup<InputProps>(props)
const { isLeading, isTrailing, leadingIconName, trailingIconName } = useComponentIcons(toRef(() => defu(props, { trailingIcon: chevronDownIcon })))

const selectSize = computed(() => buttonGroupSize.value || formGroupSize.value)

const ui = computed(() => tv(theme)({
  color: color.value,
  variant: props.variant,
  size: selectSize?.value,
  loading: props.loading,
  highlight: highlight.value,
  leading: isLeading.value || !!props.avatar || !!slots.leading,
  trailing: isTrailing.value || !!slots.trailing,
  buttonGroup: orientation.value,
}))

const groups = computed<SelectItem[][]>(() =>
  props.items?.length
    ? isArrayOfArray(props.items)
      ? props.items
      : [props.items]
    : [],
)
const items = computed(() => groups.value.flatMap(group => group) as T[])

function displayValue(value?: GetItemValue<T, VK> | GetItemValue<T, VK>[]): string {
  if (props.multiple && Array.isArray(value)) {
    return value.map(v => displayValue(v)).filter(Boolean).join(', ')
  }

  const item = items.value.find(item => compare(typeof item === 'object' ? get(item as Record<string, any>, props.valueKey as string) : item, value))
  return item && (typeof item === 'object' ? get(item, props.labelKey as string) : item)
}

function onUpdate(value: any) {
  // @ts-expect-error - 'target' does not exist in type 'EventInit'
  const event = new Event('change', { target: { value } })
  emits('change', event)
}
function onUpdateOpen(value: boolean) {
  if (!value) {
    const event = new FocusEvent('blur')
    emits('blur', event)
  }
  else {
    const event = new FocusEvent('focus')
    emits('focus', event)
  }
}

function isSelectItem(item: SelectItem): item is SelectItemBase {
  return typeof item === 'object' && item !== null
}
</script>

<!-- eslint-disable vue/no-template-shadow -->
<template>
  <SelectRoot
    v-slot="{ modelValue, open }"
    :name="name"
    v-bind="rootProps"
    :autocomplete="autocomplete"
    :disabled="disabled"
    :default-value="(defaultValue as (AcceptableValue | AcceptableValue[]))"
    :model-value="(modelValue as (AcceptableValue | AcceptableValue[]))"
    @update:model-value="onUpdate"
    @update:open="onUpdateOpen"
  >
    <SelectTrigger :id="id" :class="ui.base({ class: [props.class, props.ui?.base] })" v-bind="{ ...$attrs, ...ariaAttrs }">
      <span v-if="isLeading || !!avatar || !!slots.leading" :class="ui.leading({ class: props.ui?.leading })">
        <slot name="leading" :model-value="(modelValue as GetModelValue<T, VK, M>)" :open="open" :ui="ui">
          <Icon v-if="isLeading && leadingIconName" :name="leadingIconName" :class="ui.leadingIcon({ class: props.ui?.leadingIcon })" />
          <Avatar v-else-if="!!avatar" :size="((props.ui?.itemLeadingAvatarSize || ui.itemLeadingAvatarSize()) as AvatarProps['size'])" v-bind="avatar" :class="ui.itemLeadingAvatar({ class: props.ui?.itemLeadingAvatar })" />
        </slot>
      </span>

      <slot :model-value="(modelValue as GetModelValue<T, VK, M>)" :open="open">
        <template v-for="displayedModelValue in [displayValue(modelValue as GetModelValue<T, VK, M>)]" :key="displayedModelValue">
          <span v-if="displayedModelValue" :class="ui.value({ class: props.ui?.value })">
            {{ displayedModelValue }}
          </span>
          <span v-else :class="ui.placeholder({ class: props.ui?.placeholder })">
            {{ placeholder ?? '&nbsp;' }}
          </span>
        </template>
      </slot>

      <span v-if="isTrailing || !!slots.trailing" :class="ui.trailing({ class: props.ui?.trailing })">
        <slot name="trailing" :model-value="(modelValue as GetModelValue<T, VK, M>)" :open="open" :ui="ui">
          <Icon v-if="trailingIconName" :name="trailingIconName" :class="ui.trailingIcon({ class: props.ui?.trailingIcon })" />
        </slot>
      </span>
    </SelectTrigger>

    <SelectPortal v-bind="portalProps">
      <SelectContent :class="ui.content({ class: props.ui?.content })" v-bind="contentProps">
        <slot name="content-top" />

        <SelectViewport :class="ui.viewport({ class: props.ui?.viewport })">
          <SelectGroup v-for="(group, groupIndex) in groups" :key="`group-${groupIndex}`" :class="ui.group({ class: props.ui?.group })">
            <template v-for="(item, index) in group" :key="`group-${groupIndex}-${index}`">
              <SelectLabel v-if="isSelectItem(item) && item.type === 'label'" :class="ui.label({ class: props.ui?.label })">
                {{ get(item, props.labelKey as string) }}
              </SelectLabel>

              <SelectSeparator v-else-if="isSelectItem(item) && item.type === 'separator'" :class="ui.separator({ class: props.ui?.separator })" />

              <RekaSelectItem
                v-else
                :class="ui.item({ class: props.ui?.item })"
                :disabled="isSelectItem(item) && item.disabled"
                :value="isSelectItem(item) ? get(item, props.valueKey as string) : item"
                @select="isSelectItem(item) && item.onSelect?.($event)"
              >
                <slot name="item" :item="(item as NestedItem<T>)" :index="index">
                  <slot name="item-leading" :item="(item as NestedItem<T>)" :index="index">
                    <Icon v-if="isSelectItem(item) && item.icon" :name="item.icon" :class="ui.itemLeadingIcon({ class: props.ui?.itemLeadingIcon })" />
                    <Avatar v-else-if="isSelectItem(item) && item.avatar" :size="((props.ui?.itemLeadingAvatarSize || ui.itemLeadingAvatarSize()) as AvatarProps['size'])" v-bind="item.avatar" :class="ui.itemLeadingAvatar({ class: props.ui?.itemLeadingAvatar })" />
                    <Chip
                      v-else-if="isSelectItem(item) && item.chip"
                      :size="((props.ui?.itemLeadingChipSize || ui.itemLeadingChipSize()) as ChipProps['size'])"
                      inset
                      standalone
                      v-bind="item.chip"
                      :class="ui.itemLeadingChip({ class: props.ui?.itemLeadingChip })"
                    />
                  </slot>

                  <SelectItemText :class="ui.itemLabel({ class: props.ui?.itemLabel })">
                    <slot name="item-label" :item="(item as NestedItem<T>)" :index="index">
                      {{ isSelectItem(item) ? get(item, props.labelKey as string) : item }}
                    </slot>
                  </SelectItemText>

                  <span :class="ui.itemTrailing({ class: props.ui?.itemTrailing })">
                    <slot name="item-trailing" :item="(item as NestedItem<T>)" :index="index" />

                    <SelectItemIndicator as-child>
                      <Icon :name="checkIcon" :class="ui.itemTrailingIcon({ class: props.ui?.itemTrailingIcon })" />
                    </SelectItemIndicator>
                  </span>
                </slot>
              </RekaSelectItem>
            </template>
          </SelectGroup>
        </SelectViewport>

        <slot name="content-bottom" />

        <SelectArrow v-if="!!arrow" v-bind="arrowProps" :class="ui.arrow({ class: props.ui?.arrow })" />
      </SelectContent>
    </SelectPortal>
  </SelectRoot>
</template>

Theme

select.ts
ts
import { buttonGroupVariant } from '@/ui/theme/button-group'

export default {
  slots: {
    base:
      '',
    leading: '',
    leadingIcon: '',
    leadingAvatar: '',
    leadingAvatarSize: '',
    trailing: '',
    trailingIcon: '',
    value: '',
    placeholder: '',
    arrow: '',
    content: '',
    viewport: '',
    group: '',
    empty: '',
    label: '',
    separator: '',
    item: '',
    itemLeadingIcon: '',
    itemLeadingAvatar: '',
    itemLeadingAvatarSize: '',
    itemLeadingChip: '',
    itemLeadingChipSize: '',
    itemTrailing: '',
    itemTrailingIcon: '',
    itemLabel: '',
  },
  variants: {
    ...buttonGroupVariant,
    variant: {
      outline: '',
      soft: '',
      subtle: '',
      ghost: '',
      none: '',
    },
    color: {
      primary: '',
      secondary: '',
      success: '',
      info: '',
      warning: '',
      error: '',
      neutral: '',
    },
    leading: {
      true: '',
    },
    trailing: {
      true: '',
    },
    loading: {
      true: '',
    },
    highlight: {
      true: '',
    },
    type: {
      file: '',
    },
    size: {
      xs: {
        base: '',
        leading: '',
        trailing: '',
        leadingIcon: '',
        leadingAvatarSize: '',
        trailingIcon: '',
        label: '',
        item: '',
        itemLeadingIcon: '',
        itemLeadingAvatarSize: '',
        itemLeadingChip: '',
        itemLeadingChipSize: '',
        itemTrailingIcon: '',
      },
      sm: {
        base: '',
        leading: '',
        trailing: '',
        leadingIcon: '',
        leadingAvatarSize: '',
        trailingIcon: '',
        label: '',
        item: '',
        itemLeadingIcon: '',
        itemLeadingAvatarSize: '',
        itemLeadingChip: '',
        itemLeadingChipSize: '',
        itemTrailingIcon: '',
      },
      md: {
        base: '',
        leading: '',
        trailing: '',
        leadingIcon: '',
        leadingAvatarSize: '',
        trailingIcon: '',
        label: '',
        item: '',
        itemLeadingIcon: '',
        itemLeadingAvatarSize: '',
        itemLeadingChip: '',
        itemLeadingChipSize: '',
        itemTrailingIcon: '',
      },
      lg: {
        base: '',
        leading: '',
        trailing: '',
        leadingIcon: '',
        leadingAvatarSize: '',
        trailingIcon: '',
        label: '',
        item: '',
        itemLeadingIcon: '',
        itemLeadingAvatarSize: '',
        itemLeadingChip: '',
        itemLeadingChipSize: '',
        itemTrailingIcon: '',
      },
      xl: {
        base: '',
        leading: '',
        trailing: '',
        leadingIcon: '',
        leadingAvatarSize: '',
        trailingIcon: '',
        label: '',
        item: '',
        itemLeadingIcon: '',
        itemLeadingAvatarSize: '',
        itemLeadingChip: '',
        itemLeadingChipSize: '',
        itemTrailingIcon: '',
      },
    },
  },
  compoundVariants: [],
  defaultVariants: {
    size: 'md',
    color: 'primary',
    variant: 'outline',
  } as const,
}
View Nuxt UI theme
select.ts
ts
import { buttonGroupVariant } from '@/ui/theme/button-group'

export default {
  slots: {
    base:
      'relative group rounded-md inline-flex items-center focus:outline-none disabled:cursor-not-allowed disabled:opacity-75 transition-colors',
    leading: 'absolute inset-y-0 start-0 flex items-center',
    leadingIcon: 'shrink-0 text-dimmed',
    leadingAvatar: 'shrink-0',
    leadingAvatarSize: '',
    trailing: 'absolute inset-y-0 end-0 flex items-center',
    trailingIcon: 'shrink-0 text-dimmed',
    value: 'truncate pointer-events-none',
    placeholder: 'truncate text-dimmed',
    arrow: 'fill-default',
    content: 'max-h-60 w-(--reka-select-trigger-width) bg-default shadow-lg rounded-md ring ring-default overflow-hidden data-[state=open]:animate-[scale-in_100ms_ease-out] data-[state=closed]:animate-[scale-out_100ms_ease-in] origin-(--reka-select-content-transform-origin) pointer-events-auto',
    viewport: 'divide-y divide-default scroll-py-1',
    group: 'p-1 isolate',
    empty: 'py-2 text-center text-sm text-muted',
    label: 'font-semibold text-highlighted',
    separator: '-mx-1 my-1 h-px bg-border',
    item: 'group relative w-full flex items-center select-none outline-none before:absolute before:z-[-1] before:inset-px before:rounded-md data-disabled:cursor-not-allowed data-disabled:opacity-75 text-default data-highlighted:not-data-disabled:text-highlighted data-highlighted:not-data-disabled:before:bg-elevated/50 transition-colors before:transition-colors',
    itemLeadingIcon: 'shrink-0 text-dimmed group-data-highlighted:not-group-data-disabled:text-default transition-colors',
    itemLeadingAvatar: 'shrink-0',
    itemLeadingAvatarSize: '',
    itemLeadingChip: 'shrink-0',
    itemLeadingChipSize: '',
    itemTrailing: 'ms-auto inline-flex gap-1.5 items-center',
    itemTrailingIcon: 'shrink-0',
    itemLabel: 'truncate',
  },
  variants: {
    ...buttonGroupVariant,
    variant: {
      outline: 'text-highlighted bg-default ring ring-inset ring-accented',
      soft: 'text-highlighted bg-elevated/50 hover:bg-elevated focus:bg-elevated disabled:bg-elevated/50',
      subtle: 'text-highlighted bg-elevated ring ring-inset ring-accented',
      ghost: 'text-highlighted bg-transparent hover:bg-elevated focus:bg-elevated disabled:bg-transparent dark:disabled:bg-transparent',
      none: 'text-highlighted bg-transparent',
    },
    color: {
      primary: '',
      secondary: '',
      success: '',
      info: '',
      warning: '',
      error: '',
      neutral: '',
    },
    leading: {
      true: '',
    },
    trailing: {
      true: '',
    },
    loading: {
      true: '',
    },
    highlight: {
      true: '',
    },
    type: {
      file: 'file:me-1.5 file:font-medium file:text-muted file:outline-none',
    },
    size: {
      xs: {
        base: 'px-2 py-1 text-xs gap-1',
        leading: 'ps-2',
        trailing: 'pe-2',
        leadingIcon: 'size-4',
        leadingAvatarSize: '3xs',
        trailingIcon: 'size-4',
        label: 'p-1 text-[10px]/3 gap-1',
        item: 'p-1 text-xs gap-1',
        itemLeadingIcon: 'size-4',
        itemLeadingAvatarSize: '3xs',
        itemLeadingChip: 'size-4',
        itemLeadingChipSize: 'sm',
        itemTrailingIcon: 'size-4',
      },
      sm: {
        base: 'px-2.5 py-1.5 text-xs gap-1.5',
        leading: 'ps-2.5',
        trailing: 'pe-2.5',
        leadingIcon: 'size-4',
        leadingAvatarSize: '3xs',
        trailingIcon: 'size-4',
        label: 'p-1.5 text-[10px]/3 gap-1.5',
        item: 'p-1.5 text-xs gap-1.5',
        itemLeadingIcon: 'size-4',
        itemLeadingAvatarSize: '3xs',
        itemLeadingChip: 'size-4',
        itemLeadingChipSize: 'sm',
        itemTrailingIcon: 'size-4',
      },
      md: {
        base: 'px-2.5 py-1.5 text-sm gap-1.5',
        leading: 'ps-2.5',
        trailing: 'pe-2.5',
        leadingIcon: 'size-5',
        leadingAvatarSize: '2xs',
        trailingIcon: 'size-5',
        label: 'p-1.5 text-xs gap-1.5',
        item: 'p-1.5 text-sm gap-1.5',
        itemLeadingIcon: 'size-5',
        itemLeadingAvatarSize: '2xs',
        itemLeadingChip: 'size-5',
        itemLeadingChipSize: 'md',
        itemTrailingIcon: 'size-5',
      },
      lg: {
        base: 'px-3 py-2 text-sm gap-2',
        leading: 'ps-3',
        trailing: 'pe-3',
        leadingIcon: 'size-5',
        leadingAvatarSize: '2xs',
        trailingIcon: 'size-5',
        label: 'p-2 text-xs gap-2',
        item: 'p-2 text-sm gap-2',
        itemLeadingIcon: 'size-5',
        itemLeadingAvatarSize: '2xs',
        itemLeadingChip: 'size-5',
        itemLeadingChipSize: 'md',
        itemTrailingIcon: 'size-5',
      },
      xl: {
        base: 'px-3 py-2 text-base gap-2',
        leading: 'ps-3',
        trailing: 'pe-3',
        leadingIcon: 'size-6',
        leadingAvatarSize: 'xs',
        trailingIcon: 'size-6',
        label: 'p-2 text-sm gap-2',
        item: 'p-2 text-base gap-2',
        itemLeadingIcon: 'size-6',
        itemLeadingAvatarSize: 'xs',
        itemLeadingChip: 'size-6',
        itemLeadingChipSize: 'lg',
        itemTrailingIcon: 'size-6',
      },
    },
  },
  compoundVariants: [
    {
      color: 'primary' as const,
      variant: ['outline' as const, 'subtle' as const],
      class: 'focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-primary',
    },
    {
      color: 'primary',
      highlight: true,
      class: 'ring ring-inset ring-primary',
    } as const,
    {
      color: 'secondary' as const,
      variant: ['outline' as const, 'subtle' as const],
      class: 'focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-secondary',
    },
    {
      color: 'secondary',
      highlight: true,
      class: 'ring ring-inset ring-secondary',
    } as const,
    {
      color: 'success' as const,
      variant: ['outline' as const, 'subtle' as const],
      class: 'focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-success',
    },
    {
      color: 'success',
      highlight: true,
      class: 'ring ring-inset ring-success',
    } as const,
    {
      color: 'info' as const,
      variant: ['outline' as const, 'subtle' as const],
      class: 'focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-info',
    },
    {
      color: 'info',
      highlight: true,
      class: 'ring ring-inset ring-info',
    } as const,
    {
      color: 'warning' as const,
      variant: ['outline' as const, 'subtle' as const],
      class: 'focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-warning',
    },
    {
      color: 'warning',
      highlight: true,
      class: 'ring ring-inset ring-warning',
    } as const,
    {
      color: 'error' as const,
      variant: ['outline' as const, 'subtle' as const],
      class: 'focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-error',
    },
    {
      color: 'error',
      highlight: true,
      class: 'ring ring-inset ring-error',
    } as const,
    {
      color: 'neutral' as const,
      variant: ['outline' as const, 'subtle' as const],
      class: 'focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-inverted',
    },
    {
      color: 'neutral',
      highlight: true,
      class: 'ring ring-inset ring-inverted',
    } as const,
    {
      leading: true,
      size: 'xs',
      class: 'ps-7',
    } as const,
    {
      leading: true,
      size: 'sm',
      class: 'ps-8',
    } as const,
    {
      leading: true,
      size: 'md',
      class: 'ps-9',
    } as const,
    {
      leading: true,
      size: 'lg',
      class: 'ps-10',
    } as const,
    {
      leading: true,
      size: 'xl',
      class: 'ps-11',
    } as const,
    {
      trailing: true,
      size: 'xs',
      class: 'pe-7',
    } as const,
    {
      trailing: true,
      size: 'sm',
      class: 'pe-8',
    } as const,
    {
      trailing: true,
      size: 'md',
      class: 'pe-9',
    } as const,
    {
      trailing: true,
      size: 'lg',
      class: 'pe-10',
    } as const,
    {
      trailing: true,
      size: 'xl',
      class: 'pe-11',
    } as const,
    {
      loading: true,
      leading: true,
      class: {
        leadingIcon: 'animate-spin',
      },
    } as const,
    {
      loading: true,
      leading: false,
      trailing: true,
      class: {
        trailingIcon: 'animate-spin',
      },
    } as const,
  ],
  defaultVariants: {
    size: 'md',
    color: 'primary',
    variant: 'outline',
  } as const,
}

Test

To test this component, you can use the following test file:

Select.test.ts
ts
import type { RenderOptions } from '@testing-library/vue'
import Select from '@/ui/components/Select.vue'
import theme from '@/ui/theme/select'
import { render } from '@testing-library/vue'
import { describe, expect, it } from 'vitest'

describe('select', () => {
  globalThis.ResizeObserver = class ResizeObserver {
    observe() {}
    unobserve() {}
    disconnect() {}
  }

  const sizes = Object.keys(theme.variants.size) as any
  const variants = Object.keys(theme.variants.variant) as any

  const items = [{
    label: 'Backlog',
    value: 'backlog',
    icon: 'i-lucide-circle-help',
  }, {
    label: 'Todo',
    value: 'todo',
    icon: 'i-lucide-circle-plus',
  }, {
    label: 'In Progress',
    value: 'in_progress',
    icon: 'i-lucide-circle-arrow-up',
  }, {
    label: 'Done',
    value: 'done',
    icon: 'i-lucide-circle-check',
  }, {
    label: 'Canceled',
    value: 'canceled',
    icon: 'i-lucide-circle-x',
  }]

  const props = { open: true, portal: false, items }

  it.each<[string, RenderOptions<typeof Select>]>([
    // Props
    ['with items', { props }],
    ['with modelValue', { props: { ...props, modelValue: items[0] } }],
    ['with defaultValue', { props: { ...props, defaultValue: items[0] } }],
    ['with valueKey', { props: { ...props, valueKey: 'label' } }],
    ['with labelKey', { props: { ...props, labelKey: 'value' } }],
    ['with multiple', { props: { ...props, multiple: true } }],
    ['with multiple and modelValue', { props: { ...props, multiple: true, modelValue: [items[0], items[1]] } }],
    ['with id', { props: { ...props, id: 'id' } }],
    ['with name', { props: { ...props, name: 'name' } }],
    ['with placeholder', { props: { ...props, placeholder: 'Search...' } }],
    ['with disabled', { props: { ...props, disabled: true } }],
    ['with required', { props: { ...props, required: true } }],
    ['with icon', { props: { icon: 'i-lucide-search' } }],
    ['with leading and icon', { props: { leading: true, icon: 'i-lucide-arrow-left' } }],
    ['with leadingIcon', { props: { leadingIcon: 'i-lucide-arrow-left' } }],
    ['with trailing and icon', { props: { trailing: true, icon: 'i-lucide-arrow-right' } }],
    ['with trailingIcon', { props: { trailingIcon: 'i-lucide-arrow-right' } }],
    ['with avatar', { props: { avatar: { src: 'https://github.com/vue.png' } } }],
    ['with avatar and leadingIcon', { props: { avatar: { src: 'https://github.com/vue.png' }, leadingIcon: 'i-lucide-arrow-left' } }],
    ['with avatar and trailingIcon', { props: { avatar: { src: 'https://github.com/vue.png' }, trailingIcon: 'i-lucide-arrow-right' } }],
    ['with loading', { props: { loading: true } }],
    ['with loading and avatar', { props: { loading: true, avatar: { src: 'https://github.com/vue.png' } } }],
    ['with loading trailing', { props: { loading: true, trailing: true } }],
    ['with loading trailing and avatar', { props: { loading: true, trailing: true, avatar: { src: 'https://github.com/vue.png' } } }],
    ['with loadingIcon', { props: { loading: true, loadingIcon: 'i-lucide-sparkles' } }],
    ['with trailingIcon', { props: { ...props, trailingIcon: 'i-lucide-chevron-down' } }],
    ['with selectedIcon', { props: { ...props, selectedIcon: 'i-lucide-check' } }],
    ['with arrow', { props: { ...props, arrow: true } }],
    ...sizes.map((size: string) => [`with size ${size}`, { props: { ...props, size } }]),
    ...variants.map((variant: string) => [`with primary variant ${variant}`, { props: { ...props, variant } }]),
    ...variants.map((variant: string) => [`with neutral variant ${variant}`, { props: { ...props, variant, color: 'neutral' } }]),
    ['with class', { props: { ...props, class: 'rounded-full' } }],
    ['with ui', { props: { ...props, ui: { group: 'p-2' } } }],
    // Slots
    ['with leading slot', { props, slots: { leading: () => 'Leading slot' } }],
    ['with trailing slot', { props, slots: { trailing: () => 'Trailing slot' } }],
    ['with item slot', { props, slots: { item: () => 'Item slot' } }],
    ['with item-leading slot', { props, slots: { 'item-leading': () => 'Item leading slot' } }],
    ['with item-label slot', { props, slots: { 'item-label': () => 'Item label slot' } }],
    ['with item-trailing slot', { props, slots: { 'item-trailing': () => 'Item trailing slot' } }],
  ])('renders %s correctly', async (name, options) => {
    const { html } = render(Select, options)

    await new Promise(resolve => setTimeout(resolve, 0))

    expect(html()).toMatchSnapshot()
  })
})
Select.test.ts
ts
import type { RenderOptions } from '@testing-library/vue'
import Select from '@/UI/Components/Select.vue'
import theme from '@/UI/Theme/select'
import { render } from '@testing-library/vue'
import { describe, expect, it } from 'vitest'

describe('select', () => {
  globalThis.ResizeObserver = class ResizeObserver {
    observe() {}
    unobserve() {}
    disconnect() {}
  }

  const sizes = Object.keys(theme.variants.size) as any
  const variants = Object.keys(theme.variants.variant) as any

  const items = [{
    label: 'Backlog',
    value: 'backlog',
    icon: 'i-lucide-circle-help',
  }, {
    label: 'Todo',
    value: 'todo',
    icon: 'i-lucide-circle-plus',
  }, {
    label: 'In Progress',
    value: 'in_progress',
    icon: 'i-lucide-circle-arrow-up',
  }, {
    label: 'Done',
    value: 'done',
    icon: 'i-lucide-circle-check',
  }, {
    label: 'Canceled',
    value: 'canceled',
    icon: 'i-lucide-circle-x',
  }]

  const props = { open: true, portal: false, items }

  it.each<[string, RenderOptions<typeof Select>]>([
    // Props
    ['with items', { props }],
    ['with modelValue', { props: { ...props, modelValue: items[0] } }],
    ['with defaultValue', { props: { ...props, defaultValue: items[0] } }],
    ['with valueKey', { props: { ...props, valueKey: 'label' } }],
    ['with labelKey', { props: { ...props, labelKey: 'value' } }],
    ['with multiple', { props: { ...props, multiple: true } }],
    ['with multiple and modelValue', { props: { ...props, multiple: true, modelValue: [items[0], items[1]] } }],
    ['with id', { props: { ...props, id: 'id' } }],
    ['with name', { props: { ...props, name: 'name' } }],
    ['with placeholder', { props: { ...props, placeholder: 'Search...' } }],
    ['with disabled', { props: { ...props, disabled: true } }],
    ['with required', { props: { ...props, required: true } }],
    ['with icon', { props: { icon: 'i-lucide-search' } }],
    ['with leading and icon', { props: { leading: true, icon: 'i-lucide-arrow-left' } }],
    ['with leadingIcon', { props: { leadingIcon: 'i-lucide-arrow-left' } }],
    ['with trailing and icon', { props: { trailing: true, icon: 'i-lucide-arrow-right' } }],
    ['with trailingIcon', { props: { trailingIcon: 'i-lucide-arrow-right' } }],
    ['with avatar', { props: { avatar: { src: 'https://github.com/vue.png' } } }],
    ['with avatar and leadingIcon', { props: { avatar: { src: 'https://github.com/vue.png' }, leadingIcon: 'i-lucide-arrow-left' } }],
    ['with avatar and trailingIcon', { props: { avatar: { src: 'https://github.com/vue.png' }, trailingIcon: 'i-lucide-arrow-right' } }],
    ['with loading', { props: { loading: true } }],
    ['with loading and avatar', { props: { loading: true, avatar: { src: 'https://github.com/vue.png' } } }],
    ['with loading trailing', { props: { loading: true, trailing: true } }],
    ['with loading trailing and avatar', { props: { loading: true, trailing: true, avatar: { src: 'https://github.com/vue.png' } } }],
    ['with loadingIcon', { props: { loading: true, loadingIcon: 'i-lucide-sparkles' } }],
    ['with trailingIcon', { props: { ...props, trailingIcon: 'i-lucide-chevron-down' } }],
    ['with selectedIcon', { props: { ...props, selectedIcon: 'i-lucide-check' } }],
    ['with arrow', { props: { ...props, arrow: true } }],
    ...sizes.map((size: string) => [`with size ${size}`, { props: { ...props, size } }]),
    ...variants.map((variant: string) => [`with primary variant ${variant}`, { props: { ...props, variant } }]),
    ...variants.map((variant: string) => [`with neutral variant ${variant}`, { props: { ...props, variant, color: 'neutral' } }]),
    ['with class', { props: { ...props, class: 'rounded-full' } }],
    ['with ui', { props: { ...props, ui: { group: 'p-2' } } }],
    // Slots
    ['with leading slot', { props, slots: { leading: () => 'Leading slot' } }],
    ['with trailing slot', { props, slots: { trailing: () => 'Trailing slot' } }],
    ['with item slot', { props, slots: { item: () => 'Item slot' } }],
    ['with item-leading slot', { props, slots: { 'item-leading': () => 'Item leading slot' } }],
    ['with item-label slot', { props, slots: { 'item-label': () => 'Item label slot' } }],
    ['with item-trailing slot', { props, slots: { 'item-trailing': () => 'Item trailing slot' } }],
  ])('renders %s correctly', async (name, options) => {
    const { html } = render(Select, options)

    await new Promise(resolve => setTimeout(resolve, 0))

    expect(html()).toMatchSnapshot()
  })
})

Contributors

barbapapazes

Changelog

7a9f6 - feat: attrs on form elements (#150) on 2/14/2025
c615c - feat: add custom eslint rule to disallow relative imports (#81) on 1/7/2025
597d4 - feat: add select component (#76) on 12/23/2024