Nothing picked yet

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/menu.ts
    import type { Component } from "@effect/ui"
    import type { Html } from "@effect/ui/html"
    import type { Menu, MenuTriggerOptions } from "@effect/ui-kit"
    import { cn } from "#lib/cn"
    import { type ButtonSize, type ButtonVariant, buttonVariants } from "#ui/button"
    
    /** What a `Menu`'s `view` closure receives. A `ContextMenu`'s parts fit the item helpers too. */
    export type MenuParts = Component.Headless.Parts<typeof Menu>
    
    interface ClassOption {
      readonly class?: string | undefined
    }
    
    const popup =
      "max-h-[var(--available-height)] max-w-[min(320px,var(--available-width))] min-w-[200px] origin-[var(--transform-origin)] " +
      "overflow-y-auto rounded-lg border bg-popover p-1 text-[13px] leading-snug text-foreground shadow-float outline-none " +
      "transition-[opacity,scale] duration-150 ease-out data-[nested]:min-w-[150px] " +
      "data-[starting-style]:scale-95 data-[starting-style]:opacity-0 " +
      "data-[ending-style]:scale-95 data-[ending-style]:opacity-0 data-[ending-style]:duration-100 " +
      "data-[instant]:transition-none"
    
    const item =
      "relative flex min-h-[30px] cursor-default items-center gap-2 rounded-sm px-2 whitespace-nowrap text-foreground " +
      "no-underline outline-none select-none data-[highlighted]:bg-accent data-[highlighted]:text-accent-foreground " +
      "data-[popup-open]:bg-accent data-[disabled]:opacity-45 " +
      "[&_svg]:size-[15px] [&_svg]:shrink-0 [&_svg]:text-muted-foreground"
    
    const itemVariants = {
      default: "",
      destructive:
        "text-destructive data-[highlighted]:bg-destructive/10 data-[highlighted]:text-destructive [&_svg]:text-destructive"
    } as const
    
    const inset = "pl-[30px]"
    
    const tick =
      "before:absolute before:top-1/2 before:left-[10px] before:h-[5px] before:w-[9px] before:-translate-y-[70%] " +
      "before:-rotate-45 before:border-b-2 before:border-l-2 before:border-brand before:opacity-0 before:content-[''] " +
      "data-[checked]:before:opacity-100"
    
    const dot =
      "before:absolute before:top-1/2 before:left-[12px] before:size-1.5 before:-translate-y-1/2 before:rounded-full " +
      "before:bg-brand before:opacity-0 before:content-[''] data-[checked]:before:opacity-100"
    
    const submenuArrow =
      "after:ml-auto after:size-1.5 after:-translate-x-0.5 after:rotate-45 after:border-t-[1.5px] after:border-r-[1.5px] " +
      "after:border-muted-foreground after:content-['']"
    
    export type MenuItemVariant = keyof typeof itemVariants
    
    /** The button that opens the menu. It looks like an outline `Button` unless `variant` says otherwise. */
    export const MenuTrigger = <Msg>(
      h: Html.H<Msg>,
      menu: Pick<MenuParts, "trigger">,
      options: MenuTriggerOptions & ClassOption & {
        readonly variant?: ButtonVariant | undefined
        readonly size?: ButtonSize | undefined
      } = {}
    ) => {
      const { class: className, size, variant = "outline", ...trigger } = options
      return menu.trigger({
        ...trigger,
        element: h.button.class(buttonVariants({ variant, size, class: cn("group", className) }))
      })
    }
    
    /** A chevron for inside a trigger. It turns while the trigger's popup is open. */
    export const MenuChevron = <Msg>(h: Html.H<Msg>, options: ClassOption = {}) =>
      h.span.attr("aria-hidden", "true").class(cn(
        "mr-0.5 ml-1 size-1.5 -translate-y-px rotate-45 border-r-[1.5px] border-b-[1.5px] border-current opacity-60",
        "transition-[rotate,translate] duration-150 group-data-[popup-open]:translate-y-0.5 group-data-[popup-open]:rotate-[225deg]",
        options.class
      ))
    
    /** The popover the menu places next to its trigger. Put a `MenuPopup` inside. */
    export const MenuPositioner = <Msg>(h: Html.H<Msg>, menu: Pick<MenuParts, "positioner">, options: ClassOption = {}) =>
      menu.positioner(h.div.class(cn("outline-none", options.class)))
    
    /** The panel with the items. */
    export const MenuPopup = <Msg>(h: Html.H<Msg>, menu: Pick<MenuParts, "popup">, options: ClassOption = {}) =>
      menu.popup(h.div.class(cn(popup, options.class)))
    
    /** An action. `inset` lines its label up with checkbox and radio items. */
    export const MenuItem = <Msg>(
      h: Html.H<Msg>,
      menu: Pick<MenuParts, "item">,
      options: ClassOption & {
        readonly value: string
        readonly variant?: MenuItemVariant | undefined
        readonly inset?: boolean | undefined
        readonly closeOnClick?: boolean | undefined
      }
    ) =>
      menu.item({
        element: h.div.class(
          cn(item, itemVariants[options.variant ?? "default"], options.inset === true && inset, options.class)
        ),
        value: options.value,
        closeOnClick: options.closeOnClick
      })
    
    /** An item that is a real link. Chain `target` and `rel` on the result. */
    export const MenuLinkItem = <Msg>(
      h: Html.H<Msg>,
      menu: Pick<MenuParts, "linkItem">,
      options: ClassOption & {
        readonly value: string
        readonly href: string
        readonly closeOnClick?: boolean | undefined
      }
    ) =>
      menu.linkItem({
        element: h.a.class(cn(item, options.class)).attr("href", options.href),
        value: options.value,
        closeOnClick: options.closeOnClick
      })
    
    /** An item with a tick while it is checked. The tick is drawn from `data-checked`. */
    export const MenuCheckboxItem = <Msg>(
      h: Html.H<Msg>,
      menu: Pick<MenuParts, "checkboxItem">,
      options: ClassOption & {
        readonly value: string
        readonly checked: boolean
        readonly closeOnClick?: boolean | undefined
      }
    ) =>
      menu.checkboxItem({
        element: h.div.class(cn(item, inset, tick, options.class)),
        value: options.value,
        checked: options.checked,
        closeOnClick: options.closeOnClick
      })
    
    /** The group around radio items, with the checked value. */
    export const MenuRadioGroup = <Msg>(
      h: Html.H<Msg>,
      menu: Pick<MenuParts, "radioGroup">,
      options: ClassOption & { readonly value: string | null; readonly label?: string | undefined }
    ) =>
      menu.radioGroup({
        element: h.div.class(cn(options.class)).attr("aria-label", options.label),
        value: options.value
      })
    
    /** An item with a dot while it is the checked one of its `MenuRadioGroup`. */
    export const MenuRadioItem = <Msg>(
      h: Html.H<Msg>,
      menu: Pick<MenuParts, "radioItem">,
      options: ClassOption & { readonly value: string; readonly closeOnClick?: boolean | undefined }
    ) =>
      menu.radioItem({
        element: h.div.class(cn(item, inset, dot, options.class)),
        value: options.value,
        closeOnClick: options.closeOnClick
      })
    
    /** The parent menu's item that opens `submenu`, a `Menu` with `parentItem` drawn inside the popup. */
    export const MenuSubTrigger = <Msg>(
      h: Html.H<Msg>,
      menu: Pick<MenuParts, "item">,
      submenu: Pick<MenuParts, "submenuTrigger">,
      options: ClassOption & { readonly value: string; readonly inset?: boolean | undefined }
    ) =>
      menu.item({
        element: submenu.submenuTrigger(
          h.div.class(cn(item, submenuArrow, options.inset === true && inset, options.class))
        ),
        value: options.value
      })
    
    /** A group of items. Give its `MenuLabel` the same `group`. */
    export const MenuGroup = <Msg>(
      h: Html.H<Msg>,
      menu: Pick<MenuParts, "group">,
      options: ClassOption & { readonly group: string }
    ) => menu.group({ element: h.div.class(cn(options.class)), group: options.group })
    
    /** The small heading of a group. */
    export const MenuLabel = <Msg>(
      h: Html.H<Msg>,
      menu: Pick<MenuParts, "groupLabel">,
      options: ClassOption & { readonly group: string }
    ) =>
      menu.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
      })
    
    /** A line between items. */
    export const MenuSeparator = <Msg>(h: Html.H<Msg>, menu: Pick<MenuParts, "separator">, options: ClassOption = {}) =>
      menu.separator(h.div.class(cn("-mx-1 my-1 h-px bg-border", options.class)))
    
    /** A keyboard hint at the end of an item. */
    export const MenuShortcut = <Msg>(h: Html.H<Msg>, options: ClassOption = {}) =>
      h.span.class(cn("ml-auto pl-5 text-xs tracking-wider text-muted-foreground", options.class))
    
    /** The filter's input, at the top of the popup. The menu needs a `query` prop to filter. */
    export const MenuInput = <Msg>(
      h: Html.H<Msg>,
      menu: Pick<MenuParts, "input">,
      options: ClassOption & { readonly placeholder?: string | undefined; readonly label?: string | undefined } = {}
    ) =>
      menu.input(
        h.input
          .class(cn(
            "-mx-1 -mt-1 mb-1 block h-[34px] w-[calc(100%+0.5rem)] border-b bg-transparent px-3 outline-none",
            "placeholder:text-muted-foreground",
            options.class
          ))
          .attrs({ placeholder: options.placeholder, "aria-label": options.label ?? options.placeholder })
      )
    
    /** The element around the items of a filtering menu. */
    export const MenuList = <Msg>(h: Html.H<Msg>, menu: Pick<MenuParts, "list">, options: ClassOption = {}) =>
      menu.list(h.div.class(cn("outline-none", options.class)))
    
    /** Shown while the filter matches nothing, and `undefined` otherwise. */
    export const MenuEmpty = <Msg>(h: Html.H<Msg>, menu: Pick<MenuParts, "empty">, options: ClassOption = {}) =>
      menu.empty(h.div.class(cn("px-2 py-3.5 text-center text-muted-foreground", options.class)))
    
  3. Import it

    import { MenuTrigger, MenuChevron, MenuPositioner, MenuPopup, MenuItem, MenuLinkItem, MenuCheckboxItem, MenuRadioGroup, MenuRadioItem, MenuSubTrigger, MenuGroup, MenuLabel, MenuSeparator, MenuShortcut, MenuInput, MenuList, MenuEmpty } from "#ui/menu"
    

