# Menu

A button that opens a list of actions, links, checkbox and radio items, and submenus.

- Page: https://www.effectcn.com/components/menu
- Kind: Headless component with parts
- File: `src/ui/menu.ts`
- Built on: `Menu` 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/menu.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/menu.ts`

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

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

## Usage

Actions in a labelled group, with separators and shortcut hints.

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

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

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

const actions = [
  { value: "rename", label: "Rename", shortcut: "F2", icon: "M12 20h9M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4Z" },
  { value: "duplicate", label: "Duplicate", shortcut: "⌘D", icon: "M9 9h11v11H9zM5 15H4V4h11v1" },
  { value: "archive", label: "Archive", shortcut: "⌘E", icon: "M3 4h18v4H3zM5 8v12h14V8M10 12h4", disabled: true }
]

const trash = "M3 6h18M8 6V4h8v2M6 6l1 14h10l1-14"

const items = [...actions, { value: "delete", label: "Delete" }]

export const MenuIcons = Html.component({
  name: "MenuIcons",
  model: Schema.Struct({ open: Schema.Boolean, picked: Schema.NullOr(Schema.String) }),
  message: MenuIconsMessage
}).make({
  init: () => ({ open: false, picked: null }),
  update: {
    RequestedOpenMenu: ($) => $.evolve({ open: true }),
    RequestedCloseMenu: ($) => $.evolve({ open: false }),
    PickedMenuItem: ($, { value }) => $.evolve({ picked: value })
  },
  view: (h, model) => {
    const icon = (d: string) =>
      h.el("svg")
        .attrs({ viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", "stroke-width": "2", "aria-hidden": "true" })
        .children(h.el("path").attrs({ d, "stroke-linecap": "round", "stroke-linejoin": "round" }))
    return h.div.class("flex flex-col items-center gap-4").children(
      Menu(h, {
        props: { open: model.open, items, align: "end", sideOffset: 6 },
        onEmit: {
          RequestedOpen: () => MenuIconsMessage.RequestedOpenMenu(),
          RequestedClose: () => MenuIconsMessage.RequestedCloseMenu(),
          Picked: ({ value }) => MenuIconsMessage.PickedMenuItem({ value }),
          Highlighted: () => undefined,
          RequestedQuery: () => undefined,
          Settled: () => undefined
        },
        view: (menu) =>
          h.div.children(
            MenuTrigger(h, menu, { size: "icon" }).attr("aria-label", "File actions").children(icon("M5 12h.01M12 12h.01M19 12h.01")),
            MenuPositioner(h, menu).children(
              MenuPopup(h, menu).children(
                actions.map((action) =>
                  MenuItem(h, menu, { value: action.value }).children(
                    icon(action.icon),
                    action.label,
                    MenuShortcut(h).children(action.shortcut)
                  )
                ),
                MenuSeparator(h, menu),
                MenuItem(h, menu, { value: "delete", variant: "destructive" })
                  .children(icon(trash), "Delete", MenuShortcut(h).children("⌘⌫"))
              )
            )
          )
      }),
      h.p.class("text-xs text-muted-foreground tabular-nums").children(model.picked === null ? "Archive is disabled" : `Picked ${model.picked}`)
    )
  }
})
```

### Checkbox items

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

```ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Menu } from "@effect/ui-kit"
import { Schema } from "effect"
import { MenuCheckboxItem, MenuChevron, MenuGroup, MenuLabel, MenuPopup, MenuPositioner, MenuTrigger } from "#ui/menu"

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

const panels = [
  { value: "status-bar", label: "Status bar" },
  { value: "activity-bar", label: "Activity bar" },
  { value: "minimap", label: "Minimap" },
  { value: "breadcrumbs", label: "Breadcrumbs", disabled: true }
]

export const MenuCheckboxItems = Html.component({
  name: "MenuCheckboxItems",
  model: Schema.Struct({ open: Schema.Boolean, shown: Schema.Array(Schema.String) }),
  message: MenuCheckboxItemsMessage
}).make({
  init: () => ({ open: false, shown: ["status-bar", "breadcrumbs"] }),
  update: {
    RequestedOpenMenu: ($) => $.evolve({ open: true }),
    RequestedCloseMenu: ($) => $.evolve({ open: false }),
    PickedMenuItem: ($, { checked, value }) =>
      $.evolve({ shown: (shown) => checked ? [...shown, value] : shown.filter((panel) => panel !== value) })
  },
  view: (h, model) =>
    h.div.class("flex flex-col items-center gap-4").children(
      Menu(h, {
        props: { open: model.open, items: panels, align: "start", sideOffset: 6 },
        onEmit: {
          RequestedOpen: () => MenuCheckboxItemsMessage.RequestedOpenMenu(),
          RequestedClose: () => MenuCheckboxItemsMessage.RequestedCloseMenu(),
          Picked: ({ checked, value }) => MenuCheckboxItemsMessage.PickedMenuItem({ value, checked: checked === true }),
          Highlighted: () => undefined,
          RequestedQuery: () => undefined,
          Settled: () => undefined
        },
        view: (menu) =>
          h.div.children(
            MenuTrigger(h, menu).children("View", MenuChevron(h)),
            MenuPositioner(h, menu).children(
              MenuPopup(h, menu).children(
                MenuGroup(h, menu, { group: "appearance" }).children(
                  MenuLabel(h, menu, { group: "appearance" }).children("Appearance"),
                  panels.map(({ label, value }) =>
                    MenuCheckboxItem(h, menu, { value, checked: model.shown.includes(value) }).children(label)
                  )
                )
              )
            )
          )
      }),
      h.p.class("text-xs text-muted-foreground tabular-nums").children(`Showing ${model.shown.length} of ${panels.length}`)
    )
})
```

### Radio items

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

```ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Menu } from "@effect/ui-kit"
import { Schema } from "effect"
import { MenuChevron, MenuLabel, MenuPopup, MenuPositioner, MenuRadioGroup, MenuRadioItem, MenuSeparator, MenuTrigger } from "#ui/menu"

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

const fields = [
  { value: "name", label: "Name" },
  { value: "modified", label: "Date modified" },
  { value: "size", label: "Size" }
]

const orders = [
  { value: "ascending", label: "Ascending" },
  { value: "descending", label: "Descending" }
]

export const MenuRadioItems = Html.component({
  name: "MenuRadioItems",
  model: Schema.Struct({ open: Schema.Boolean, field: Schema.String, order: Schema.String }),
  message: MenuRadioItemsMessage
}).make({
  init: () => ({ open: false, field: "modified", order: "descending" }),
  update: {
    RequestedOpenMenu: ($) => $.evolve({ open: true }),
    RequestedCloseMenu: ($) => $.evolve({ open: false }),
    PickedMenuItem: ($, { value }) =>
      orders.some((order) => order.value === value) ? $.evolve({ order: value }) : $.evolve({ field: value })
  },
  view: (h, model) =>
    h.div.class("flex flex-col items-center gap-4").children(
      Menu(h, {
        props: { open: model.open, items: [...fields, ...orders], align: "start", sideOffset: 6 },
        onEmit: {
          RequestedOpen: () => MenuRadioItemsMessage.RequestedOpenMenu(),
          RequestedClose: () => MenuRadioItemsMessage.RequestedCloseMenu(),
          Picked: ({ value }) => MenuRadioItemsMessage.PickedMenuItem({ value }),
          Highlighted: () => undefined,
          RequestedQuery: () => undefined,
          Settled: () => undefined
        },
        view: (menu) => {
          const radioItem = ({ label, value }: { readonly value: string; readonly label: string }) =>
            MenuRadioItem(h, menu, { value }).children(label
            )
          return h.div.children(
            MenuTrigger(h, menu).children("Sort", MenuChevron(h)),
            MenuPositioner(h, menu).children(
              MenuPopup(h, menu).children(
                MenuLabel(h, menu, { group: "field" }).children("Sort by"),
                MenuRadioGroup(h, menu, { value: model.field, label: "Sort by" }).children(
                  fields.map(radioItem)
                ),
                MenuSeparator(h, menu),
                MenuLabel(h, menu, { group: "order" }).children("Order"),
                MenuRadioGroup(h, menu, { value: model.order, label: "Order" }).children(
                  orders.map(radioItem)
                )
              )
            )
          )
        }
      }),
      h.p.class("text-xs text-muted-foreground tabular-nums").children(`Sorted by ${model.field}, ${model.order}`)
    )
})
```

### Submenus

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

```ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Menu } from "@effect/ui-kit"
import { Schema } from "effect"
import { MenuChevron, MenuItem, MenuPopup, MenuPositioner, MenuSeparator, MenuSubTrigger, MenuTrigger } from "#ui/menu"

const MenuSubmenuMessage = UiSchema.TaggedEnum({
  RequestedOpenMenu: {},
  RequestedCloseMenu: {},
  RequestedOpenSubmenu: { submenu: Schema.String },
  RequestedCloseSubmenu: { submenu: Schema.String },
  PickedMenuItem: { value: Schema.String }
})

const items = [
  { value: "open", label: "Open" },
  { value: "share", label: "Share" },
  { value: "move", label: "Move to" },
  { value: "delete", label: "Delete" }
]

const submenus = [
  {
    parentItem: "share",
    label: "Share",
    items: [
      { value: "email", label: "Email link" },
      { value: "message", label: "Message" },
      { value: "copy-link", label: "Copy link" }
    ]
  },
  {
    parentItem: "move",
    label: "Move to",
    items: [
      { value: "projects", label: "Projects" },
      { value: "archive", label: "Archive" },
      { value: "new-folder", label: "New folder…" }
    ]
  }
]

export const MenuSubmenu = Html.component({
  name: "MenuSubmenu",
  model: Schema.Struct({
    open: Schema.Boolean,
    submenu: Schema.NullOr(Schema.String),
    picked: Schema.NullOr(Schema.String)
  }),
  message: MenuSubmenuMessage
}).make({
  init: () => ({ open: false, submenu: null, picked: null }),
  update: {
    RequestedOpenMenu: ($) => $.evolve({ open: true }),
    RequestedCloseMenu: ($) => $.evolve({ open: false, submenu: null }),
    RequestedOpenSubmenu: ($, { submenu }) => $.evolve({ submenu }),
    // A submenu that closes because its sibling opened may report after it.
    RequestedCloseSubmenu: ($, { submenu }) => $.model.submenu === submenu ? $.evolve({ submenu: null }) : $.model,
    PickedMenuItem: ($, { value }) => $.evolve({ picked: value })
  },
  view: (h, model) => {
    const reports = {
      Picked: ({ value }: { readonly value: string }) => MenuSubmenuMessage.PickedMenuItem({ value }),
      Highlighted: () => undefined,
      RequestedQuery: () => undefined,
      Settled: () => undefined
    }
    return h.div.class("flex flex-col items-center gap-4").children(
      Menu(h, {
        key: "root",
        props: { open: model.open, items, align: "start", sideOffset: 6 },
        onEmit: {
          ...reports,
          RequestedOpen: () => MenuSubmenuMessage.RequestedOpenMenu(),
          RequestedClose: () => MenuSubmenuMessage.RequestedCloseMenu()
        },
        view: (menu) =>
          h.div.children(
            MenuTrigger(h, menu).children("File", MenuChevron(h)),
            MenuPositioner(h, menu).children(
              MenuPopup(h, menu).children(
                MenuItem(h, menu, { value: "open" }).children("Open"),
                MenuSeparator(h, menu),
                submenus.map(({ items, label, parentItem }) =>
                  Menu(h, {
                    key: parentItem,
                    props: { open: model.submenu === parentItem, items, parentItem, sideOffset: 2, alignOffset: -5 },
                    onEmit: {
                      ...reports,
                      RequestedOpen: () => MenuSubmenuMessage.RequestedOpenSubmenu({ submenu: parentItem }),
                      RequestedClose: () => MenuSubmenuMessage.RequestedCloseSubmenu({ submenu: parentItem })
                    },
                    view: (submenu) =>
                      h.div.children(
                        MenuSubTrigger(h, menu, submenu, { value: parentItem })
                          .children(label),
                        MenuPositioner(h, submenu).children(
                          MenuPopup(h, submenu).children(
                            items.map((item) =>
                              MenuItem(h, submenu, { value: item.value }).children(item.label)
                            )
                          )
                        )
                      )
                  })
                ),
                MenuSeparator(h, menu),
                MenuItem(h, menu, { value: "delete", variant: "destructive" })
                  .children("Delete")
              )
            )
          )
      }),
      h.p.class("text-xs text-muted-foreground tabular-nums").children(model.picked === null ? "Nothing picked yet" : `Picked ${model.picked}`)
    )
  }
})
```

### With a filter

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

```ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Menu } from "@effect/ui-kit"
import { Schema } from "effect"
import { MenuCheckboxItem, MenuChevron, MenuEmpty, MenuInput, MenuList, MenuPopup, MenuPositioner, MenuTrigger } from "#ui/menu"

const MenuFilterMessage = UiSchema.TaggedEnum({
  RequestedOpenMenu: {},
  RequestedCloseMenu: {},
  RequestedQueryMenu: { query: Schema.String },
  PickedMenuItem: { value: Schema.String, checked: Schema.Boolean }
})

const labels = [
  { value: "bug", label: "Bug" },
  { value: "documentation", label: "Documentation" },
  { value: "enhancement", label: "Enhancement" },
  { value: "good-first-issue", label: "Good first issue" },
  { value: "help-wanted", label: "Help wanted" },
  { value: "question", label: "Question" }
]

export const MenuFilter = Html.component({
  name: "MenuFilter",
  model: Schema.Struct({ open: Schema.Boolean, query: Schema.String, applied: Schema.Array(Schema.String) }),
  message: MenuFilterMessage
}).make({
  init: () => ({ open: false, query: "", applied: ["enhancement"] }),
  update: {
    RequestedOpenMenu: ($) => $.evolve({ open: true }),
    RequestedCloseMenu: ($) => $.evolve({ open: false }),
    RequestedQueryMenu: ($, { query }) => $.evolve({ query }),
    PickedMenuItem: ($, { checked, value }) =>
      $.evolve({ applied: (applied) => checked ? [...applied, value] : applied.filter((label) => label !== value) })
  },
  view: (h, model) =>
    h.div.class("flex flex-col items-center gap-4").children(
      Menu(h, {
        // Passing `query` turns filtering on, and focus stays in the input.
        props: { open: model.open, items: labels, query: model.query, autoHighlight: true, align: "start", sideOffset: 6 },
        onEmit: {
          RequestedOpen: () => MenuFilterMessage.RequestedOpenMenu(),
          RequestedClose: () => MenuFilterMessage.RequestedCloseMenu(),
          RequestedQuery: ({ query }) => MenuFilterMessage.RequestedQueryMenu({ query }),
          Picked: ({ checked, value }) => MenuFilterMessage.PickedMenuItem({ value, checked: checked === true }),
          Highlighted: () => undefined,
          Settled: () => undefined
        },
        view: (menu) =>
          h.div.children(
            MenuTrigger(h, menu).children("Labels", MenuChevron(h)),
            MenuPositioner(h, menu).children(
              MenuPopup(h, menu).children(
                MenuInput(h, menu, { placeholder: "Filter labels…" }),
                MenuList(h, menu).children(
                  labels.map(({ label, value }) =>
                    MenuCheckboxItem(h, menu, { value, checked: model.applied.includes(value) }).children(label)
                  )
                ),
                MenuEmpty(h, menu)?.children("No label found")
              )
            )
          )
      }),
      h.p.class("text-xs text-muted-foreground tabular-nums").children(
        model.applied.length === 0 ? "No labels" : `Labels: ${model.applied.join(", ")}`
      )
    )
})
```

### Open on hover, with links

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

```ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Menu } from "@effect/ui-kit"
import { Schema } from "effect"
import { MenuChevron, MenuLinkItem, MenuPopup, MenuPositioner, MenuShortcut, MenuTrigger } from "#ui/menu"

const MenuOpenOnHoverMessage = UiSchema.TaggedEnum({
  RequestedOpenMenu: {},
  RequestedCloseMenu: {}
})

const resources = [
  { value: "docs", label: "Documentation", href: "https://effect.website/docs" },
  { value: "github", label: "GitHub", href: "https://github.com/Effect-TS/ui" },
  { value: "discord", label: "Discord", href: "https://discord.gg/effect-ts" }
]

export const MenuOpenOnHover = Html.component({
  name: "MenuOpenOnHover",
  model: Schema.Struct({ open: Schema.Boolean }),
  message: MenuOpenOnHoverMessage
}).make({
  init: () => ({ open: false }),
  update: {
    RequestedOpenMenu: ($) => $.evolve({ open: true }),
    RequestedCloseMenu: ($) => $.evolve({ open: false })
  },
  view: (h, model) =>
    Menu(h, {
      props: { open: model.open, items: resources, openOnHover: true, delay: 80, closeDelay: 120, sideOffset: 6 },
      onEmit: {
        RequestedOpen: () => MenuOpenOnHoverMessage.RequestedOpenMenu(),
        RequestedClose: () => MenuOpenOnHoverMessage.RequestedCloseMenu(),
        Picked: () => undefined,
        Highlighted: () => undefined,
        RequestedQuery: () => undefined,
        Settled: () => undefined
      },
      view: (menu) =>
        h.div.children(
          MenuTrigger(h, menu, { variant: "ghost" }).children("Resources", MenuChevron(h)),
          MenuPositioner(h, menu).children(
            MenuPopup(h, menu).children(
              resources.map(({ href, label, value }) =>
                MenuLinkItem(h, menu, { value, href, closeOnClick: true })
                  .attrs({ target: "_blank", rel: "noreferrer" })
                  .children(label, MenuShortcut(h).children("↗"))
              )
            )
          )
        )
    })
})
```

