Installation

  1. Set up the project

    Once per project: the packages, Tailwind CSS, the theme tokens and the cn helper. Follow Installation.

  2. Copy the component into your project

    The kit owns behaviour, ARIA and data attributes. This file is the look, written with Tailwind classes, and it is yours to change.

    src/ui/select.ts
    import type { Component } from "@effect/ui"
    import type { Html } from "@effect/ui/html"
    import type { Select } from "@effect/ui-kit"
    import { cn } from "#lib/cn"
    
    /** What the `view` closure of the kit's `Select` receives. */
    export type SelectParts = Component.Headless.Parts<typeof Select>
    
    export type SelectSize = keyof typeof triggerSizes
    
    interface ClassOption {
      readonly class?: string | undefined
    }
    
    const triggerSizes = {
      sm: "h-7 min-w-36 gap-1.5 rounded-sm pr-2 pl-2.5 text-xs",
      default: "h-8.5 min-w-48 pr-2.5 pl-3 text-[13px]",
      lg: "h-10 min-w-56 pr-3 pl-3.5 text-sm"
    } as const
    
    const popupSizes = {
      sm: "text-xs [&_[role=option]]:min-h-6.5 [&_[role=option]]:px-1.5 [&_[role=option]]:py-0.5",
      default: "text-[13px]",
      lg: "text-sm [&_[role=option]]:min-h-8.5 [&_[role=option]]:px-2.5"
    } as const
    
    /** The text above the trigger. It names the trigger, and a click focuses it. */
    export const SelectLabel = <Msg>(h: Html.H<Msg>, select: SelectParts, options: ClassOption = {}) =>
      select.label(h.div.class(cn("mb-1.5 cursor-default text-[13px] leading-snug font-medium", options.class)))
    
    /** The button that opens the popup. Put `SelectValue` and `SelectIcon` inside. */
    export const SelectTrigger = <Msg>(
      h: Html.H<Msg>,
      select: SelectParts,
      options: ClassOption & { readonly size?: SelectSize | undefined } = {}
    ) =>
      select.trigger(
        // The press opens the popup and the kit moves focus into it. Left alone, the browser would then focus the
        // pressed button, and the kit closes a popup that covers its trigger when the trigger takes focus.
        h.button.on("mousedown", () => undefined, { preventDefault: "always" }).class(cn(
          "inline-flex items-center justify-between gap-2 rounded-md border border-input bg-background text-start",
          "leading-none whitespace-nowrap text-foreground shadow-sm select-none",
          "transition-colors duration-150 hover:bg-accent data-[popup-open]:bg-accent",
          "data-[disabled]:cursor-not-allowed data-[disabled]:opacity-50 data-[disabled]:hover:bg-background",
          "data-[readonly]:cursor-default data-[readonly]:bg-muted",
          triggerSizes[options.size ?? "default"],
          options.class
        ))
      )
    
    /** The selected label, or the placeholder, inside the trigger. */
    export const SelectValue = <Msg>(h: Html.H<Msg>, select: SelectParts, options: ClassOption = {}) =>
      select.value(
        h.span.class(cn("min-w-0 truncate leading-snug data-[placeholder]:text-muted-foreground", options.class))
      )
    
    /** The chevron inside the trigger. */
    export const SelectIcon = <Msg>(h: Html.H<Msg>, select: SelectParts, options: ClassOption = {}) =>
      select.icon(
        h.span.class(cn(
          "mx-1 mb-[3px] size-[7px] shrink-0 rotate-45 border-r-[1.5px] border-b-[1.5px] border-muted-foreground",
          options.class
        ))
      )
    
    /**
     * The element the kit places, in the top layer. Put `SelectPopup` inside. Its
     * vertical margin is the gap the kit keeps to the viewport's edges while the
     * popup covers the trigger.
     */
    export const SelectPositioner = <Msg>(h: Html.H<Msg>, select: SelectParts, options: ClassOption = {}) =>
      select.positioner(h.div.class(cn("outline-none data-[side=none]:my-2.5", options.class)))
    
    /**
     * The box with the options. Over the trigger (`data-side="none"`) it only
     * fades and has no `max-height`: the kit measures it to line the selected
     * option up with the trigger's text, and a scale or a cap would throw that
     * off. Next to the trigger it also scales and stops at 20rem.
     */
    export const SelectPopup = <Msg>(
      h: Html.H<Msg>,
      select: SelectParts,
      options: ClassOption & { readonly size?: SelectSize | undefined } = {}
    ) =>
      select.popup(
        h.div.class(cn(
          "relative box-border max-w-[var(--available-width)] min-w-[max(var(--anchor-width),10rem)] overflow-y-auto",
          "rounded-lg border bg-popover p-1 text-foreground shadow-float outline-none",
          "max-h-[min(var(--available-height),20rem)] data-[side=none]:max-h-none",
          "origin-[var(--transform-origin)] transition-[opacity,scale] duration-150",
          "data-[starting-style]:opacity-0 data-[ending-style]:opacity-0",
          "not-data-[side=none]:data-[starting-style]:scale-95 not-data-[side=none]:data-[ending-style]:scale-95",
          "data-[side=none]:[scrollbar-width:none]",
          "has-[>[data-slot=select-list]]:flex has-[>[data-slot=select-list]]:flex-col",
          "has-[>[data-slot=select-list]]:overflow-hidden has-[>[data-slot=select-list]]:p-0",
          popupSizes[options.size ?? "default"],
          options.class
        ))
      )
    
    /** The scrolling part of a popup that also holds scroll arrows. */
    export const SelectList = <Msg>(h: Html.H<Msg>, select: SelectParts, options: ClassOption = {}) =>
      select.list(
        h.div.attr("data-slot", "select-list").class(
          cn("min-h-0 flex-1 overflow-y-auto p-1 outline-none [scrollbar-width:none]", options.class)
        )
      )
    
    /** One option. Put `SelectItemText` and `SelectItemIndicator` inside. */
    export const SelectItem = <Msg>(
      h: Html.H<Msg>,
      select: SelectParts,
      options: ClassOption & { readonly value: string }
    ) =>
      select.item({
        element: h.div.class(cn(
          "flex min-h-7.5 cursor-default scroll-my-1 items-center gap-2 rounded-sm px-2 py-1 leading-snug outline-none",
          "select-none data-[highlighted]:bg-accent data-[highlighted]:text-accent-foreground",
          "data-[selected]:font-medium data-[disabled]:text-muted-foreground data-[disabled]:opacity-60",
          "[&_svg]:size-[15px] [&_svg]:shrink-0 [&_svg]:text-muted-foreground",
          options.class
        )),
        value: options.value
      })
    
    /** The option's label, which the kit lines up with the trigger's text. */
    export const SelectItemText = <Msg>(h: Html.H<Msg>, select: SelectParts, options: ClassOption = {}) =>
      select.itemText(h.div.class(cn("min-w-0 flex-1 whitespace-nowrap", options.class)))
    
    /** The tick of a selected option. `undefined` for the others. */
    export const SelectItemIndicator = <Msg>(
      h: Html.H<Msg>,
      select: SelectParts,
      options: ClassOption & { readonly value: string }
    ) =>
      select.itemIndicator({
        element: h.span.class(cn(
          "mr-1.5 mb-0.5 ml-2.5 h-[9px] w-[5px] shrink-0 rotate-45 border-r-[1.5px] border-b-[1.5px] border-brand",
          options.class
        )),
        value: options.value
      })
    
    /** A checkbox in front of an option's label, for a `multiple` select. */
    export const SelectItemCheckbox = <Msg>(h: Html.H<Msg>, options: ClassOption = {}) =>
      h.span.attr("aria-hidden", "true").class(cn(
        "grid size-[15px] shrink-0 place-items-center rounded-xs border border-input bg-background transition-colors",
        "duration-150 in-data-[selected]:border-brand in-data-[selected]:bg-brand",
        "in-data-[selected]:before:mb-0.5 in-data-[selected]:before:h-2 in-data-[selected]:before:w-1",
        "in-data-[selected]:before:rotate-45 in-data-[selected]:before:border-r-[1.5px]",
        "in-data-[selected]:before:border-b-[1.5px] in-data-[selected]:before:border-brand-foreground",
        options.class
      ))
    
    /** A run of options under a `SelectGroupLabel`. */
    export const SelectGroup = <Msg>(
      h: Html.H<Msg>,
      select: SelectParts,
      options: ClassOption & { readonly group: string }
    ) => select.group({ element: h.div.key(options.group).class(cn(options.class)), group: options.group })
    
    export const SelectGroupLabel = <Msg>(
      h: Html.H<Msg>,
      select: SelectParts,
      options: ClassOption & { readonly group: string }
    ) =>
      select.groupLabel({
        element: h.div.class(cn("px-2 pt-1.5 pb-1 text-xs font-medium text-muted-foreground", options.class)),
        group: options.group
      })
    
    export const SelectSeparator = <Msg>(
      h: Html.H<Msg>,
      select: SelectParts,
      options: ClassOption & { readonly key?: string | undefined } = {}
    ) => {
      const element = h.div.class(cn("-mx-1 my-1 h-px bg-border", options.class))
      return select.separator(options.key === undefined ? element : element.key(options.key))
    }
    
    // The arrows stay mounted and show on `data-visible`: an arrow that came and went in front of the list would
    // shift the list's place among the popup's children, and the list would be built again, losing its scroll.
    const scrollArrow =
      "inset-x-0 z-10 hidden h-6 cursor-default place-items-center rounded-lg bg-popover data-[visible]:grid " +
      "before:size-1.5 before:rotate-45 before:border-muted-foreground"
    
    /** Shown while the list can scroll up. Hovering it scrolls. Needs `SelectList`. */
    export const SelectScrollUpArrow = <Msg>(h: Html.H<Msg>, select: SelectParts, options: ClassOption = {}) =>
      select.scrollUpArrow({
        keepMounted: true,
        element: h.div.class(cn(
          scrollArrow,
          "top-0 before:translate-y-0.5 before:border-t-[1.5px] before:border-l-[1.5px]",
          options.class
        ))
      })
    
    /** Shown while the list can scroll down. Hovering it scrolls. Needs `SelectList`. */
    export const SelectScrollDownArrow = <Msg>(h: Html.H<Msg>, select: SelectParts, options: ClassOption = {}) =>
      select.scrollDownArrow({
        keepMounted: true,
        element: h.div.class(cn(
          scrollArrow,
          "bottom-0 before:-translate-y-0.5 before:border-r-[1.5px] before:border-b-[1.5px]",
          options.class
        ))
      })
    
  3. Import it

    import { SelectLabel, SelectTrigger, SelectValue, SelectIcon, SelectPositioner, SelectPopup, SelectList, SelectItem, SelectItemText, SelectItemIndicator, SelectItemCheckbox, SelectGroup, SelectGroupLabel, SelectSeparator, SelectScrollUpArrow, SelectScrollDownArrow } from "#ui/select"
    

