# Select

A button that opens a list of options and shows the selected one.

- Page: https://www.effectcn.com/components/select
- Kind: Headless component with parts
- File: `src/ui/select.ts`
- Built on: `Select` from `@effect/ui-kit`

## Installation

1. Set up the project once: the packages, Tailwind CSS, the theme tokens and the `cn` helper. See [Installation](https://www.effectcn.com/docs/installation.md).
2. Copy the file below to `src/ui/select.ts`. The kit owns behaviour, ARIA and data attributes. This file is the look, written with Tailwind classes, and it is yours to change.
3. Import it.

`src/ui/select.ts`

```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
    ))
  })
```

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

## Usage

By default the popup opens over the trigger, with the selected option on top of the trigger's text.

```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.

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

const regions = [
  {
    key: "americas",
    label: "North America",
    zones: [
      { value: "est", label: "Eastern Time (EST)" },
      { value: "cst", label: "Central Time (CST)" },
      { value: "pst", label: "Pacific Time (PST)" }
    ]
  },
  {
    key: "europe",
    label: "Europe & Africa",
    zones: [
      { value: "gmt", label: "Greenwich Mean Time (GMT)" },
      { value: "cet", label: "Central European Time (CET)" },
      { value: "eet", label: "Eastern European Time (EET)" }
    ]
  },
  {
    key: "asia",
    label: "Asia",
    zones: [
      { value: "ist", label: "India Standard Time (IST)" },
      { value: "jst", label: "Japan Standard Time (JST)" }
    ]
  }
]

const zones = regions.flatMap((region) => region.zones)

const SelectGroupsMessage = UiSchema.TaggedEnum({
  RequestedOpenTimezone: {},
  RequestedCloseTimezone: {},
  PickedTimezone: { timezone: Schema.NullOr(Schema.String) }
})

export const SelectGroups = Html.component({
  name: "SelectGroups",
  model: Schema.Struct({ open: Schema.Boolean, timezone: Schema.NullOr(Schema.String) }),
  message: SelectGroupsMessage
}).make({
  init: () => ({ open: false, timezone: null }),
  update: {
    RequestedOpenTimezone: ($) => $.evolve({ open: true }),
    RequestedCloseTimezone: ($) => $.evolve({ open: false }),
    PickedTimezone: ($, { timezone }) => $.evolve({ timezone })
  },
  view: (h, model) =>
    Select(h, {
      props: {
        open: model.open,
        value: model.timezone,
        items: zones,
        placeholder: "Select a timezone",
        alignItemWithTrigger: false,
        align: "start",
        sideOffset: 6
      },
      onEmit: {
        RequestedOpen: () => SelectGroupsMessage.RequestedOpenTimezone(),
        RequestedClose: () => SelectGroupsMessage.RequestedCloseTimezone(),
        Picked: ({ value }) =>
          SelectGroupsMessage.PickedTimezone({ timezone: typeof value === "string" ? value : null }),
        Settled: () => undefined
      },
      view: (select) =>
        h.div.children(
          SelectTrigger(h, select, { class: "w-64" }).attr("aria-label", "Timezone").children(
              SelectValue(h, select),
              SelectIcon(h, select)
            ),
          SelectPositioner(h, select).children(
            SelectPopup(h, select).children(
              regions.flatMap((region, index) => [
                index > 0 && SelectSeparator(h, select, { key: `separator-${region.key}` }),
                SelectGroup(h, select, { group: region.key }).children(
                  SelectGroupLabel(h, select, { group: region.key }).children(region.label),
                  region.zones.map(({ label, value }) =>
                    SelectItem(h, select, { value }).children(
                      SelectItemText(h, select).children(label),
                      SelectItemIndicator(h, select, { value })
                    )
                  )
                )
              ])
            )
          )
        )
    })
})
```

### Icons and descriptions

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

```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 roles = [
  {
    value: "viewer",
    label: "Viewer",
    description: "Can read and comment.",
    icon: "M2 12s3.6-7 10-7 10 7 10 7-3.6 7-10 7S2 12 2 12zm10 3a3 3 0 100-6 3 3 0 000 6z"
  },
  {
    value: "editor",
    label: "Editor",
    description: "Can edit, but not share or delete.",
    icon: "M12 20h9M16.5 3.5a2.1 2.1 0 013 3L7 19l-4 1 1-4 12.5-12.5z"
  },
  {
    value: "admin",
    label: "Admin",
    description: "Can manage members and billing.",
    icon: "M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"
  },
  {
    value: "owner",
    label: "Owner",
    description: "Full access. Transfer it from the workspace settings.",
    icon: "M3 18h18M4 8l4 4 4-7 4 7 4-4-1.5 10h-13L4 8z",
    disabled: true
  }
]

const SelectRichMessage = UiSchema.TaggedEnum({
  RequestedOpenRole: {},
  RequestedCloseRole: {},
  PickedRole: { role: Schema.String }
})

const icon = <M>(h: Html.H<M>, path: string) =>
  h.el("svg")
    .attrs({
      viewBox: "0 0 24 24",
      fill: "none",
      stroke: "currentColor",
      "stroke-width": "2",
      "stroke-linecap": "round",
      "stroke-linejoin": "round",
      "aria-hidden": "true"
    })
    .children(h.el("path").attr("d", path))

export const SelectRich = Html.component({
  name: "SelectRich",
  model: Schema.Struct({ open: Schema.Boolean, role: Schema.String }),
  message: SelectRichMessage
}).make({
  init: () => ({ open: false, role: "editor" }),
  update: {
    RequestedOpenRole: ($) => $.evolve({ open: true }),
    RequestedCloseRole: ($) => $.evolve({ open: false }),
    PickedRole: ($, { role }) => $.evolve({ role })
  },
  view: (h, model) =>
    Select(h, {
      props: {
        open: model.open,
        value: model.role,
        items: roles.map(({ disabled, label, value }) => ({ value, label, disabled })),
        alignItemWithTrigger: false,
        align: "start",
        sideOffset: 6
      },
      onEmit: {
        RequestedOpen: () => SelectRichMessage.RequestedOpenRole(),
        RequestedClose: () => SelectRichMessage.RequestedCloseRole(),
        Picked: ({ value }) => typeof value === "string" ? SelectRichMessage.PickedRole({ role: value }) : undefined,
        Settled: () => undefined
      },
      view: (select) =>
        h.div.children(
          SelectTrigger(h, select).attr("aria-label", "Role").children(
            SelectValue(h, select),
            SelectIcon(h, select)
          ),
          SelectPositioner(h, select).children(
            SelectPopup(h, select, { class: "w-75" }).children(
              roles.map(({ description, icon: path, label, value }) =>
                SelectItem(h, select, { value, class: "items-start gap-2.5 p-2 [&_svg]:mt-0.5" }).children(
                  icon(h, path),
                  SelectItemText(h, select).children(
                    label,
                    h.span.class("block text-xs font-normal whitespace-normal text-muted-foreground").children(description)
                  ),
                  SelectItemIndicator(h, select, { value, class: "mt-[3px]" })
                )
              )
            )
          )
        )
    })
})
```

### Sizes

Three trigger sizes from a data-size attribute.

```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 sizes = [
  { size: "sm", name: "Small" },
  { size: "default", name: "Default" },
  { size: "lg", name: "Large" }
] as const

const intervals = [
  { value: "day", label: "Last 24 hours" },
  { value: "week", label: "Last 7 days" },
  { value: "month", label: "Last 30 days" },
  { value: "quarter", label: "Last 90 days" }
]

const SelectSizesMessage = UiSchema.TaggedEnum({
  RequestedOpenInterval: { size: Schema.String },
  RequestedCloseInterval: { size: Schema.String },
  PickedInterval: { size: Schema.String, interval: Schema.String }
})

export const SelectSizes = Html.component({
  name: "SelectSizes",
  model: Schema.Struct({
    open: Schema.NullOr(Schema.String),
    intervals: Schema.Record(Schema.String, Schema.String)
  }),
  message: SelectSizesMessage
}).make({
  init: () => ({ open: null, intervals: { sm: "day", default: "week", lg: "month" } }),
  update: {
    RequestedOpenInterval: ($, { size }) => $.evolve({ open: size }),
    RequestedCloseInterval: ($, { size }) => $.model.open === size ? $.evolve({ open: null }) : $.model,
    PickedInterval: ($, { interval, size }) =>
      $.evolve({ intervals: (current) => ({ ...current, [size]: interval }) })
  },
  view: (h, model) =>
    h.div.class("flex flex-wrap items-center gap-2.5").children(
      sizes.map(({ name, size }) =>
        Select(h, {
          key: size,
          props: { open: model.open === size, value: model.intervals[size] ?? null, items: intervals },
          onEmit: {
            RequestedOpen: () => SelectSizesMessage.RequestedOpenInterval({ size }),
            RequestedClose: () => SelectSizesMessage.RequestedCloseInterval({ size }),
            Picked: ({ value }) =>
              typeof value === "string" ? SelectSizesMessage.PickedInterval({ size, interval: value }) : undefined,
            Settled: () => undefined
          },
          view: (select) =>
            h.div.children(
              SelectTrigger(h, select, { size }).attr("aria-label", `${name} interval`).children(
                SelectValue(h, select),
                SelectIcon(h, select)
              ),
              SelectPositioner(h, select).children(
                SelectPopup(h, select, { size }).children(
                  intervals.map(({ label, value }) =>
                    SelectItem(h, select, { value }).children(
                      SelectItemText(h, select).children(label),
                      SelectItemIndicator(h, select, { value })
                    )
                  )
                )
              )
            )
        })
      )
    )
})
```

### 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.

```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, SelectLabel, SelectPopup, SelectPositioner, SelectTrigger, SelectValue } from "#ui/select"

const regions = [
  { value: "fra1", label: "Frankfurt (fra1)" },
  { value: "lhr1", label: "London (lhr1)" },
  { value: "iad1", label: "Washington, D.C. (iad1)", disabled: true },
  { value: "sfo1", label: "San Francisco (sfo1)" },
  { value: "hnd1", label: "Tokyo (hnd1)", disabled: true },
  { value: "syd1", label: "Sydney (syd1)" }
]

const selects = [
  { key: "options", label: "Disabled options", disabled: false, readOnly: false },
  { key: "disabled", label: "Disabled", disabled: true, readOnly: false },
  { key: "read-only", label: "Read-only", disabled: false, readOnly: true }
]

const SelectDisabledMessage = UiSchema.TaggedEnum({
  RequestedOpenRegion: { key: Schema.String },
  RequestedCloseRegion: { key: Schema.String },
  PickedRegion: { region: Schema.String }
})

export const SelectDisabled = Html.component({
  name: "SelectDisabled",
  model: Schema.Struct({ open: Schema.NullOr(Schema.String), region: Schema.String }),
  message: SelectDisabledMessage
}).make({
  init: () => ({ open: null, region: "fra1" }),
  update: {
    RequestedOpenRegion: ($, { key }) => $.evolve({ open: key }),
    RequestedCloseRegion: ($, { key }) => $.model.open === key ? $.evolve({ open: null }) : $.model,
    PickedRegion: ($, { region }) => $.evolve({ region })
  },
  view: (h, model) =>
    h.div.class("flex flex-wrap items-start gap-2.5").children(
      selects.map(({ disabled, key, label, readOnly }) =>
        Select(h, {
          key,
          props: { open: model.open === key, value: model.region, items: regions, disabled, readOnly },
          onEmit: {
            RequestedOpen: () => SelectDisabledMessage.RequestedOpenRegion({ key }),
            RequestedClose: () => SelectDisabledMessage.RequestedCloseRegion({ key }),
            Picked: ({ value }) =>
              typeof value === "string" ? SelectDisabledMessage.PickedRegion({ region: value }) : undefined,
            Settled: () => undefined
          },
          view: (select) =>
            h.div.class("flex flex-col").children(
              SelectLabel(h, select).children(label),
              SelectTrigger(h, select, { class: "w-full" }).children(
                SelectValue(h, select),
                SelectIcon(h, select)
              ),
              SelectPositioner(h, select).children(
                SelectPopup(h, select).children(
                  regions.map(({ label, value }) =>
                    SelectItem(h, select, { value }).children(
                      SelectItemText(h, select).children(label),
                      SelectItemIndicator(h, select, { value })
                    )
                  )
                )
              )
            )
        })
      )
    )
})
```

### Multiple

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

```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, SelectItemCheckbox, SelectItemText, SelectLabel, SelectPopup, SelectPositioner, SelectTrigger, SelectValue } from "#ui/select"

const channels = [
  { value: "email", label: "Email" },
  { value: "push", label: "Push" },
  { value: "sms", label: "SMS" },
  { value: "slack", label: "Slack" },
  { value: "webhook", label: "Webhook" }
]

const SelectMultipleMessage = UiSchema.TaggedEnum({
  RequestedOpenChannels: {},
  RequestedCloseChannels: {},
  PickedChannels: { channels: Schema.Array(Schema.String) }
})

export const SelectMultiple = Html.component({
  name: "SelectMultiple",
  model: Schema.Struct({ open: Schema.Boolean, channels: Schema.Array(Schema.String) }),
  message: SelectMultipleMessage
}).make({
  init: () => ({ open: false, channels: ["email", "slack"] }),
  update: {
    RequestedOpenChannels: ($) => $.evolve({ open: true }),
    RequestedCloseChannels: ($) => $.evolve({ open: false }),
    PickedChannels: ($, { channels }) => $.evolve({ channels })
  },
  view: (h, model) =>
    h.div.class("flex flex-col items-start gap-3.5").children(
      // With `multiple`, a pick toggles the item and leaves the popup open.
      Select(h, {
        props: {
          open: model.open,
          value: model.channels,
          items: channels,
          multiple: true,
          placeholder: "No channels",
          alignItemWithTrigger: false,
          align: "start",
          sideOffset: 6
        },
        onEmit: {
          RequestedOpen: () => SelectMultipleMessage.RequestedOpenChannels(),
          RequestedClose: () => SelectMultipleMessage.RequestedCloseChannels(),
          Picked: ({ value }) =>
            SelectMultipleMessage.PickedChannels({ channels: Array.isArray(value) ? value : [] }),
          Settled: () => undefined
        },
        view: (select) =>
          h.div.class("flex w-60 flex-col").children(
            SelectLabel(h, select).children("Notify me by"),
            SelectTrigger(h, select, { class: "w-full" }).children(
              SelectValue(h, select),
              SelectIcon(h, select)
            ),
            SelectPositioner(h, select).children(
              SelectPopup(h, select).children(
                channels.map(({ label, value }) =>
                  SelectItem(h, select, { value }).children(
                    SelectItemCheckbox(h),
                    SelectItemText(h, select).children(label)
                  )
                )
              )
            )
          )
      }),
      h.p.class("text-xs text-muted-foreground tabular-nums").children(`${model.channels.length} of ${channels.length} channels on`)
    )
})
```

### Scrollable

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

```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, SelectList, SelectPopup, SelectPositioner, SelectScrollDownArrow, SelectScrollUpArrow, SelectTrigger, SelectValue } from "#ui/select"

const countries = [
  "Argentina", "Australia", "Austria", "Belgium", "Brazil", "Canada", "Chile", "Colombia", "Czechia", "Denmark",
  "Egypt", "Estonia", "Finland", "France", "Germany", "Greece", "Hungary", "Iceland", "India", "Indonesia",
  "Ireland", "Italy", "Japan", "Kenya", "Latvia", "Lithuania", "Mexico", "Morocco", "Netherlands", "New Zealand",
  "Nigeria", "Norway", "Peru", "Poland", "Portugal", "Romania", "Singapore", "South Africa", "South Korea",
  "Spain", "Sweden", "Switzerland", "Thailand", "Turkey", "Ukraine", "United Kingdom", "United States", "Vietnam"
].map((label) => ({ value: label.toLowerCase().replaceAll(" ", "-"), label }))

const SelectScrollableMessage = UiSchema.TaggedEnum({
  RequestedOpenCountry: {},
  RequestedCloseCountry: {},
  PickedCountry: { country: Schema.String }
})

export const SelectScrollable = Html.component({
  name: "SelectScrollable",
  model: Schema.Struct({ open: Schema.Boolean, country: Schema.String }),
  message: SelectScrollableMessage
}).make({
  init: () => ({ open: false, country: "norway" }),
  update: {
    RequestedOpenCountry: ($) => $.evolve({ open: true }),
    RequestedCloseCountry: ($) => $.evolve({ open: false }),
    PickedCountry: ($, { country }) => $.evolve({ country })
  },
  view: (h, model) =>
    Select(h, {
      props: { open: model.open, value: model.country, items: countries },
      onEmit: {
        RequestedOpen: () => SelectScrollableMessage.RequestedOpenCountry(),
        RequestedClose: () => SelectScrollableMessage.RequestedCloseCountry(),
        Picked: ({ value }) =>
          typeof value === "string" ? SelectScrollableMessage.PickedCountry({ country: value }) : undefined,
        Settled: () => undefined
      },
      view: (select) =>
        h.div.children(
          SelectTrigger(h, select).attr("aria-label", "Country").children(
            SelectValue(h, select),
            SelectIcon(h, select)
          ),
          SelectPositioner(h, select).children(
            SelectPopup(h, select).children(
              // The arrows show while there is more to scroll, and scroll while the pointer is over them.
              SelectScrollUpArrow(h, select),
              SelectList(h, select).children(
                countries.map(({ label, value }) =>
                  SelectItem(h, select, { value }).children(
                    SelectItemText(h, select).children(label),
                    SelectItemIndicator(h, select, { value })
                  )
                )
              ),
              SelectScrollDownArrow(h, select)
            )
          )
        )
    })
})
```

### In a form

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

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

const priorities = [
  { value: "low", label: "Low" },
  { value: "medium", label: "Medium" },
  { value: "high", label: "High" },
  { value: "urgent", label: "Urgent" }
]

const SelectFormMessage = UiSchema.TaggedEnum({
  RequestedOpenPriority: {},
  RequestedClosePriority: {},
  PickedPriority: { priority: Schema.NullOr(Schema.String) },
  SubmittedForm: { priority: Schema.String }
})

export const SelectForm = Html.component({
  name: "SelectForm",
  model: Schema.Struct({
    open: Schema.Boolean,
    priority: Schema.NullOr(Schema.String),
    submitted: Schema.NullOr(Schema.String)
  }),
  message: SelectFormMessage
}).make({
  init: () => ({ open: false, priority: null, submitted: null }),
  update: {
    RequestedOpenPriority: ($) => $.evolve({ open: true }),
    RequestedClosePriority: ($) => $.evolve({ open: false }),
    PickedPriority: ($, { priority }) => $.evolve({ priority }),
    SubmittedForm: ($, { priority }) => $.evolve({ submitted: priority })
  },
  view: (h, model) =>
    h.form
      .class("flex w-full max-w-90 flex-col gap-3.5")
      .on("submit", ({ fields }) => SelectFormMessage.SubmittedForm({ priority: fields.priority ?? "" }))
      .children(
        // `name` and `required` add a hidden input next to the trigger, so the form validates and submits it.
        Select(h, {
          props: {
            open: model.open,
            value: model.priority,
            items: priorities,
            placeholder: "Choose a priority",
            name: "priority",
            required: true
          },
          onEmit: {
            RequestedOpen: () => SelectFormMessage.RequestedOpenPriority(),
            RequestedClose: () => SelectFormMessage.RequestedClosePriority(),
            Picked: ({ value }) =>
              SelectFormMessage.PickedPriority({ priority: typeof value === "string" ? value : null }),
            Settled: () => undefined
          },
          view: (select) =>
            h.div.class("flex flex-col").children(
              SelectLabel(h, select).children("Priority"),
              SelectTrigger(h, select, { class: "w-full" }).children(
                SelectValue(h, select),
                SelectIcon(h, select)
              ),
              h.p.class("mt-1.5 text-xs text-muted-foreground").children("Urgent issues page the on-call engineer."),
              SelectPositioner(h, select).children(
                SelectPopup(h, select).children(
                  priorities.map(({ label, value }) =>
                    SelectItem(h, select, { value }).children(
                      SelectItemText(h, select).children(label),
                      SelectItemIndicator(h, select, { value })
                    )
                  )
                )
              )
            )
        }),
        h.div.class("flex flex-wrap items-center gap-2.5").children(
          Button(h, { props: { type: "submit" } }).children("Create issue"),
          h.p.class("text-xs text-muted-foreground tabular-nums").children(
            model.submitted === null ? "Nothing submitted yet" : `Submitted priority=${model.submitted}`
          )
        )
      )
})
```

## Anatomy

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

| Part | Description |
| --- | --- |
| `label` | A <div> that names the trigger. A click focuses the trigger without opening. |
| `trigger` | The <button> that opens the popup. |
| `value` | A <span> in the trigger, filled with the selected label or the placeholder. |
| `icon` | A <span> in the trigger, for a chevron. |
| `backdrop` | A <div> under the positioner, in the top layer. |
| `positioner` | A <div> the select places, a manual popover in the top layer. |
| `popup` | A <div> in the positioner: the listbox, and the box to style. |
| `list` | A <div> in the popup that scrolls, when the popup holds more than items. |
| `item({ element, value })` | A <div> per option, keyed by its value. |
| `itemText` | A <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. |
| `separator` | A <div> between items or groups. |
| `scrollUpArrow / scrollDownArrow({ element })` | A <div> in the popup, drawn while the list can scroll that way. |
| `arrow` | A <div> in the popup that points at the trigger. Hidden while the popup covers it. |

## API reference

### Props

| Prop | Type | Description |
| --- | --- | --- |
| `open` | `boolean` | Whether the popup shows. Required: the consumer owns it. |
| `items` | `ReadonlyArray<{ value, label, disabled? }>` | Every option in drawing order. Navigation, typeahead and the trigger's text read them. |
| `value` | `string \| ReadonlyArray<string> \| null` | The selected value, or the values with multiple. |
| `multiple` | `boolean` | More than one option can be selected. Default false. |
| `placeholder` | `string` | The trigger's text while nothing is selected. |
| `disabled / readOnly / required` | `boolean` | As on a native <select>. |
| `name / form / autoComplete` | `string` | Adds a hidden input, so a form submits it. |
| `alignItemWithTrigger` | `boolean` | The popup covers the trigger with the selected item over its text. Default true. |
| `side / align / sideOffset / alignOffset` | `Positioning` | Where the popup goes when it isn't aligned with the trigger. side defaults to "bottom". |
| `modal` | `boolean` | While open, the page doesn't scroll and a press outside only closes. Default true. |
| `highlightItemOnHover` | `boolean` | The pointer highlights items. Default true. |

### Events

| Event | Description |
| --- | --- |
| `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

| Attribute | Description |
| --- | --- |
| `data-popup-open` | On the trigger and the icon while the popup is open. |
| `data-placeholder` | On the trigger and the value while nothing is selected. |
| `data-disabled / data-readonly / data-required` | On the trigger, from the props. |
| `data-open / data-closed` | On the backdrop, the positioner and the popup. |
| `data-starting-style / data-ending-style` | On the popup for the first frame after it opens, and while it closes. |
| `data-side / data-align` | On the positioner and the popup: where it ended up. data-side is "none" while it covers the trigger. |
| `data-selected` | On the selected items. |
| `data-highlighted` | On the item with focus. |
| `data-disabled` | On a disabled item. |
| `--anchor-width / --available-height` | CSS variables on the positioner, for sizing the popup. |
| `--transform-origin` | CSS variable on the popup: the point it grows from. |

## Related components

- [Button](https://www.effectcn.com/components/button.md): A native button that can stay focusable while disabled.