## Anatomy

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

| Part | Description |
| --- | --- |
| `trigger` | The <button> that opens the popup. Takes { element } and the trigger's own openOnHover, delay, closeDelay and disabled. |
| `positioner` | A <div>, a manual popover in the top layer that the menu places next to the trigger. |
| `popup` | The <div> inside the positioner with role="menu". Style this one. |
| `item` | A <div> per value, { element, value }. Closes the menu when picked. |
| `linkItem` | An <a> per value. Enter follows its href. |
| `checkboxItem / checkboxItemIndicator` | An item with a checked state, { element, value, checked }, and the <span> shown while it is checked. |
| `radioGroup / radioItem / radioItemIndicator` | A <div> with the checked value around radio items, and the <span> shown in the checked one. |
| `group / groupLabel` | A <div> around items and its label, tied together by { group }. |
| `separator` | A <div> between items. |
| `submenuTrigger` | Applied by a submenu to the parent's item that opens it. |
| `input / list / clear / empty` | The filter's <input>, the <div> around the filtered items, a button that empties the input, and the <div> shown when nothing matches. |
| `backdrop / arrow / viewport` | A <div> under the popup, an arrow pointing at the trigger, and a wrapper for content that changes between triggers. |
| `contextTrigger` | A <div> that opens the menu at the pointer on a right click. |

## API reference

### Props

| Prop | Type | Description |
| --- | --- | --- |
| `open` | `boolean` | Whether the popup shows. The menu only asks, with RequestedOpen and RequestedClose. |
| `items` | `Array<{ value, label, disabled? }>` | Every item in the order it is drawn, for navigation, typeahead and filtering. |
| `parentItem` | `string` | In a submenu, the value of the parent's item that opens it. |
| `side / align` | `Side / Align` | Where the popup sits against the trigger. "bottom" and "center" by default, "inline-end" and "start" in a submenu. |
| `sideOffset / alignOffset` | `number` | The gap to the trigger and the shift along its side, in pixels. |
| `modal` | `boolean` | While open, the page doesn't scroll and a press outside only closes the menu. True by default. |
| `openOnHover` | `boolean` | Resting on the trigger for delay ms opens the menu; leaving closes it after closeDelay. |
| `query` | `string` | The filter's text. Given, the menu filters its items and focus stays in the input part. |
| `filter` | `"contains" \| "startsWith" \| "endsWith" \| null` | How items match the query. null hides none: draw only the items that match. |
| `loopFocus` | `boolean` | The arrow keys wrap from the last item to the first. True by default. |
| `orientation` | `"vertical" \| "horizontal"` | Which arrow keys move between items. |
| `disabled` | `boolean` | The trigger and the items ignore the user. |
| `closeParentOnEsc` | `boolean` | In a submenu, Escape closes the whole menu. |

### Events

| Event | Description |
| --- | --- |
| `RequestedOpen` | Asks for open to be true, with the reason and the id of the trigger pressed. |
| `RequestedClose` | Asks for open to be false, with the reason: item-press, outside-press, escape-key, focus-out ... |
| `Picked` | An item was picked. checked is the new state of a checkbox item, and true for a radio item. |
| `Highlighted` | The highlighted item changed, to value or to none. |
| `RequestedQuery` | Asks for query to change. Also emitted to clear the query after the popup closes. |
| `Settled` | The popup's transitions ended, after it opened or closed. |

### Data attributes

| Attribute | Description |
| --- | --- |
| `data-popup-open` | On the trigger and a submenu trigger while their popup is open. |
| `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: the hooks for the enter and exit transition. |
| `data-side / data-align` | On the positioner, the popup and the arrow: where the popup ended up. |
| `data-instant` | On the positioner and the popup when transitions should be off: "click" from the keyboard, "dismiss" after Escape, "trigger-change", "group" in a Menubar. |
| `data-nested` | On the popup of a submenu. |
| `data-highlighted` | On the item the pointer or the keyboard is on. |
| `data-checked / data-unchecked` | On checkbox and radio items and their indicators. |
| `data-disabled` | On a disabled trigger or item. |

## Related components

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