Usage

Basic.ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Menu } from "@effect/ui-kit"
import { Schema } from "effect"
import { MenuChevron, MenuGroup, MenuItem, MenuLabel, MenuPopup, MenuPositioner, MenuSeparator, MenuShortcut, MenuTrigger } from "#ui/menu"

const MenuBasicMessage = UiSchema.TaggedEnum({
  RequestedOpenMenu: {},
  RequestedCloseMenu: {},
  PickedMenuItem: { value: Schema.String }
})

const account = [
  { value: "profile", label: "Profile", shortcut: "⇧⌘P" },
  { value: "billing", label: "Billing", shortcut: "⌘B" },
  { value: "settings", label: "Settings", shortcut: "⌘," }
]

const team = [
  { value: "invite", label: "Invite people" },
  { value: "new-team", label: "New team", shortcut: "⌘T" }
]

const items = [...account, ...team, { value: "sign-out", label: "Sign out", shortcut: "⇧⌘Q" }]

export const MenuBasic = Html.component({
  name: "MenuBasic",
  model: Schema.Struct({ open: Schema.Boolean, picked: Schema.NullOr(Schema.String) }),
  message: MenuBasicMessage
}).make({
  init: () => ({ open: false, picked: null }),
  update: {
    RequestedOpenMenu: ($) => $.evolve({ open: true }),
    RequestedCloseMenu: ($) => $.evolve({ open: false }),
    PickedMenuItem: ($, { value }) => $.evolve({ picked: value })
  },
  view: (h, model) =>
    h.div.class("flex flex-col items-center gap-4").children(
      Menu(h, {
        props: { open: model.open, items, align: "start", sideOffset: 6 },
        onEmit: {
          RequestedOpen: () => MenuBasicMessage.RequestedOpenMenu(),
          RequestedClose: () => MenuBasicMessage.RequestedCloseMenu(),
          Picked: ({ value }) => MenuBasicMessage.PickedMenuItem({ value }),
          Highlighted: () => undefined,
          RequestedQuery: () => undefined,
          Settled: () => undefined
        },
        view: (menu) => {
          const item = ({ label, shortcut, value }: { value: string; label: string; shortcut?: string }) =>
            MenuItem(h, menu, { value }).children(label, shortcut === undefined ? undefined : MenuShortcut(h).children(shortcut))
          return h.div.children(
            MenuTrigger(h, menu).children("My account", MenuChevron(h)),
            MenuPositioner(h, menu).children(
              MenuPopup(h, menu).children(
                MenuGroup(h, menu, { group: "account" }).children(
                  MenuLabel(h, menu, { group: "account" }).children("My account"),
                  account.map(item)
                ),
                MenuSeparator(h, menu),
                team.map(item),
                MenuSeparator(h, menu),
                item(items[items.length - 1]!)
              )
            )
          )
        }
      }),
      h.p.class("text-xs text-muted-foreground tabular-nums").children(model.picked === null ? "Nothing picked yet" : `Picked ${model.picked}`)
    )
})

