# Select

> Field that opens a menu of choices anchored under it, plus a compact pop-up button for view settings next to a title.

Docs: https://plumbago.ochotzas.com/components/select

## Installation

```sh
npx plumbago add select
```

This copies `components/ui/select.tsx` into your project, along with `cn`, `morph`, `island`, and installs `@base-ui/react`.

## Usage

```tsx
import { Select, SelectContent, SelectItem, SelectLabel, SelectTrigger } from "@/components/ui/select"

<Select items={{ daily: "Every day", weekly: "Every week" }} defaultValue="daily">
  <SelectLabel>Repeat</SelectLabel>
  <SelectTrigger />
  <SelectContent>
    <SelectItem value="daily">Every day</SelectItem>
    <SelectItem value="weekly">Every week</SelectItem>
  </SelectContent>
</Select>
```

## Examples

### Preview

```tsx
import { Select, SelectContent, SelectItem, SelectLabel, SelectTrigger } from "@/components/ui/select"

const repeats = {
  never: "Never",
  daily: "Every day",
  weekdays: "Weekdays",
  weekly: "Every week",
  monthly: "Every month",
}

export default function SelectDemo() {
  return (
    <div className="flex w-full max-w-sm flex-col gap-2">
      <Select items={repeats} defaultValue="weekdays">
        <SelectLabel>Repeat</SelectLabel>
        <SelectTrigger />
        <SelectContent>
          {Object.entries(repeats).map(([value, label]) => (
            <SelectItem key={value} value={value}>
              {label}
            </SelectItem>
          ))}
        </SelectContent>
      </Select>
    </div>
  )
}
```

### Groups

```tsx
import { Select, SelectContent, SelectGroup, SelectGroupLabel, SelectItem, SelectLabel, SelectSeparator, SelectTrigger } from "@/components/ui/select"

const courses = [
  { label: "Starters", dishes: { burrata: "Burrata, peach, basil", soup: "Chilled tomato soup" } },
  { label: "Mains", dishes: { risotto: "Wild mushroom risotto", bream: "Grilled sea bream" } },
  { label: "Desserts", dishes: { tart: "Lemon tart", affogato: "Affogato" } },
]

const dishLabels: Record<string, string> = Object.assign({}, ...courses.map((course) => course.dishes))

export default function SelectGroups() {
  return (
    <div className="flex w-full max-w-sm flex-col gap-2">
      <Select items={dishLabels}>
        <SelectLabel>Dish of the day</SelectLabel>
        <SelectTrigger placeholder="Choose a dish" />
        <SelectContent>
          {courses.map((course, index) => (
            <SelectGroup key={course.label}>
              {index > 0 && <SelectSeparator />}
              <SelectGroupLabel>{course.label}</SelectGroupLabel>
              {Object.entries(course.dishes).map(([value, label]) => (
                <SelectItem key={value} value={value}>
                  {label}
                </SelectItem>
              ))}
            </SelectGroup>
          ))}
        </SelectContent>
      </Select>
    </div>
  )
}
```

### Pop-up button

```tsx
import { Island, ListRow, ListRowText, ListRowTitle, ListRowValue } from "@/components/ui/island"
import { Select, SelectContent, SelectItem, SelectTrigger } from "@/components/ui/select"
import { useState } from "react"

const sorts = { popular: "Popularity", name: "Name", price: "Price" }

type Sort = keyof typeof sorts

const dishes = [
  { name: "Grilled sea bream", price: 24, orders: 41 },
  { name: "Burrata, peach, basil", price: 12, orders: 58 },
  { name: "Wild mushroom risotto", price: 19, orders: 33 },
  { name: "Lemon tart", price: 8, orders: 47 },
]

const orderBy: Record<Sort, (a: (typeof dishes)[number], b: (typeof dishes)[number]) => number> = {
  popular: (a, b) => b.orders - a.orders,
  name: (a, b) => a.name.localeCompare(b.name),
  price: (a, b) => a.price - b.price,
}

export default function SelectPopUpButton() {
  const [sort, setSort] = useState<Sort>("popular")
  const sorted = [...dishes].sort(orderBy[sort])
  return (
    <div className="flex w-full max-w-md flex-col gap-3">
      <div className="flex items-center justify-between gap-3 px-1">
        <h3 className="text-title2 font-bold text-ink">Menu</h3>
        <Select variant="popup" items={sorts} value={sort} onValueChange={(value) => value && setSort(value)}>
          <SelectTrigger aria-label="Sort dishes">{(value: Sort) => `Sort: ${sorts[value]}`}</SelectTrigger>
          <SelectContent>
            {Object.entries(sorts).map(([value, label]) => (
              <SelectItem key={value} value={value}>
                {label}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
      </div>
      <Island variant="list" key={sort}>
        {sorted.map((dish, index) => (
          <ListRow
            key={dish.name}
            style={{ transitionDelay: `${index * 30}ms` }}
            className="transition-[opacity,filter,translate,scale] duration-spring ease-spring starting:opacity-0 motion-safe:starting:translate-y-1.5 motion-safe:starting:scale-98 motion-safe:starting:blur-[8px]"
          >
            <ListRowText>
              <ListRowTitle>{dish.name}</ListRowTitle>
            </ListRowText>
            <ListRowValue className="tabular-nums">€{dish.price}</ListRowValue>
          </ListRow>
        ))}
      </Island>
    </div>
  )
}
```

