# ContextMenu

A menu that opens at the pointer on a right click, or after a long press on a touch screen.

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

```ts
import type { Component } from "@effect/ui"
import type { Html } from "@effect/ui/html"
import type { ContextMenuParts, Menu } from "@effect/ui-kit"
import { cn } from "#lib/cn"
import {
  MenuCheckboxItem,
  MenuGroup,
  MenuItem,
  MenuLabel,
  MenuLinkItem,
  MenuPopup,
  MenuPositioner,
  MenuRadioGroup,
  MenuRadioItem,
  MenuSeparator,
  MenuShortcut,
  MenuSubTrigger
} from "#ui/menu"

type MenuParts = Component.Headless.Parts<typeof Menu>

/**
 * The area a right click or a long press opens the menu over. It has no look of
 * its own beyond a focus ring: pass the area's classes as `class`, and an `id`
 * when several triggers share one menu, which also keys the element.
 */
export const ContextMenuTrigger = <Msg>(
  h: Html.H<Msg>,
  contextMenu: Pick<ContextMenuParts, "trigger">,
  options: { readonly class?: string | undefined; readonly id?: string | undefined } = {}
) =>
  contextMenu.trigger(
    (options.id === undefined ? h.div : h.div.key(options.id))
      .class(cn(
        "outline-none select-none [-webkit-touch-callout:none] focus-visible:ring-2 focus-visible:ring-ring",
        options.class
      ))
      .attr("id", options.id)
  )

/**
 * The item of the context menu that opens `submenu`, a `Menu` with `parentItem`
 * drawn inside the popup.
 */
export const ContextMenuSubTrigger = <Msg>(
  h: Html.H<Msg>,
  contextMenu: Pick<ContextMenuParts, "item">,
  submenu: Pick<MenuParts, "submenuTrigger">,
  options: { readonly value: string; readonly inset?: boolean | undefined; readonly class?: string | undefined }
) => MenuSubTrigger(h, contextMenu, submenu, options)

// The popup and the items are a Menu's: each helper takes the context menu's parts, or a submenu's.
export const ContextMenuPositioner = MenuPositioner
export const ContextMenuPopup = MenuPopup
export const ContextMenuItem = MenuItem
export const ContextMenuLinkItem = MenuLinkItem
export const ContextMenuCheckboxItem = MenuCheckboxItem
export const ContextMenuRadioGroup = MenuRadioGroup
export const ContextMenuRadioItem = MenuRadioItem
export const ContextMenuGroup = MenuGroup
export const ContextMenuLabel = MenuLabel
export const ContextMenuSeparator = MenuSeparator
export const ContextMenuShortcut = MenuShortcut
```

```ts
import { ContextMenuTrigger, ContextMenuSubTrigger, ContextMenuPositioner, ContextMenuPopup, ContextMenuItem, ContextMenuLinkItem, ContextMenuCheckboxItem, ContextMenuRadioGroup, ContextMenuRadioItem, ContextMenuGroup, ContextMenuLabel, ContextMenuSeparator, ContextMenuShortcut } from "#ui/context-menu"
```

## Usage

Right click the area, or focus it and press Shift+F10 or the Menu key.

```ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { ContextMenu } from "@effect/ui-kit"
import { Schema } from "effect"
import { ContextMenuItem, ContextMenuPopup, ContextMenuPositioner, ContextMenuSeparator, ContextMenuShortcut, ContextMenuTrigger } from "#ui/context-menu"

const ContextMenuBasicMessage = UiSchema.TaggedEnum({
  RequestedOpenContextMenu: {},
  RequestedCloseContextMenu: {},
  PickedContextMenuItem: { value: Schema.String }
})

const navigation = [
  { value: "back", label: "Back", shortcut: "⌘[" },
  { value: "forward", label: "Forward", shortcut: "⌘]", disabled: true },
  { value: "reload", label: "Reload", shortcut: "⌘R" }
]

const page = [
  { value: "save", label: "Save page as…", shortcut: "⌘S" },
  { value: "print", label: "Print…", shortcut: "⌘P" },
  { value: "source", label: "View page source", shortcut: "⌥⌘U" }
]

const area =
  "grid min-h-36 w-80 max-w-full place-items-center rounded-md border border-dashed border-input p-4 text-center " +
  "text-[13px] text-muted-foreground transition-colors data-[popup-open]:border-ring data-[popup-open]:bg-brand-wash"

export const ContextMenuBasic = Html.component({
  name: "ContextMenuBasic",
  model: Schema.Struct({ open: Schema.Boolean, picked: Schema.NullOr(Schema.String) }),
  message: ContextMenuBasicMessage
}).make({
  init: () => ({ open: false, picked: null }),
  update: {
    RequestedOpenContextMenu: ($) => $.evolve({ open: true }),
    RequestedCloseContextMenu: ($) => $.evolve({ open: false }),
    PickedContextMenuItem: ($, { value }) => $.evolve({ picked: value })
  },
  view: (h, model) =>
    ContextMenu(h, {
      props: { open: model.open, items: [...navigation, ...page] },
      onEmit: {
        RequestedOpen: () => ContextMenuBasicMessage.RequestedOpenContextMenu(),
        RequestedClose: () => ContextMenuBasicMessage.RequestedCloseContextMenu(),
        Picked: ({ value }) => ContextMenuBasicMessage.PickedContextMenuItem({ value }),
        Highlighted: () => undefined,
        Settled: () => undefined
      },
      view: (contextMenu) => {
        const item = ({ label, shortcut, value }: { readonly value: string; readonly label: string; readonly shortcut: string }) =>
          ContextMenuItem(h, contextMenu, { value }).children(
            label,
            ContextMenuShortcut(h).children(shortcut)
          )
        return h.div.class("flex flex-col items-center gap-4").children(
          ContextMenuTrigger(h, contextMenu, { class: area }).children(
            model.picked === null ? "Right click here" : `Picked ${model.picked}`
          ),
          ContextMenuPositioner(h, contextMenu).children(
            ContextMenuPopup(h, contextMenu).children(
              navigation.map(item),
              ContextMenuSeparator(h, contextMenu),
              page.map(item)
            )
          )
        )
      }
    })
})
```

## Examples

### Submenus

A submenu is a Menu with parentItem, drawn inside the context menu's popup.

```ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { ContextMenu, Menu } from "@effect/ui-kit"
import { Schema } from "effect"
import { ContextMenuItem, ContextMenuPopup, ContextMenuPositioner, ContextMenuSeparator, ContextMenuSubTrigger, ContextMenuTrigger } from "#ui/context-menu"

const ContextMenuSubmenuMessage = UiSchema.TaggedEnum({
  RequestedOpenContextMenu: {},
  RequestedCloseContextMenu: {},
  RequestedOpenSubmenu: { submenu: Schema.String },
  RequestedCloseSubmenu: { submenu: Schema.String },
  PickedContextMenuItem: { value: Schema.String }
})

const items = [
  { value: "open", label: "Open" },
  { value: "open-with", label: "Open with" },
  { value: "share", label: "Share" },
  { value: "delete", label: "Move to trash" }
]

const submenus = [
  {
    parentItem: "open-with",
    label: "Open with",
    items: [
      { value: "preview", label: "Preview" },
      { value: "editor", label: "Text editor" },
      { value: "browser", label: "Browser" }
    ]
  },
  {
    parentItem: "share",
    label: "Share",
    items: [
      { value: "email", label: "Email" },
      { value: "message", label: "Message" },
      { value: "copy-link", label: "Copy link" }
    ]
  }
]

const area =
  "grid min-h-36 w-80 max-w-full place-items-center rounded-md border border-dashed border-input p-4 text-center " +
  "text-[13px] text-muted-foreground transition-colors data-[popup-open]:border-ring data-[popup-open]:bg-brand-wash"

export const ContextMenuSubmenu = Html.component({
  name: "ContextMenuSubmenu",
  model: Schema.Struct({
    open: Schema.Boolean,
    submenu: Schema.NullOr(Schema.String),
    picked: Schema.NullOr(Schema.String)
  }),
  message: ContextMenuSubmenuMessage
}).make({
  init: () => ({ open: false, submenu: null, picked: null }),
  update: {
    RequestedOpenContextMenu: ($) => $.evolve({ open: true }),
    RequestedCloseContextMenu: ($) => $.evolve({ open: false, submenu: null }),
    RequestedOpenSubmenu: ($, { submenu }) => $.evolve({ submenu }),
    RequestedCloseSubmenu: ($, { submenu }) => $.model.submenu === submenu ? $.evolve({ submenu: null }) : $.model,
    PickedContextMenuItem: ($, { value }) => $.evolve({ picked: value })
  },
  view: (h, model) => {
    const picked = ({ value }: { readonly value: string }) => ContextMenuSubmenuMessage.PickedContextMenuItem({ value })
    return ContextMenu(h, {
      key: "root",
      props: { open: model.open, items },
      onEmit: {
        RequestedOpen: () => ContextMenuSubmenuMessage.RequestedOpenContextMenu(),
        RequestedClose: () => ContextMenuSubmenuMessage.RequestedCloseContextMenu(),
        Picked: picked,
        Highlighted: () => undefined,
        Settled: () => undefined
      },
      view: (contextMenu) =>
        h.div.class("flex flex-col items-center gap-4").children(
          ContextMenuTrigger(h, contextMenu, { class: area }).children(
            model.picked === null ? "Right click report.pdf" : `Picked ${model.picked}`
          ),
          ContextMenuPositioner(h, contextMenu).children(
            ContextMenuPopup(h, contextMenu).children(
              ContextMenuItem(h, contextMenu, { value: "open" }).children("Open"),
              // A submenu is a Menu with `parentItem`, drawn inside the popup.
              submenus.map(({ items, label, parentItem }) =>
                Menu(h, {
                  key: parentItem,
                  props: { open: model.submenu === parentItem, items, parentItem, sideOffset: 2, alignOffset: -5 },
                  onEmit: {
                    RequestedOpen: () => ContextMenuSubmenuMessage.RequestedOpenSubmenu({ submenu: parentItem }),
                    RequestedClose: () => ContextMenuSubmenuMessage.RequestedCloseSubmenu({ submenu: parentItem }),
                    Picked: picked,
                    Highlighted: () => undefined,
                    RequestedQuery: () => undefined,
                    Settled: () => undefined
                  },
                  view: (submenu) =>
                    h.div.children(
                      ContextMenuSubTrigger(h, contextMenu, submenu, { value: parentItem }).children(label),
                      ContextMenuPositioner(h, submenu).children(
                        ContextMenuPopup(h, submenu).children(
                          items.map((item) =>
                            ContextMenuItem(h, submenu, { value: item.value })
                              .children(item.label)
                          )
                        )
                      )
                    )
                })
              ),
              ContextMenuSeparator(h, contextMenu),
              ContextMenuItem(h, contextMenu, { value: "delete", variant: "destructive" }).children("Move to trash")
            )
          )
        )
    })
  }
})
```

### Checkbox and radio items

Checkable items keep the menu open, and the area reflects the Model as it changes.

```ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { ContextMenu } from "@effect/ui-kit"
import { Schema } from "effect"
import { ContextMenuCheckboxItem, ContextMenuGroup, ContextMenuLabel, ContextMenuPopup, ContextMenuPositioner, ContextMenuRadioGroup, ContextMenuRadioItem, ContextMenuSeparator, ContextMenuTrigger } from "#ui/context-menu"

const ContextMenuCheckableMessage = UiSchema.TaggedEnum({
  RequestedOpenContextMenu: {},
  RequestedCloseContextMenu: {},
  PickedContextMenuItem: { value: Schema.String, checked: Schema.Boolean }
})

const toggles = [
  { value: "grid", label: "Show grid" },
  { value: "rulers", label: "Show rulers" },
  { value: "snap", label: "Snap to guides" }
]

const zooms = [
  { value: "50", label: "50%" },
  { value: "100", label: "100%" },
  { value: "200", label: "200%" }
]

const area =
  "grid min-h-36 w-80 max-w-full place-items-center rounded-md border border-dashed border-input p-4 text-center " +
  "text-[13px] text-muted-foreground transition-colors data-[popup-open]:border-ring data-[popup-open]:bg-brand-wash"

export const ContextMenuCheckable = Html.component({
  name: "ContextMenuCheckable",
  model: Schema.Struct({ open: Schema.Boolean, shown: Schema.Array(Schema.String), zoom: Schema.String }),
  message: ContextMenuCheckableMessage
}).make({
  init: () => ({ open: false, shown: ["grid"], zoom: "100" }),
  update: {
    RequestedOpenContextMenu: ($) => $.evolve({ open: true }),
    RequestedCloseContextMenu: ($) => $.evolve({ open: false }),
    PickedContextMenuItem: ($, { checked, value }) =>
      zooms.some((zoom) => zoom.value === value)
        ? $.evolve({ zoom: value })
        : $.evolve({ shown: (shown) => checked ? [...shown, value] : shown.filter((toggle) => toggle !== value) })
  },
  view: (h, model) =>
    ContextMenu(h, {
      props: { open: model.open, items: [...toggles, ...zooms] },
      onEmit: {
        RequestedOpen: () => ContextMenuCheckableMessage.RequestedOpenContextMenu(),
        RequestedClose: () => ContextMenuCheckableMessage.RequestedCloseContextMenu(),
        Picked: ({ checked, value }) => ContextMenuCheckableMessage.PickedContextMenuItem({ value, checked: checked === true }),
        Highlighted: () => undefined,
        Settled: () => undefined
      },
      view: (contextMenu) =>
        h.div.class("flex flex-col items-center gap-4").children(
          ContextMenuTrigger(h, contextMenu, { class: area }).children(
            `Canvas at ${model.zoom}%` + (model.shown.length === 0 ? "" : `, with ${model.shown.join(", ")}`)
          ),
          ContextMenuPositioner(h, contextMenu).children(
            ContextMenuPopup(h, contextMenu).children(
              toggles.map(({ label, value }) =>
                ContextMenuCheckboxItem(h, contextMenu, { value, checked: model.shown.includes(value) }).children(label)
              ),
              ContextMenuSeparator(h, contextMenu),
              ContextMenuGroup(h, contextMenu, { group: "zoom" }).children(
                ContextMenuLabel(h, contextMenu, { group: "zoom" }).children("Zoom"),
                ContextMenuRadioGroup(h, contextMenu, { value: model.zoom }).children(
                  zooms.map(({ label, value }) =>
                    ContextMenuRadioItem(h, contextMenu, { value }).children(label
                    )
                  )
                )
              )
            )
          )
        )
    })
})
```

### One menu for every row

Several triggers open one menu. RequestedOpen reports the row's id, and the actions change that row.

```ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { ContextMenu } from "@effect/ui-kit"
import { Schema } from "effect"
import { ContextMenuGroup, ContextMenuItem, ContextMenuLabel, ContextMenuPopup, ContextMenuPositioner, ContextMenuSeparator, ContextMenuTrigger } from "#ui/context-menu"

const ContextMenuRowsMessage = UiSchema.TaggedEnum({
  RequestedOpenContextMenu: { triggerId: Schema.NullOr(Schema.String) },
  RequestedCloseContextMenu: {},
  PickedContextMenuItem: { value: Schema.String }
})

const File = Schema.Struct({ id: Schema.String, name: Schema.String, starred: Schema.Boolean })

const actions = [
  { value: "star", label: "Star" },
  { value: "duplicate", label: "Duplicate" },
  { value: "delete", label: "Delete" }
]

export const ContextMenuRows = Html.component({
  name: "ContextMenuRows",
  model: Schema.Struct({
    open: Schema.Boolean,
    target: Schema.NullOr(Schema.String),
    copies: Schema.Number,
    files: Schema.Array(File)
  }),
  message: ContextMenuRowsMessage
}).make({
  init: () => ({
    open: false,
    target: null,
    copies: 0,
    files: [
      { id: "file-readme", name: "README.md", starred: true },
      { id: "file-package", name: "package.json", starred: false },
      { id: "file-config", name: "tsconfig.json", starred: false }
    ]
  }),
  update: {
    // One menu serves every row: `triggerId` is the `id` of the row that opened it.
    RequestedOpenContextMenu: ($, { triggerId }) => $.evolve({ open: true, target: triggerId }),
    RequestedCloseContextMenu: ($) => $.evolve({ open: false }),
    PickedContextMenuItem: ($, { value }) => {
      const file = $.model.files.find((file) => file.id === $.model.target)
      if (file === undefined) return $.model
      switch (value) {
        case "star":
          return $.evolve({
            files: (files) => files.map((each) => each.id === file.id ? { ...each, starred: !each.starred } : each)
          })
        case "duplicate":
          return $.evolve({
            copies: (copies) => copies + 1,
            files: (files) =>
              files.flatMap((each) =>
                each.id === file.id
                  ? [each, { id: `file-copy-${$.model.copies}`, name: `Copy of ${each.name}`, starred: false }]
                  : [each]
              )
          })
        default:
          return $.evolve({ files: (files) => files.filter((each) => each.id !== file.id) })
      }
    }
  },
  view: (h, model) => {
    const target = model.files.find((file) => file.id === model.target)
    return ContextMenu(h, {
      props: { open: model.open, items: actions },
      onEmit: {
        RequestedOpen: ({ triggerId }) => ContextMenuRowsMessage.RequestedOpenContextMenu({ triggerId }),
        RequestedClose: () => ContextMenuRowsMessage.RequestedCloseContextMenu(),
        Picked: ({ value }) => ContextMenuRowsMessage.PickedContextMenuItem({ value }),
        Highlighted: () => undefined,
        Settled: () => undefined
      },
      view: (contextMenu) =>
        h.div.class("flex w-80 max-w-full flex-col gap-3").children(
          h.div.class("flex flex-col rounded-md border p-1").children(
            model.files.length === 0
              ? h.p.class("text-xs text-muted-foreground tabular-nums").children("No files left")
              : model.files.map((file) =>
                ContextMenuTrigger(h, contextMenu, {
                  id: file.id,
                  class: "flex h-8 items-center justify-between rounded-sm px-2 text-[13px] hover:bg-accent data-[popup-open]:bg-accent"
                }).children(
                  h.span.children(file.name),
                  file.starred ? h.span.class("text-brand").attr("aria-label", "Starred").children("★") : undefined
                )
              )
          ),
          h.p.class("text-xs text-muted-foreground tabular-nums").children("Right click a file"),
          ContextMenuPositioner(h, contextMenu).children(
            ContextMenuPopup(h, contextMenu).children(
              ContextMenuGroup(h, contextMenu, { group: "file" }).children(
                ContextMenuLabel(h, contextMenu, { group: "file" })
                  .children(target?.name ?? "File"),
                ContextMenuItem(h, contextMenu, { value: "star" })
                  .children(target?.starred === true ? "Remove star" : "Star"),
                ContextMenuItem(h, contextMenu, { value: "duplicate" }).children("Duplicate")
              ),
              ContextMenuSeparator(h, contextMenu),
              ContextMenuItem(h, contextMenu, { value: "delete", variant: "destructive" }).children("Delete")
            )
          )
        )
    })
  }
})
```

## Anatomy

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

| Part | Description |
| --- | --- |
| `trigger` | The <div> area a right click or a long press opens the menu over. Gets tabindex="0". |
| `positioner` | A <div>, a manual popover placed at the pointer. |
| `popup` | The <div> inside the positioner with role="menu". |
| `item / linkItem` | A <div> or an <a> per value, { element, value }. |
| `checkboxItem / checkboxItemIndicator` | An item with a checked state 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. |
| `backdrop / arrow / finalFocus` | A <div> under the popup, an arrow, and an element to focus on close. |

## 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. |
| `disabled` | `boolean` | The menu ignores the user, and the browser's own menu shows instead. |
| `side / align` | `Side / Align` | "bottom" and "start" by default, so the popup's corner sits under the pointer. |
| `loopFocus` | `boolean` | The arrow keys wrap from the last item to the first. True by default. |
| `finalFocus` | `boolean` | On close, focus goes back to the element that had it. False leaves it where it is. |

### Events

| Event | Description |
| --- | --- |
| `RequestedOpen` | Asks for open to be true. triggerId is the id the consumer gave the trigger, or null. |
| `RequestedClose` | Asks for open to be false: item-press, outside-press, escape-key, focus-out or cancel-open. |
| `Picked` | An item was picked. checked is the new state of a checkbox item. |
| `Highlighted` | The highlighted item changed. |
| `Settled` | The popup's transitions ended. |

### Data attributes

| Attribute | Description |
| --- | --- |
| `data-popup-open / data-pressed` | On the trigger while the menu is open from it. |
| `data-starting-style / data-ending-style` | On the popup while it enters and exits. |
| `data-side / data-align` | On the positioner and the popup. |
| `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 item. |

## Related components

- [Menu](https://www.effectcn.com/components/menu.md): A button that opens a list of actions, links, checkbox and radio items, and submenus.