Examples

Icons, a disabled and a destructive item

An icon button opens the menu, aligned to its end. A disabled item stays in the arrow keys' order.

Archive is disabled

Checkbox items

A checkbox item reports its new state in Picked and keeps the menu open.

Showing 2 of 4

Radio items

Two radio groups in one menu, each with its value in the Model.

Sorted by modified, descending

A submenu is another Menu with parentItem, drawn inside the popup. It opens on hover or with ArrowRight.

Nothing picked yet

With a filter

With a query, focus stays in the input, typing narrows the items and the arrow keys move the highlight.

Labels: enhancement

Open on hover, with links

openOnHover opens the menu when the pointer rests on the trigger. Link items are real anchors.

Anatomy

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

PartDescription
triggerThe <button> that opens the popup. Takes { element } and the trigger's own openOnHover, delay, closeDelay and disabled.
positionerA <div>, a manual popover in the top layer that the menu places next to the trigger.
popupThe <div> inside the positioner with role="menu". Style this one.
itemA <div> per value, { element, value }. Closes the menu when picked.
linkItemAn <a> per value. Enter follows its href.
checkboxItem / checkboxItemIndicatorAn item with a checked state, { element, value, checked }, and the <span> shown while it is checked.
radioGroup / radioItem / radioItemIndicatorA <div> with the checked value around radio items, and the <span> shown in the checked one.
group / groupLabelA <div> around items and its label, tied together by { group }.
separatorA <div> between items.
submenuTriggerApplied by a submenu to the parent's item that opens it.
input / list / clear / emptyThe filter's <input>, the <div> around the filtered items, a button that empties the input, and the <div> shown when nothing matches.
backdrop / arrow / viewportA <div> under the popup, an arrow pointing at the trigger, and a wrapper for content that changes between triggers.
contextTriggerA <div> that opens the menu at the pointer on a right click.

