# Context Menu

> The menu a right click or long press opens over rows, files and cards.

Page: https://uicontext.com/docs/components/context-menu

Group: Overlays.

## When to use

The menu a right click or long press opens over rows, files and cards. Use [Menu](https://uicontext.com/docs/components/menu.md) instead when the menu opens from a button.

## Usage

```ts
import { ContextMenu, ContextMenuState } from "./ui/uicontext/components/ContextMenu.ts"

const Message = UiSchema.TaggedEnum({
	ChangedMenu: { menu: ContextMenuState },
	Picked: { value: Schema.String, file: Schema.NullOr(Schema.String) },
})

export const FileMenu = (h: Html.H<typeof Message.Type>, menu: ContextMenuState) =>
	ContextMenu(h, {
		state: menu,
		onState: (next) => Message.ChangedMenu({ menu: next }),
		entries: [
			{ _tag: "Item", value: "rename", label: "Rename", shortcut: "f2" },
			{ _tag: "Separator" },
			{ _tag: "Item", value: "trash", label: "Move to trash", tone: "danger" },
		],
		onSelect: (event, file) => (event._tag === "RequestedPick" ? Message.Picked({ value: event.value, file }) : undefined),
		view: (area) => area(h.div, "report").children("Report.pdf"),
	})
```

## Examples

Each example is a complete file. Its imports point where the CLI installs the source.

### Files

The example the page opens with: Context Menu in “Files”.

```ts title="src/demo.ts" source="www/src/examples/context-menu/demo.ts"
import { UiSchema } from "effect/ui"
import { Html } from "effect/ui/html"
import * as stylex from "@stylexjs/stylex"
import { Schema } from "effect"
import { ContextMenu, contextMenuClosed, ContextMenuState } from "./ui/uicontext/components/ContextMenu.ts"
import type { MenuEntry } from "./ui/uicontext/components/Menu.ts"
import { sx } from "./ui/uicontext/components/Sx.ts"
import { color, corner, density, font, space, stroke } from "./ui/uicontext/components/tokens.stylex.ts"

const styles = stylex.create({
	wrap: { display: "grid", gap: space.md, inlineSize: "min(100%, 30rem)" },
	list: { display: "grid", borderWidth: stroke.hairline, borderStyle: "solid", borderColor: color.line, borderRadius: corner.card, backgroundColor: color.panel, padding: space.xs },
	row: {
		display: "flex",
		alignItems: "center",
		gap: space.md,
		minBlockSize: { default: density.control, "@media (pointer: coarse)": 44 },
		paddingInline: space.md,
		borderRadius: `calc(${corner.card} - 4px)`,
		fontSize: font.base,
		cursor: "default",
		userSelect: "none",
	},
	name: { flexGrow: 1, minInlineSize: 0, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" },
	star: { color: color.warning, flexShrink: 0 },
	meta: { flexShrink: 0, fontSize: font.sm, color: color.muted, fontVariantNumeric: "tabular-nums" },
	said: { margin: 0, minBlockSize: "1.4em", fontSize: font.sm, color: color.muted },
})

const files = [
	{ id: "q3-plan", name: "Q3 launch plan.pdf", size: "2.4 MB" },
	{ id: "pricing", name: "Pricing research — enterprise interviews.docx", size: "318 KB" },
	{ id: "roadmap", name: "Roadmap 2027.key", size: "41.2 MB" },
	{ id: "budget", name: "Marketing budget.xlsx", size: "96 KB" },
]

const nameOf = (file: string | null) => files.find((f) => f.id === file)?.name ?? "the file"

// what each action says it did; a real app does the work here
const done: Readonly<Record<string, string>> = {
	open: "Opened",
	rename: "Renaming",
	duplicate: "Made a copy of",
	"move:finance": "Moved to Finance:",
	"move:archive": "Archived",
	trash: "Moved to trash:",
}

const entriesFor = (starred: boolean): ReadonlyArray<MenuEntry> => [
	{ _tag: "Item", value: "open", label: "Open", shortcut: "enter" },
	{ _tag: "Item", value: "rename", label: "Rename", shortcut: "f2" },
	{ _tag: "Item", value: "duplicate", label: "Make a copy", shortcut: "mod+d" },
	{ _tag: "Checkbox", value: "star", label: "Starred", checked: starred },
	{
		_tag: "Submenu",
		value: "move",
		label: "Move to",
		entries: [
			{ _tag: "Item", value: "move:finance", label: "Finance" },
			{ _tag: "Item", value: "move:archive", label: "Archive" },
		],
	},
	{ _tag: "Separator" },
	{ _tag: "Item", value: "trash", label: "Move to trash", tone: "danger", shortcut: "delete" },
]

const Message = UiSchema.TaggedEnum({
	ChangedMenu: { menu: ContextMenuState },
	Picked: { value: Schema.String, file: Schema.NullOr(Schema.String) },
	Starred: { on: Schema.Boolean, file: Schema.NullOr(Schema.String) },
})

// a folder's files: right-click a row, long-press it on a phone, or focus it and press Shift+F10
export const FileRows = Html.component({
	name: "FileRows",
	model: Schema.Struct({ menu: ContextMenuState, starred: Schema.Array(Schema.String), said: Schema.String }),
	message: Message,
}).make({
	init: () => ({ menu: contextMenuClosed, starred: ["roadmap"], said: "" }),
	update: {
		ChangedMenu: ($, { menu }) => $.evolve({ menu }),
		Starred: ($, { on, file }) =>
			file === null
				? $.model
				: $.evolve({ starred: (list) => (on ? [...list, file] : list.filter((id) => id !== file)), said: `${on ? "Starred" : "Unstarred"} “${nameOf(file)}”.` }),
		Picked: ($, { value, file }) => $.evolve({ said: `${done[value] ?? value} “${nameOf(file)}”.` }),
	},
	view: (h, model) =>
		h.div.attrs(sx(styles.wrap)).children(
			ContextMenu(h, {
				state: model.menu,
				onState: (menu) => Message.ChangedMenu({ menu }),
				entries: entriesFor(model.menu.target !== null && model.starred.includes(model.menu.target)),
				onSelect: (event, file) =>
					event._tag === "RequestedToggle" ? Message.Starred({ on: event.checked, file }) : Message.Picked({ value: event.value, file }),
				view: (area) =>
					h.div.attrs({ role: "list", "aria-label": "Files in Marketing", ...sx(styles.list) }).children(
						files.map((file) =>
							area(h.div.key(file.id).attrs({ role: "listitem", "aria-label": file.name }), file.id, styles.row).children(
								h.span.attrs(sx(styles.name)).children(file.name),
								model.starred.includes(file.id) ? h.span.attrs({ role: "img", "aria-label": "Starred", ...sx(styles.star) }).children("★") : null,
								h.span.attrs(sx(styles.meta)).children(file.size),
							)),
					),
			}),
			h.p.attrs({ role: "status", ...sx(styles.said) }).children(model.said),
		),
})
```

### One choice in a group

Radio items set a value and leave the menu open, so you see the change.

```ts title="src/priority.ts" source="www/src/examples/context-menu/priority.ts"
import { UiSchema } from "effect/ui"
import { Html } from "effect/ui/html"
import * as stylex from "@stylexjs/stylex"
import { Schema } from "effect"
import { ContextMenu, contextMenuClosed, ContextMenuState } from "./ui/uicontext/components/ContextMenu.ts"
import { sx } from "./ui/uicontext/components/Sx.ts"
import { color, corner, font, space, stroke } from "./ui/uicontext/components/tokens.stylex.ts"

const styles = stylex.create({
	column: { display: "grid", gap: space.sm, inlineSize: "min(100%, 18rem)" },
	card: {
		display: "grid",
		gap: space.xs,
		padding: space.md,
		borderWidth: stroke.hairline,
		borderStyle: "solid",
		borderColor: color.line,
		borderRadius: corner.card,
		backgroundColor: color.panel,
		cursor: "default",
	},
	key: { fontSize: font.xs, color: color.muted, fontVariantNumeric: "tabular-nums" },
	title: { fontSize: font.base, overflowWrap: "anywhere" },
	priority: { fontSize: font.sm, color: color.muted },
})

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

const Issue = Schema.Struct({ id: Schema.String, title: Schema.String, priority: Schema.String })

const Message = UiSchema.TaggedEnum({
	ChangedMenu: { menu: ContextMenuState },
	SetPriority: { issue: Schema.NullOr(Schema.String), priority: Schema.String },
})

// cards on a board: right-click one to change its priority without opening it
export const BoardCards = Html.component({
	name: "BoardCards",
	model: Schema.Struct({ menu: ContextMenuState, issues: Schema.Array(Issue) }),
	message: Message,
}).make({
	init: () => ({
		menu: contextMenuClosed,
		issues: [
			{ id: "ENG-142", title: "Checkout fails when the coupon field has a trailing space", priority: "urgent" },
			{ id: "ENG-139", title: "Export invoices as CSV", priority: "medium" },
			{ id: "ENG-131", title: "Dark mode for the billing portal", priority: "low" },
		],
	}),
	update: {
		ChangedMenu: ($, { menu }) => $.evolve({ menu }),
		SetPriority: ($, { issue, priority }) => $.evolve({ issues: (list) => list.map((i) => (i.id === issue ? { ...i, priority } : i)) }),
	},
	view: (h, model) => {
		const target = model.issues.find((i) => i.id === model.menu.target)
		return ContextMenu(h, {
			state: model.menu,
			onState: (menu) => Message.ChangedMenu({ menu }),
			entries: [
				{ _tag: "Radio", group: "priority", label: "Priority", value: target?.priority ?? null, options: priorities },
			],
			onSelect: (event, issue) => (event._tag === "RequestedPickRadio" ? Message.SetPriority({ issue, priority: event.value }) : undefined),
			view: (area) =>
				h.div.attrs({ role: "list", "aria-label": "In progress", ...sx(styles.column) }).children(
					model.issues.map((issue) =>
						area(h.div.key(issue.id).attrs({ role: "listitem", "aria-label": `${issue.id} ${issue.title}` }), issue.id, styles.card).children(
							h.span.attrs(sx(styles.key)).children(issue.id),
							h.span.attrs(sx(styles.title)).children(issue.title),
							h.span.attrs(sx(styles.priority)).children(priorities.find((p) => p.value === issue.priority)?.label ?? ""),
						)),
				),
		})
	},
})
```

## API reference

### ContextMenu (view function)

**Options**

| Name | Type | Description |
| --- | --- | --- |
| `key` | `string` | Names the menu among others in the same view; needed for more than one. |
| `state` (required) | `ContextMenuState` | — |
| `onState` (required) | `(state: ContextMenuState) => Message` | — |
| `entries` (required) | `MenuEntry[]` | The entries, as Menu takes them: usually built for `state.target`. |
| `onSelect` (required) | `(event: typeof MenuEvents.Type, target: string \| null) => Message` | An action picked, a checkbox toggled or a radio option chosen, with the area it was for. |
| `disabled` | `boolean` | The browser's own menu shows instead: a text field, a read-only view. |
| `view` (required) | `(area: ContextMenuArea) => View.Content` | Draws the page. `area(builder, id)` makes an element open this menu, and the id comes back as `state.target`; leave the id out for a single area. |

### Menu (component)

**Props**

| Name | Type | Description |
| --- | --- | --- |
| `label` (required) | `string` | The button's text, and its accessible name |
| `entries` (required) | `MenuEntry[]` | The menu's actions, checkbox and radio items, separators, labels and submenus, in order |
| `iconOnly` | `boolean` | Show only an icon on the button (the label still names it): "⋯" by default |
| `icon` | `string` | The icon the button shows instead of its label, by name; "chevron" draws a down chevron |
| `emphasis` | `"outline" \| "ghost"` | Outline (the default) or ghost, as Button's |
| `size` | `"xs" \| "sm" \| "md"` | "xs": a 24px icon button, for a row's or a block's actions |
| `align` | `"start" \| "end"` | Which edge of the button the menu lines up with |
| `disabled` | `boolean` | The button can't open the menu |
| `tabbable` | `boolean` | False for a row's menu that its row opens from the keyboard (Shift+F10): the button leaves the Tab order, so a long list isn't a Tab stop per row |

**Events**

| Event | Payload | Description |
| --- | --- | --- |
| `RequestedPick` | `{ value: string }` | An action was picked |
| `RequestedToggle` | `{ value: string; checked: boolean }` | A checkbox item asks for `checked` |
| `RequestedPickRadio` | `{ group: string; value: string }` | A radio item asks for `value` in its group |

### MenuPreview (view function)

**Options**

| Name | Type | Description |
| --- | --- | --- |
| `entries` (required) | `MenuEntry[]` | The items to draw, as `Menu` takes them |
| `highlighted` | `string` | The value of the item drawn as highlighted, as if the pointer were on it |

### MenuRows (view function)

**Options**

| Name | Type | Description |
| --- | --- | --- |
| `submenu` (required) | `string \| null` | The value of the submenu that's open, or null |
| `pick` (required) | `(value: string, checked: boolean \| undefined) => Message` | — |
| `openSubmenu` (required) | `(value: string) => Message` | — |
| `closeSubmenu` (required) | `(value: string) => Message` | — |

## Keyboard and accessibility

### Keys

| Keys | Does |
| --- | --- |
| Shift+F10 | On a focused area, open its menu |
| Down arrow, Up arrow | Move between items |
| Enter, Space | Pick the item, or check it |
| Right arrow, Left arrow | Open or close a submenu |
| A–Z | Jump to the next item that starts with what’s typed |
| Escape, Tab | Close the menu and put focus back |

On a Mac, Control is Command and Alt is Option. Left and Right trade places in right-to-left text.

## Installation

```sh
pnpm dlx shadcn@latest add checkfu/uicontext/context-menu
```

With npm: `npx shadcn@latest add checkfu/uicontext/context-menu`. With yarn: `yarn dlx shadcn@latest add checkfu/uicontext/context-menu`. With bun: `bunx --bun shadcn@latest add checkfu/uicontext/context-menu`.

It writes these files:

- `src/ui/uicontext/components/Button.ts`
- `src/ui/uicontext/components/ContextMenu.ts`
- `src/ui/uicontext/components/Direction.ts`
- `src/ui/uicontext/components/Kbd.ts`
- `src/ui/uicontext/components/Menu.ts`
- `src/ui/uicontext/components/Motion.ts`
- `src/ui/uicontext/components/Sx.ts`
- `src/ui/uicontext/components/button.stylex.ts`
- `src/ui/uicontext/components/tokens.stylex.ts`
- `src/ui/uicontext/components/variants.ts`

And installs the npm packages `@stylexjs/stylex`, `effect`.

## Source

- [src/ContextMenu.ts](https://github.com/checkfu/uicontext/blob/main/src/ContextMenu.ts)
- [src/Menu.ts](https://github.com/checkfu/uicontext/blob/main/src/Menu.ts)

## Used in

- [SaaS dashboard](https://uicontext.com/blocks/saas-dashboard.md)
- [Task manager](https://uicontext.com/blocks/issue-tracker.md)
- [Company brain](https://uicontext.com/blocks/doc-workspace.md)
- [Analytics dashboard](https://uicontext.com/blocks/analytics.md)
- [Email](https://uicontext.com/blocks/email.md)
- [Storefront](https://uicontext.com/blocks/storefront.md)
- [Helpdesk](https://uicontext.com/blocks/helpdesk.md)
- [Team chat](https://uicontext.com/blocks/team-chat.md)
- [Design](https://uicontext.com/blocks/design-tool.md)
- [Whiteboard](https://uicontext.com/blocks/whiteboard.md)

## Related

- [Dialog](https://uicontext.com/docs/components/dialog.md) (`dialog`): A modal window with a title, a description and actions.
- [Menu](https://uicontext.com/docs/components/menu.md) (`menu`): A dropdown menu of actions, checkbox and radio items, shortcuts and submenus.
- [Sheet](https://uicontext.com/docs/components/sheet.md) (`sheet`): A panel that slides over the page from a side or the bottom.
- [Toast](https://uicontext.com/docs/components/toast.md) (`toast`): Short notifications with an optional action like Undo.
- [Popover](https://uicontext.com/docs/components/popover.md) (`popover`): Content that opens beside its trigger and closes when you click away.
- [Hover Card](https://uicontext.com/docs/components/hover-card.md) (`hover-card`): A preview of what a link leads to, on hover or focus, such as the person behind a mention.