### In a settings row

```tsx
import { Island, IslandLabel } from "@/components/ui/island"
import { Select, SelectContent, SelectItem, SelectTrigger } from "@/components/ui/select"

const slots = { 15: "Every 15 min", 30: "Every 30 min", 60: "Every hour" }
const turns = { 75: "75 min", 90: "90 min", 120: "2 hours" }

export default function SelectInASettingsRow() {
  return (
    <div className="w-full max-w-md">
      <IslandLabel>Bookings</IslandLabel>
      <Island variant="list">
        <Select variant="row" items={slots} defaultValue="15">
          <SelectTrigger title="Reservations" />
          <SelectContent>
            {Object.entries(slots).map(([value, label]) => (
              <SelectItem key={value} value={value}>
                {label}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
        <Select variant="row" items={turns} defaultValue="90">
          <SelectTrigger title="Table turn" />
          <SelectContent>
            {Object.entries(turns).map(([value, label]) => (
              <SelectItem key={value} value={value}>
                {label}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
      </Island>
    </div>
  )
}
```

### Disabled

```tsx
import { Select, SelectContent, SelectItem, SelectLabel, SelectTrigger } from "@/components/ui/select"

export default function SelectDisabled() {
  return (
    <div className="flex w-full max-w-sm flex-col gap-2">
      <Select items={{ sunday: "Sunday" }} defaultValue="sunday" disabled>
        <SelectLabel>Closed on</SelectLabel>
        <SelectTrigger />
        <SelectContent>
          <SelectItem value="sunday">Sunday</SelectItem>
        </SelectContent>
      </Select>
      <p className="ml-1 text-footnote font-medium text-ink-2">Set by the owner of Casa Verde.</p>
    </div>
  )
}
```

## Built on Base UI

Select wraps these Base UI parts and keeps their props:

- [Select](https://base-ui.com/react/components/select)

## Source

```tsx
import { Select as BaseSelect } from "@base-ui/react/select"
import { cn } from "@/lib/cn"
import { morphColor, morphFromTrigger, morphPanel } from "@/lib/morph"
import { ListRow } from "@/components/ui/island"
import {
  type ComponentProps,
  type CSSProperties,
  createContext,
  type ReactNode,
  type RefObject,
  useContext,
  useId,
  useLayoutEffect,
  useMemo,
  useRef,
  useState,
} from "react"

export type SelectVariant = "field" | "popup" | "row"

type SelectItems = Record<string, ReactNode> | ReadonlyArray<{ value: unknown; label: ReactNode }>

type SelectContextValue = { variant: SelectVariant; items: SelectItems | undefined; anchor: RefObject<HTMLSpanElement | null> }

const SelectContext = createContext<SelectContextValue>({ variant: "field", items: undefined, anchor: { current: null } })

export type SelectProps<Value, Multiple extends boolean | undefined = false> = BaseSelect.Root.Props<Value, Multiple> & {
  variant?: SelectVariant
}

export function Select<Value, Multiple extends boolean | undefined = false>({ variant = "field", ...props }: SelectProps<Value, Multiple>) {
  const anchor = useRef<HTMLSpanElement | null>(null)
  const items = props.items as SelectItems | undefined
  const context = useMemo(() => ({ variant, items, anchor }), [variant, items])
  return (
    <SelectContext.Provider value={context}>
      <BaseSelect.Root {...props} />
    </SelectContext.Provider>
  )
}

function labelOf(items: SelectItems | undefined, value: unknown): ReactNode {
  if (Array.isArray(value)) return value.map((entry) => labelOf(items, entry)).join(", ")
  if (!items) return value == null ? null : String(value)
  if (Array.isArray(items)) return items.find((item) => item.value === value)?.label ?? null
  return typeof value === "string" ? ((items as Record<string, ReactNode>)[value] ?? null) : null
}

function isEmpty(value: unknown) {
  return value == null || (Array.isArray(value) && value.length === 0)
}

export type SelectLabelProps = Omit<ComponentProps<typeof BaseSelect.Label>, "className"> & {
  className?: string
}

export function SelectLabel({ className, ...props }: SelectLabelProps) {
  return <BaseSelect.Label data-slot="select-label" className={cn("ml-1 text-footnote font-medium text-ink-2", className)} {...props} />
}

export type SelectTriggerProps = Omit<ComponentProps<typeof BaseSelect.Trigger>, "className" | "children"> & {
  placeholder?: ReactNode
  title?: ReactNode
  children?: ComponentProps<typeof BaseSelect.Value>["children"]
  className?: string
}

const triggerStyles: Record<SelectVariant, string> = {
  field: cn(
    "group/trigger flex h-11 w-full items-center justify-between gap-2 rounded-md bg-fill-field pr-3 pl-4 text-left text-body text-ink",
    "transition-shadow duration-fast ease-out focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent data-popup-open:ring-2 data-popup-open:ring-accent",
    "data-disabled:cursor-default data-disabled:opacity-40",
  ),
  popup: cn(
    "relative inline-flex h-9 items-center rounded-full bg-fill-secondary text-[15px] font-medium whitespace-nowrap text-ink",
    "after:absolute after:inset-x-0 after:-inset-y-1",
    "transition-control hover:not-data-disabled:bg-[color-mix(in_srgb,var(--pb-fill-secondary),var(--pb-ink)_7%)]",
    "active:not-data-disabled:scale-press active:not-data-disabled:duration-[90ms] data-disabled:cursor-default data-disabled:opacity-40",
  ),
  row: "data-popup-open:bg-press data-disabled:cursor-default data-disabled:opacity-40",
}

export function SelectTrigger({ placeholder, title, children, className, ...props }: SelectTriggerProps) {
  const { variant, items, anchor } = useContext(SelectContext)
  const titleId = useId()
  const renderValue = (value: unknown) => {
    if (isEmpty(value) && children === undefined) return placeholder
    return typeof children === "function" ? children(value) : (children ?? labelOf(items, value))
  }
  const value = (
    <BaseSelect.Value
      data-slot="select-value"
      placeholder={placeholder}
      className={cn("min-w-0 truncate data-placeholder:text-ink-3", variant === "field" && "flex-1", variant === "row" && "text-ink-2")}
    >
      {renderValue}
    </BaseSelect.Value>
  )

  if (variant === "row") {
    return (
      <BaseSelect.Trigger
        render={<ListRow render={<button type="button" />} />}
        aria-labelledby={titleId}
        className={cn("cursor-pointer select-none [-webkit-tap-highlight-color:transparent]", triggerStyles.row, className)}
        {...props}
      >
        <span id={titleId} data-slot="select-title" className="min-w-0 flex-1 truncate text-left">
          {title}
        </span>
        <span ref={anchor} data-slot="select-row-value" className="flex min-w-0 items-center gap-1">
          {value}
          <BaseSelect.Icon data-slot="select-icon" className="flex shrink-0 text-ink-3">
            <ChevronUpDown />
          </BaseSelect.Icon>
        </span>
      </BaseSelect.Trigger>
    )
  }

  if (variant === "popup") {
    return (
      <BaseSelect.Trigger
        data-slot="select-trigger"
        className={cn("cursor-pointer select-none [-webkit-tap-highlight-color:transparent]", triggerStyles.popup, className)}
        {...props}
      >
        <FitWidth>
          {value}
          <BaseSelect.Icon data-slot="select-icon" className="flex shrink-0 text-ink-2">
            <ChevronUpDown />
          </BaseSelect.Icon>
        </FitWidth>
      </BaseSelect.Trigger>
    )
  }

  return (
    <BaseSelect.Trigger
      data-slot="select-trigger"
      className={cn("cursor-pointer select-none [-webkit-tap-highlight-color:transparent]", triggerStyles.field, className)}
      {...props}
    >
      {value}
      <BaseSelect.Icon
        data-slot="select-icon"
        className="flex shrink-0 text-ink-3 transition-transform duration-spring ease-spring group-data-popup-open/trigger:rotate-180"
      >
        <ChevronDown />
      </BaseSelect.Icon>
    </BaseSelect.Trigger>
  )
}

function FitWidth({ children }: { children: ReactNode }) {
  const inner = useRef<HTMLSpanElement | null>(null)
  const [width, setWidth] = useState<number | null>(null)

  useLayoutEffect(() => {
    const element = inner.current
    if (!element) return
    const observer = new ResizeObserver(() => setWidth(element.offsetWidth))
    observer.observe(element)
    return () => observer.disconnect()
  }, [])

  return (
    <span
      data-slot="select-fit"
      className="block overflow-hidden transition-[width] duration-spring ease-spring motion-reduce:transition-none"
      style={width === null ? undefined : { width }}
    >
      <span ref={inner} className="flex w-max items-center gap-1 pr-2 pl-3.5">
        {children}
      </span>
    </span>
  )
}

export type SelectContentProps = Omit<ComponentProps<typeof BaseSelect.Popup>, "className"> & {
  side?: BaseSelect.Positioner.Props["side"]
  align?: BaseSelect.Positioner.Props["align"]
  sideOffset?: number
  className?: string
}

export function SelectContent({ side = "bottom", align, sideOffset = 6, className, children, ...props }: SelectContentProps) {
  const { variant, anchor } = useContext(SelectContext)
  return (
    <BaseSelect.Portal>
      <BaseSelect.Positioner
        ref={morphColor}
        data-slot="select-positioner"
        alignItemWithTrigger={false}
        anchor={variant === "row" ? anchor : undefined}
        side={side}
        align={align ?? (variant === "field" ? "start" : "end")}
        sideOffset={sideOffset}
        collisionPadding={8}
        className={cn(
          morphFromTrigger,
          "z-50 outline-none",
          variant === "field" && "[--morph-radius-start:var(--pb-radius-md)] [--morph-shape-start:squircle]",
          variant === "row" && "[--morph-radius-start:var(--pb-radius-sm)] [--morph-shape-start:squircle]",
        )}
        style={{ "--morph-gap": `${sideOffset}px` } as CSSProperties}
      >
        <BaseSelect.Popup
          data-slot="select-content"
          className={cn(
            "flex max-h-[min(var(--available-height),22rem)] flex-col overflow-hidden rounded-md text-ink outline-none",
            variant === "field" ? "w-(--anchor-width)" : "w-max min-w-[max(200px,var(--anchor-width))] max-w-[min(280px,var(--available-width))]",
            morphPanel,
            className,
          )}
          {...props}
        >
          <BaseSelect.List className="flex flex-col overflow-y-auto overscroll-contain p-1.5 scroll-py-1.5 outline-none">{children}</BaseSelect.List>
        </BaseSelect.Popup>
      </BaseSelect.Positioner>
    </BaseSelect.Portal>
  )
}

export type SelectItemProps = Omit<ComponentProps<typeof BaseSelect.Item>, "className"> & {
  className?: string
}

export function SelectItem({ className, children, ...props }: SelectItemProps) {
  return (
    <BaseSelect.Item
      data-slot="select-item"
      className={cn(
        "flex h-10 shrink-0 cursor-pointer items-center gap-2.5 rounded-sm px-2.5 text-body text-ink outline-none select-none",
        "transition-colors duration-fast ease-out data-highlighted:bg-press data-disabled:cursor-default data-disabled:text-ink-3",
        className,
      )}
      {...props}
    >
      <BaseSelect.ItemText className="min-w-0 flex-1 truncate">{children}</BaseSelect.ItemText>
      <BaseSelect.ItemIndicator className="flex shrink-0 text-ink">
        <Check />
      </BaseSelect.ItemIndicator>
    </BaseSelect.Item>
  )
}

export type SelectGroupProps = Omit<ComponentProps<typeof BaseSelect.Group>, "className"> & {
  className?: string
}

export function SelectGroup({ className, ...props }: SelectGroupProps) {
  return <BaseSelect.Group data-slot="select-group" className={cn("flex flex-col", className)} {...props} />
}

export type SelectGroupLabelProps = Omit<ComponentProps<typeof BaseSelect.GroupLabel>, "className"> & {
  className?: string
}

export function SelectGroupLabel({ className, ...props }: SelectGroupLabelProps) {
  return (
    <BaseSelect.GroupLabel
      data-slot="select-group-label"
      className={cn("px-2.5 pt-2 pb-1 text-caption font-semibold text-ink-2 select-none", className)}
      {...props}
    />
  )
}

export type SelectSeparatorProps = Omit<ComponentProps<typeof BaseSelect.Separator>, "className"> & {
  className?: string
}

export function SelectSeparator({ className, ...props }: SelectSeparatorProps) {
  return <BaseSelect.Separator data-slot="select-separator" className={cn("mx-1 my-1.5 h-px shrink-0 bg-line", className)} {...props} />
}

function ChevronDown() {
  return (
    <svg viewBox="0 0 24 24" aria-hidden="true" className="size-5 fill-none stroke-current" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round">
      <path d="M6 9.5l6 6 6-6" />
    </svg>
  )
}

function ChevronUpDown() {
  return (
    <svg viewBox="0 0 24 24" aria-hidden="true" className="size-4 fill-none stroke-current" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round">
      <path d="M8 9.5l4-4 4 4M8 14.5l4 4 4-4" />
    </svg>
  )
}

function Check() {
  return (
    <svg viewBox="0 0 12 12" aria-hidden="true" className="size-3.5 fill-none stroke-current" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
      <path d="M2.5 6.3l2.3 2.2L9.5 3.5" />
    </svg>
  )
}
```