Usage

Basic.ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Select } from "@effect/ui-kit"
import { Schema } from "effect"
import { SelectIcon, SelectItem, SelectItemIndicator, SelectItemText, SelectPopup, SelectPositioner, SelectTrigger, SelectValue } from "#ui/select"

const fruits = [
  { value: "apple", label: "Apple" },
  { value: "banana", label: "Banana" },
  { value: "blueberry", label: "Blueberry" },
  { value: "grapes", label: "Grapes" },
  { value: "pineapple", label: "Pineapple" }
]

const SelectBasicMessage = UiSchema.TaggedEnum({
  RequestedOpenFruit: {},
  RequestedCloseFruit: {},
  PickedFruit: { fruit: Schema.NullOr(Schema.String) }
})

export const SelectBasic = Html.component({
  name: "SelectBasic",
  model: Schema.Struct({ open: Schema.Boolean, fruit: Schema.NullOr(Schema.String) }),
  message: SelectBasicMessage
}).make({
  init: () => ({ open: false, fruit: null }),
  update: {
    RequestedOpenFruit: ($) => $.evolve({ open: true }),
    RequestedCloseFruit: ($) => $.evolve({ open: false }),
    PickedFruit: ($, { fruit }) => $.evolve({ fruit })
  },
  view: (h, model) =>
    Select(h, {
      props: { open: model.open, value: model.fruit, items: fruits, placeholder: "Select a fruit" },
      onEmit: {
        RequestedOpen: () => SelectBasicMessage.RequestedOpenFruit(),
        RequestedClose: () => SelectBasicMessage.RequestedCloseFruit(),
        Picked: ({ value }) => SelectBasicMessage.PickedFruit({ fruit: typeof value === "string" ? value : null }),
        Settled: () => undefined
      },
      view: (select) =>
        h.div.children(
          SelectTrigger(h, select).attr("aria-label", "Fruit").children(
            SelectValue(h, select),
            SelectIcon(h, select)
          ),
          SelectPositioner(h, select).children(
            SelectPopup(h, select).children(
              fruits.map(({ label, value }) =>
                SelectItem(h, select, { value }).children(
                  SelectItemText(h, select).children(label),
                  SelectItemIndicator(h, select, { value })
                )
              )
            )
          )
        )
    })
})