API reference

Props

PropTypeDescription
openbooleanWhether the popup shows. The menu only asks, with RequestedOpen and RequestedClose.
itemsArray<{ value, label, disabled? }>Every item in the order it is drawn, for navigation, typeahead and filtering.
parentItemstringIn a submenu, the value of the parent's item that opens it.
side / alignSide / AlignWhere the popup sits against the trigger. "bottom" and "center" by default, "inline-end" and "start" in a submenu.
sideOffset / alignOffsetnumberThe gap to the trigger and the shift along its side, in pixels.
modalbooleanWhile open, the page doesn't scroll and a press outside only closes the menu. True by default.
openOnHoverbooleanResting on the trigger for delay ms opens the menu; leaving closes it after closeDelay.
querystringThe filter's text. Given, the menu filters its items and focus stays in the input part.
filter"contains" | "startsWith" | "endsWith" | nullHow items match the query. null hides none: draw only the items that match.
loopFocusbooleanThe arrow keys wrap from the last item to the first. True by default.
orientation"vertical" | "horizontal"Which arrow keys move between items.
disabledbooleanThe trigger and the items ignore the user.
closeParentOnEscbooleanIn a submenu, Escape closes the whole menu.

Events

EventDescription
RequestedOpenAsks for open to be true, with the reason and the id of the trigger pressed.
RequestedCloseAsks for open to be false, with the reason: item-press, outside-press, escape-key, focus-out ...
PickedAn item was picked. checked is the new state of a checkbox item, and true for a radio item.
HighlightedThe highlighted item changed, to value or to none.
RequestedQueryAsks for query to change. Also emitted to clear the query after the popup closes.
SettledThe popup's transitions ended, after it opened or closed.

Data attributes

AttributeDescription
data-popup-openOn the trigger and a submenu trigger while their popup is open.
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: the hooks for the enter and exit transition.
data-side / data-alignOn the positioner, the popup and the arrow: where the popup ended up.
data-instantOn the positioner and the popup when transitions should be off: "click" from the keyboard, "dismiss" after Escape, "trigger-change", "group" in a Menubar.
data-nestedOn the popup of a submenu.
data-highlightedOn the item the pointer or the keyboard is on.
data-checked / data-uncheckedOn checkbox and radio items and their indicators.
data-disabledOn a disabled trigger or item.

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.