Examples

Groups and labels

Options in labelled groups with separators. With alignItemWithTrigger off, the popup drops below the trigger and flips when it doesn't fit.

Icons and descriptions

An item is your markup: the trigger shows the label from items, the option shows what you draw.

Sizes

Three trigger sizes from a data-size attribute.

Disabled and read-only

Disabled options take keyboard focus but can't be picked. A read-only select opens and can be browsed, not changed.

Disabled options
Disabled
Read-only

Multiple

Picking toggles an option and keeps the popup open. The value is an array.

Notify me by

2 of 5 channels on

Scrollable

A long list scrolls inside the list part, with arrows that scroll on hover.

In a form

With name and required, the select validates and submits like a native one.

Priority

Urgent issues page the on-call engineer.

Nothing submitted yet

Anatomy

The parts the view closure receives. Apply each one to an element of your own.

PartDescription
labelA <div> that names the trigger. A click focuses the trigger without opening.
triggerThe <button> that opens the popup.
valueA <span> in the trigger, filled with the selected label or the placeholder.
iconA <span> in the trigger, for a chevron.
backdropA <div> under the positioner, in the top layer.
positionerA <div> the select places, a manual popover in the top layer.
popupA <div> in the positioner: the listbox, and the box to style.
listA <div> in the popup that scrolls, when the popup holds more than items.
item({ element, value })A <div> per option, keyed by its value.
itemTextA <div> in an item: its label, lined up with the trigger's text.
itemIndicator({ element, value })A <span> in an item, undefined unless the item is selected or keepMounted is set.
group({ element, group })A <div> around related items.
groupLabel({ element, group })A <div> in a group that names it.
separatorA <div> between items or groups.
scrollUpArrow / scrollDownArrow({ element })A <div> in the popup, drawn while the list can scroll that way.
arrowA <div> in the popup that points at the trigger. Hidden while the popup covers it.

API reference

Props

PropTypeDescription
openbooleanWhether the popup shows. Required: the consumer owns it.
itemsReadonlyArray<{ value, label, disabled? }>Every option in drawing order. Navigation, typeahead and the trigger's text read them.
valuestring | ReadonlyArray<string> | nullThe selected value, or the values with multiple.
multiplebooleanMore than one option can be selected. Default false.
placeholderstringThe trigger's text while nothing is selected.
disabled / readOnly / requiredbooleanAs on a native <select>.
name / form / autoCompletestringAdds a hidden input, so a form submits it.
alignItemWithTriggerbooleanThe popup covers the trigger with the selected item over its text. Default true.
side / align / sideOffset / alignOffsetPositioningWhere the popup goes when it isn't aligned with the trigger. side defaults to "bottom".
modalbooleanWhile open, the page doesn't scroll and a press outside only closes. Default true.
highlightItemOnHoverbooleanThe pointer highlights items. Default true.

Events

EventDescription
RequestedOpen({ reason })Asks for open to be true.
RequestedClose({ reason })Asks for open to be false.
Picked({ value, reason })Asks for value to be the whole new selection.
Settled({ open })The popup's transitions ended after it opened or closed.

Data attributes

AttributeDescription
data-popup-openOn the trigger and the icon while the popup is open.
data-placeholderOn the trigger and the value while nothing is selected.
data-disabled / data-readonly / data-requiredOn the trigger, from the props.
data-open / data-closedOn the backdrop, the positioner and the popup.
data-starting-style / data-ending-styleOn the popup for the first frame after it opens, and while it closes.
data-side / data-alignOn the positioner and the popup: where it ended up. data-side is "none" while it covers the trigger.
data-selectedOn the selected items.
data-highlightedOn the item with focus.
data-disabledOn a disabled item.
--anchor-width / --available-heightCSS variables on the positioner, for sizing the popup.
--transform-originCSS variable on the popup: the point it grows from.

The components this page's file and examples import.

  • Button: A native button that can stay focusable while disabled.

effectcn is built with Effect UI and @effect/ui-kit. Not affiliated with Effectful Technologies.