Context Menu for Astro
Astro menus that open from a right click or a long press. Built with the popover component, with support for keyboard navigation, multiple selection, and more.
Installation
bunx --bun shadcn@latest add @gnostic/context-menunpx shadcn@latest add @gnostic/context-menupnpm dlx shadcn@latest add @gnostic/context-menuComplete the Installation guide first. Then copy the component files below.
Install component packages
bun add @data-slot/core @data-slot/dropdown-menuCopy the files
src/components/ui/context-menu/context-menu-checkbox-item.astro
---
import type { HTMLAttributes } from "astro/types"
import DropdownMenuCheckboxItem from "../dropdown-menu/dropdown-menu-checkbox-item.astro"
import type { ContextMenuCheckboxItemProps } from "./types.ts"
type Props = HTMLAttributes<"button"> & ContextMenuCheckboxItemProps
const {
class: className,
value,
defaultChecked,
variant,
inset,
disabled,
...props
} = Astro.props
---
<DropdownMenuCheckboxItem
class={className}
value={value}
defaultChecked={defaultChecked}
disabled={disabled ? true : undefined}
variant={variant}
inset={inset}
{...props}
>
<slot />
</DropdownMenuCheckboxItem>
src/components/ui/context-menu/context-menu-content.astro
---
import type { HTMLAttributes } from "astro/types"
import DropdownMenuContent from "../dropdown-menu/dropdown-menu-content.astro"
import type { ContextMenuContentProps } from "./types.ts"
type Props = HTMLAttributes<"div"> & ContextMenuContentProps
const {
class: className,
side,
align,
sideOffset,
alignOffset,
avoidCollisions,
collisionPadding,
...props
} = Astro.props
---
<DropdownMenuContent
class={className}
side={side}
align={align}
sideOffset={sideOffset}
alignOffset={alignOffset}
avoidCollisions={avoidCollisions}
collisionPadding={collisionPadding}
{...props}
>
<slot />
</DropdownMenuContent>
src/components/ui/context-menu/context-menu-group.astro
---
import type { HTMLAttributes } from "astro/types"
import DropdownMenuGroup from "../dropdown-menu/dropdown-menu-group.astro"
type Props = HTMLAttributes<"div">
const { class: className, ...props } = Astro.props
---
<DropdownMenuGroup class={className} {...props}>
<slot />
</DropdownMenuGroup>
src/components/ui/context-menu/context-menu-item.astro
---
import type { HTMLAttributes, HTMLTag, Polymorphic } from "astro/types"
import DropdownMenuItem from "../dropdown-menu/dropdown-menu-item.astro"
import type { ContextMenuItemProps } from "./types.ts"
type Props<T extends HTMLTag = "button"> = Polymorphic<{ as: T }> &
HTMLAttributes<T> &
ContextMenuItemProps
const { class: className, variant, inset, ...props } = Astro.props
---
<DropdownMenuItem class={className} variant={variant} inset={inset} {...props}>
<slot />
</DropdownMenuItem>
src/components/ui/context-menu/context-menu-label.astro
---
import type { HTMLAttributes } from "astro/types"
import DropdownMenuLabel from "../dropdown-menu/dropdown-menu-label.astro"
import type { ContextMenuLabelProps } from "./types.ts"
type Props = HTMLAttributes<"div"> & ContextMenuLabelProps
const { class: className, inset, ...props } = Astro.props
---
<DropdownMenuLabel class={className} inset={inset} {...props}>
<slot />
</DropdownMenuLabel>
src/components/ui/context-menu/context-menu-portal.astro
---
import type { HTMLAttributes } from "astro/types"
import DropdownMenuPortal from "../dropdown-menu/dropdown-menu-portal.astro"
type Props = HTMLAttributes<"div">
const { class: className, ...props } = Astro.props
---
<DropdownMenuPortal class={className} {...props}>
<slot />
</DropdownMenuPortal>
src/components/ui/context-menu/context-menu-radio-group.astro
---
import type { HTMLAttributes } from "astro/types"
type Props = HTMLAttributes<"div">
const { class: className, ...props } = Astro.props
---
<div
data-slot="context-menu-radio-group"
role="group"
class={className}
{...props}
>
<slot />
</div>
src/components/ui/context-menu/context-menu-radio-item.astro
---
import type { HTMLAttributes } from "astro/types"
import DropdownMenuRadioItem from "../dropdown-menu/dropdown-menu-radio-item.astro"
import type { ContextMenuRadioItemProps } from "./types.ts"
type Props = HTMLAttributes<"button"> & ContextMenuRadioItemProps
const {
class: className,
value,
defaultChecked,
variant,
inset,
disabled,
...props
} = Astro.props
---
<DropdownMenuRadioItem
class={className}
value={value}
defaultChecked={defaultChecked}
disabled={disabled ? true : undefined}
variant={variant}
inset={inset}
{...props}
>
<slot />
</DropdownMenuRadioItem>
src/components/ui/context-menu/context-menu-separator.astro
---
import type { HTMLAttributes } from "astro/types"
import DropdownMenuSeparator from "../dropdown-menu/dropdown-menu-separator.astro"
type Props = HTMLAttributes<"div">
const { class: className, ...props } = Astro.props
---
<DropdownMenuSeparator class={className} {...props} />
src/components/ui/context-menu/context-menu-shortcut.astro
---
import type { HTMLAttributes } from "astro/types"
import DropdownMenuShortcut from "../dropdown-menu/dropdown-menu-shortcut.astro"
type Props = HTMLAttributes<"span">
const { class: className, ...props } = Astro.props
---
<DropdownMenuShortcut class={className} {...props}>
<slot />
</DropdownMenuShortcut>
src/components/ui/context-menu/context-menu-trigger.astro
---
import type { HTMLAttributes } from "astro/types"
import { cn } from "cn"
type Props = HTMLAttributes<"div">
const { class: className, tabindex = 0, ...props } = Astro.props
---
<div
data-slot="context-menu-trigger"
tabindex={tabindex}
aria-haspopup="menu"
aria-expanded="false"
class={cn("select-none", className)}
{...props}
>
<slot />
</div>
src/components/ui/context-menu/context-menu.astro
---
import type { HTMLAttributes } from "astro/types"
import DropdownMenu from "../dropdown-menu/dropdown-menu.astro"
import type { ContextMenuProps } from "./types.ts"
// Coss context menu visuals come from the shared dropdown menu recipes.
// data-slot has no context menu package, so this root owns the right-click
// binding and the dropdown menu owns the popup.
type Props = HTMLAttributes<"div"> & ContextMenuProps
const {
class: className,
defaultOpen,
defaultValue,
defaultValues,
closeOnClickOutside,
closeOnEscape,
closeOnSelect,
highlightItemOnHover,
side = "bottom",
align = "center",
sideOffset = 4,
alignOffset = 0,
avoidCollisions,
collisionPadding,
lockScroll,
...props
} = Astro.props
---
<div data-slot="context-menu" class={className} {...props}>
<DropdownMenu
defaultOpen={defaultOpen}
defaultValue={defaultValue}
defaultValues={defaultValues}
closeOnClickOutside={closeOnClickOutside}
closeOnEscape={closeOnEscape}
closeOnSelect={closeOnSelect}
highlightItemOnHover={highlightItemOnHover}
side={side}
align={align}
sideOffset={sideOffset}
alignOffset={alignOffset}
avoidCollisions={avoidCollisions}
collisionPadding={collisionPadding}
lockScroll={lockScroll}
>
<!-- Point anchor. context-menu.ts moves this box to the pointer. -->
<button
data-slot="dropdown-menu-trigger"
type="button"
tabindex="-1"
aria-label="Context menu"
class="pointer-events-none fixed top-0 left-0 size-0 border-0 p-0 opacity-0"
></button>
<slot />
</DropdownMenu>
</div>
<script>
import { create, type ContextMenuController } from "./context-menu.ts"
// Destroy bindings before a view transition so the next page load binds once.
const controllers: ContextMenuController[] = []
const initialize = () => controllers.push(...create())
initialize()
document.addEventListener("astro:page-load", initialize)
document.addEventListener("astro:before-swap", () => {
for (const controller of controllers) controller.destroy()
controllers.length = 0
})
</script>
src/components/ui/context-menu/context-menu.ts
import {
clearRootBinding,
emit,
getPart,
getRootBinding,
getRoots,
hasRootBinding,
lockScroll,
on,
onRoot,
reuseRootBinding,
setRootBinding,
unlockScroll,
} from '@data-slot/core'
import { createDropdownMenu } from '@data-slot/dropdown-menu'
import type {
DropdownMenuController,
DropdownMenuHighlightChangeDetail,
DropdownMenuOpenChangeDetail,
DropdownMenuSelectDetail,
DropdownMenuSetDetail,
DropdownMenuValueChangeDetail,
DropdownMenuValuesChangeDetail,
} from '@data-slot/dropdown-menu'
/**
* Binding key for one context menu root.
* A second `createContextMenu()` call returns the controller already stored here.
*/
const BINDING_KEY = '@gnostic/context-menu'
/** Touch and pen presses that stay inside this distance count as a long press. */
const LONG_PRESS_MOVE_PX = 10
/** Hold time before a touch or pen press opens the menu. */
const LONG_PRESS_MS = 500
/**
* Clicks that follow a context-menu gesture within this window must not close
* the menu that gesture just opened.
*/
const OPEN_CLICK_GUARD_MS = 100
/** Viewport rectangle used as the dropdown menu anchor. */
interface AnchorRect {
left: number
top: number
width: number
height: number
}
/**
* Controller for one context menu.
* Item behavior, focus, and placement stay on the inner dropdown menu.
*/
export interface ContextMenuController {
/** Open the menu against the trigger bounds. */
open(): void
/** Open the menu at a viewport point. Width and height are zero. */
openAt(x: number, y: number): void
/** Close the menu. */
close(): void
/** Whether the menu popup is open. */
readonly isOpen: boolean
/** Dropdown menu controller that owns the popup and its items. */
readonly menu: DropdownMenuController
/** Remove listeners and destroy the dropdown menu controller. */
destroy(): void
}
/**
* Place the invisible dropdown trigger where the popup should anchor.
* The dropdown menu reads this element's box on open.
*/
function placeAnchor(anchor: HTMLElement, rect: AnchorRect) {
const style = anchor.style
style.position = 'fixed'
style.margin = '0'
style.padding = '0'
style.borderWidth = '0'
style.pointerEvents = 'none'
style.width = `${rect.width}px`
style.height = `${rect.height}px`
// A transformed ancestor makes fixed `top` and `left` relative to that
// ancestor. Measure that origin, then place the box on the pointer.
style.left = '0px'
style.top = '0px'
const origin = anchor.getBoundingClientRect()
style.left = `${rect.left - origin.left}px`
style.top = `${rect.top - origin.top}px`
}
/**
* True when the event target belongs to this trigger and not a nested trigger.
*/
function ownsTrigger(target: EventTarget | null, trigger: Element) {
const element =
target instanceof Element
? target
: target instanceof Node
? target.parentElement
: null
if (!element || !trigger.contains(element)) return false
return element.closest('[data-slot="context-menu-trigger"]') === trigger
}
/**
* True when the trigger is marked disabled.
*/
function isTriggerDisabled(trigger: Element) {
return (
trigger.hasAttribute('data-disabled') ||
trigger.getAttribute('aria-disabled') === 'true'
)
}
/**
* Create a context menu controller for one root.
*
* The root must contain `context-menu-trigger` and a dropdown menu with a
* trigger and content. A right click, a long press, or the context-menu key
* moves the dropdown trigger to the requested box and emits `dropdown-menu:set`.
*
* @param root - Element with `data-slot="context-menu"`.
*/
export function createContextMenu(root: Element): ContextMenuController {
const existing = reuseRootBinding<ContextMenuController>(
root,
BINDING_KEY,
'[@gnostic/context-menu] createContextMenu() called more than once for the same root. Returning the existing controller. Destroy it before rebinding.',
)
if (existing) return existing
const trigger = getPart<HTMLElement>(root, 'context-menu-trigger')
const menu = getPart<HTMLElement>(root, 'dropdown-menu')
const anchor = menu
? getPart<HTMLElement>(menu, 'dropdown-menu-trigger')
: null
const content = menu
? getPart<HTMLElement>(menu, 'dropdown-menu-content')
: null
if (!trigger || !menu || !anchor || !content) {
throw new Error(
'ContextMenu requires ContextMenuTrigger and ContextMenuContent.',
)
}
// Copy the narrowed elements so nested functions keep a definite type.
const triggerEl: HTMLElement = trigger
const menuEl: HTMLElement = menu
const anchorEl: HTMLElement = anchor
const contentEl: HTMLElement = content
const menuController =
getRootBinding<DropdownMenuController>(
menuEl,
'@data-slot/dropdown-menu',
) ?? createDropdownMenu(menuEl)
// The anchor is only a positioning box. Name the popup, then hide the anchor
// so assistive technology does not stop on an empty control.
contentEl.setAttribute('aria-label', 'Context menu')
contentEl.removeAttribute('aria-labelledby')
anchorEl.setAttribute('aria-hidden', 'true')
const cleanups: Array<() => void> = []
let destroyed = false
let openedAt = 0
let ignoreClick = false
let pressTimer: ReturnType<typeof setTimeout> | null = null
let pressX = 0
let pressY = 0
// The dropdown menu locks scroll on open, which moves the fixed containing
// block. Hold that lock before measuring the anchor so the box stays put.
let heldScrollLock = false
let repositioning = false
function menuLocksScroll() {
return menuEl.getAttribute('data-lock-scroll') !== 'false'
}
function holdScrollLock() {
if (heldScrollLock || !menuLocksScroll()) return
lockScroll()
heldScrollLock = true
}
function releaseScrollLock() {
if (!heldScrollLock) return
heldScrollLock = false
unlockScroll()
}
const controls = anchorEl.getAttribute('aria-controls')
if (controls) triggerEl.setAttribute('aria-controls', controls)
triggerEl.setAttribute('aria-haspopup', 'menu')
if (!triggerEl.hasAttribute('aria-expanded')) {
triggerEl.setAttribute('aria-expanded', 'false')
}
/**
* Move the anchor, then open. An open menu closes and opens again so the
* dropdown menu reads the new anchor box.
*/
function showAt(rect: AnchorRect) {
if (destroyed || isTriggerDisabled(triggerEl)) return
holdScrollLock()
placeAnchor(anchorEl, rect)
openedAt = performance.now()
// Closing to reposition also emits open-change. Keep the scroll lock
// until the menu stays closed.
repositioning = true
if (menuController.isOpen) {
emit<DropdownMenuSetDetail>(menuEl, 'dropdown-menu:set', {
open: false,
})
}
repositioning = false
emit<DropdownMenuSetDetail>(menuEl, 'dropdown-menu:set', {
open: true,
})
}
function openAtPoint(x: number, y: number) {
showAt({ left: x, top: y, width: 0, height: 0 })
}
function openAtTrigger() {
const rect = triggerEl.getBoundingClientRect()
showAt({
left: rect.left,
top: rect.top,
width: rect.width,
height: rect.height,
})
}
function clearPress() {
if (pressTimer === null) return
clearTimeout(pressTimer)
pressTimer = null
}
cleanups.push(
on(triggerEl, 'contextmenu', (event) => {
if (!ownsTrigger(event.target, triggerEl)) return
event.preventDefault()
event.stopPropagation()
// A completed long press already opened the menu.
if (ignoreClick) return
openAtPoint(event.clientX, event.clientY)
}),
)
cleanups.push(
on(triggerEl, 'keydown', (event) => {
if (!ownsTrigger(event.target, triggerEl)) return
const isContextKey =
event.key === 'ContextMenu' ||
(event.key === 'F10' && event.shiftKey)
if (!isContextKey) return
event.preventDefault()
openAtTrigger()
}),
)
// Touch and pen have no right click. A held press opens the menu.
cleanups.push(
on(triggerEl, 'pointerdown', (event) => {
if (event.pointerType === 'mouse' || event.button !== 0) return
if (
!ownsTrigger(event.target, triggerEl) ||
isTriggerDisabled(triggerEl)
)
return
clearPress()
pressX = event.clientX
pressY = event.clientY
pressTimer = setTimeout(() => {
pressTimer = null
ignoreClick = true
openAtPoint(pressX, pressY)
}, LONG_PRESS_MS)
}),
)
cleanups.push(
on(triggerEl, 'pointermove', (event) => {
if (pressTimer === null) return
const distance = Math.hypot(
event.clientX - pressX,
event.clientY - pressY,
)
if (distance > LONG_PRESS_MOVE_PX) clearPress()
}),
)
cleanups.push(on(triggerEl, 'pointerup', clearPress))
cleanups.push(on(triggerEl, 'pointercancel', clearPress))
cleanups.push(on(triggerEl, 'pointerleave', clearPress))
// The trigger sits inside the dropdown root, so an outside press does not
// see a primary click here. Close it unless this click opened the menu.
cleanups.push(
on(triggerEl, 'click', (event) => {
if (ignoreClick) {
ignoreClick = false
event.preventDefault()
event.stopPropagation()
return
}
if (!ownsTrigger(event.target, triggerEl)) return
if (event.ctrlKey || event.metaKey) return
if (performance.now() - openedAt < OPEN_CLICK_GUARD_MS) return
if (!menuController.isOpen) return
emit<DropdownMenuSetDetail>(menuEl, 'dropdown-menu:set', {
open: false,
})
}),
)
cleanups.push(
on(contentEl, 'contextmenu', (event) => {
event.preventDefault()
}),
)
cleanups.push(
on(menuEl, 'dropdown-menu:open-change', (event) => {
const detail = (event as CustomEvent<DropdownMenuOpenChangeDetail>)
.detail
triggerEl.setAttribute(
'aria-expanded',
detail?.open ? 'true' : 'false',
)
if (!detail?.open && !repositioning) releaseScrollLock()
emit(root, 'context-menu:open-change', detail)
}),
)
cleanups.push(
on(menuEl, 'dropdown-menu:highlight-change', (event) => {
const detail = (
event as CustomEvent<DropdownMenuHighlightChangeDetail>
).detail
emit(root, 'context-menu:highlight-change', detail)
}),
)
cleanups.push(
on(menuEl, 'dropdown-menu:select', (event) => {
const detail = (event as CustomEvent<DropdownMenuSelectDetail>)
.detail
// `emit` does not create a cancelable event. Selection must stay
// cancelable, matching the dropdown menu event.
const allowed = root.dispatchEvent(
new CustomEvent<DropdownMenuSelectDetail>(
'context-menu:select',
{ bubbles: true, cancelable: true, detail },
),
)
if (!allowed) event.preventDefault()
}),
)
cleanups.push(
on(menuEl, 'dropdown-menu:value-change', (event) => {
const detail = (event as CustomEvent<DropdownMenuValueChangeDetail>)
.detail
emit(root, 'context-menu:value-change', detail)
}),
)
cleanups.push(
on(menuEl, 'dropdown-menu:values-change', (event) => {
const detail = (
event as CustomEvent<DropdownMenuValuesChangeDetail>
).detail
emit(root, 'context-menu:values-change', detail)
}),
)
cleanups.push(
onRoot(root, 'context-menu:set', (event) => {
const detail = (event as CustomEvent<DropdownMenuSetDetail>).detail
if (!detail || typeof detail !== 'object') return
if (detail.open === true && isTriggerDisabled(triggerEl)) return
// Programmatic open uses the trigger box. A pointer open calls
// `dropdown-menu:set` directly and does not pass through here.
if (detail.open === true) {
const rect = triggerEl.getBoundingClientRect()
holdScrollLock()
placeAnchor(anchorEl, {
left: rect.left,
top: rect.top,
width: rect.width,
height: rect.height,
})
openedAt = performance.now()
repositioning = true
if (menuController.isOpen) {
emit<DropdownMenuSetDetail>(menuEl, 'dropdown-menu:set', {
open: false,
})
}
repositioning = false
}
emit(menuEl, 'dropdown-menu:set', detail)
}),
)
// A menu marked open before this script runs still uses the trigger box.
if (menuController.isOpen) openAtTrigger()
const controller: ContextMenuController = {
open: openAtTrigger,
openAt: openAtPoint,
close: () => {
if (destroyed) return
emit<DropdownMenuSetDetail>(menuEl, 'dropdown-menu:set', {
open: false,
})
},
get isOpen() {
return menuController.isOpen
},
menu: menuController,
destroy() {
if (destroyed) return
if (!clearRootBinding(root, BINDING_KEY, controller)) return
destroyed = true
clearPress()
releaseScrollLock()
for (const cleanup of cleanups) cleanup()
cleanups.length = 0
menuController.destroy()
},
}
return setRootBinding(root, BINDING_KEY, controller)
}
/**
* Find and bind every context menu in a scope.
* Roots that already have a controller are skipped.
*
* @param scope - Parent to search. Defaults to the document.
*/
export function create(scope: ParentNode = document): ContextMenuController[] {
const controllers: ContextMenuController[] = []
for (const root of getRoots(scope, 'context-menu')) {
if (hasRootBinding(root, BINDING_KEY)) continue
controllers.push(createContextMenu(root))
}
return controllers
}
src/components/ui/context-menu/index.ts
export { default as ContextMenu } from './context-menu.astro'
export { default as ContextMenuCheckboxItem } from './context-menu-checkbox-item.astro'
export { default as ContextMenuContent } from './context-menu-content.astro'
export { default as ContextMenuGroup } from './context-menu-group.astro'
export { default as ContextMenuItem } from './context-menu-item.astro'
export { default as ContextMenuLabel } from './context-menu-label.astro'
export { default as ContextMenuPortal } from './context-menu-portal.astro'
export { default as ContextMenuRadioGroup } from './context-menu-radio-group.astro'
export { default as ContextMenuRadioItem } from './context-menu-radio-item.astro'
export { default as ContextMenuSeparator } from './context-menu-separator.astro'
export { default as ContextMenuShortcut } from './context-menu-shortcut.astro'
export { default as ContextMenuTrigger } from './context-menu-trigger.astro'
export type {
ContextMenuCheckboxItemProps,
ContextMenuContentProps,
ContextMenuItemProps,
ContextMenuLabelProps,
ContextMenuProps,
ContextMenuRadioItemProps,
} from './types.ts'
src/components/ui/context-menu/types.ts
import type {
DropdownMenuContentProps,
DropdownMenuProps,
} from '../dropdown-menu/types.ts'
/**
* Options for a menu that opens from a right click or a long press.
*
* These fields match the supported dropdown menu props.
* Listen for `context-menu:*` events on this root instead.
*
* The menu locks page scroll while it is open, same as the dropdown menu.
* That keeps the popup on the pointer. Pass `lockScroll={false}` to leave
* the page free. The popup then uses absolute positioning.
*/
export interface ContextMenuProps extends DropdownMenuProps {
/**
* Preferred side of the pointer or trigger.
*
* @default "bottom"
*/
side?: DropdownMenuProps['side']
/**
* Preferred alignment against the pointer or trigger.
*
* @default "center"
*/
align?: DropdownMenuProps['align']
/**
* Distance in pixels from the pointer or trigger.
*
* @default 4
*/
sideOffset?: number
/**
* Offset in pixels from the start or end alignment.
*
* @default 0
*/
alignOffset?: number
}
/**
* Placement fields for the context menu popup.
* Set fields override the same fields on `ContextMenu`.
*/
export type ContextMenuContentProps = DropdownMenuContentProps
/**
* Props for one action in a context menu.
* Button attributes such as `class`, `disabled`, and `aria-*` pass through.
* Set `as` to render another element, such as `as="a"` for a link.
*/
export interface ContextMenuItemProps {
/**
* Visual style of the action.
* `destructive` uses the destructive foreground color.
*
* @default "default"
*/
variant?: 'default' | 'destructive'
/**
* Indent the label so it lines up with checkbox and radio labels.
*
* @default false
*/
inset?: boolean
}
/**
* Props for a context menu item that toggles one value.
* Button attributes such as `class` and `disabled` pass through.
*/
export interface ContextMenuCheckboxItemProps {
/**
* Value committed when the item is checked.
*/
value: string
/**
* Check this item when the menu root has no `defaultValues`.
*
* @default false
*/
defaultChecked?: boolean
/**
* Visual style of the action.
*
* @default "default"
*/
variant?: 'default' | 'destructive'
/**
* Indent the label.
*
* @default false
*/
inset?: boolean
}
/**
* Props for one choice in the menu radio selection.
* A context menu has one radio value. Button attributes pass through.
*/
export interface ContextMenuRadioItemProps {
/**
* Value committed when this choice is selected.
*/
value: string
/**
* Select this choice when the menu root has no `defaultValue`.
*
* @default false
*/
defaultChecked?: boolean
/**
* Visual style of the choice.
*
* @default "default"
*/
variant?: 'default' | 'destructive'
/**
* Indent the label.
*
* @default false
*/
inset?: boolean
}
/**
* Props for a non-interactive context menu label.
*/
export interface ContextMenuLabelProps {
/**
* Indent the label so it lines up with checkbox and radio labels.
*
* @default false
*/
inset?: boolean
}
Usage
---
import {
ContextMenu,
ContextMenuCheckboxItem,
ContextMenuContent,
ContextMenuGroup,
ContextMenuItem,
ContextMenuLabel,
ContextMenuRadioGroup,
ContextMenuRadioItem,
ContextMenuSeparator,
ContextMenuShortcut,
ContextMenuTrigger,
} from "@/components/ui/context-menu"
---
<ContextMenu>
<ContextMenuTrigger>Right click here</ContextMenuTrigger>
<ContextMenuContent>
<ContextMenuGroup>
<ContextMenuLabel>My Account</ContextMenuLabel>
<ContextMenuItem>Profile</ContextMenuItem>
<ContextMenuItem>Billing</ContextMenuItem>
</ContextMenuGroup>
<ContextMenuSeparator />
<ContextMenuGroup>
<ContextMenuCheckboxItem value="email">
Email notifications
</ContextMenuCheckboxItem>
<ContextMenuRadioGroup>
<ContextMenuRadioItem value="pro">Pro plan</ContextMenuRadioItem>
</ContextMenuRadioGroup>
</ContextMenuGroup>
</ContextMenuContent>
</ContextMenu>
Composition
Arrange the parts as shown for a ContextMenu:
ContextMenu
├── ContextMenuTrigger
└── ContextMenuContent
├── ContextMenuGroup
│ ├── ContextMenuLabel
│ ├── ContextMenuItem
│ └── ContextMenuItem
├── ContextMenuSeparator
└── ContextMenuGroup
├── ContextMenuCheckboxItem
├── ContextMenuRadioGroup
│ └── ContextMenuRadioItem
└── ContextMenuItem
└── ContextMenuShortcut
ContextMenuContent already renders the menu portal. Use ContextMenuPortal only when you build a custom positioner. Do not wrap ContextMenuContent in a second portal.
Visual styles follow the Coss context menu. Item layout, checkbox marks, and the popup surface use the same recipes as Dropdown Menu. There is no @data-slot/context-menu package. This component binds the right click, then opens the dropdown menu at that point.
Examples
Basic
A right-click target with account actions.
With Shortcuts
Add ContextMenuShortcut to show keyboard hints. The hint is a label. It does not register a shortcut.
With Icons
Combine icons with labels. The menu recipe sizes the icons.
With Checkboxes
Use ContextMenuCheckboxItem for toggles. Set closeOnSelect={false} when several choices should stay in the menu.
With Radio Group
Use ContextMenuRadioItem for one selection. Store the current choice on ContextMenu with defaultValue. ContextMenuRadioGroup groups the choices. The menu still has one radio value.
With Destructive Items
Use variant="destructive" for irreversible actions.
Sides
The popup opens below the pointer by default, centered, with a 4px offset. Set side, align, and sideOffset on ContextMenuContent to override that placement.
API Reference
ContextMenuProps
side?DropdownMenuProps['side']
Preferred side of the pointer or trigger.
DropdownMenuProps['side']"bottom"align?DropdownMenuProps['align']
Preferred alignment against the pointer or trigger.
DropdownMenuProps['align']"center"sideOffset?number
Distance in pixels from the pointer or trigger.
number4alignOffset?number
Offset in pixels from the start or end alignment.
number0defaultOpen?boolean
Initial open state
booleandefaultValue?string | null
Initial radio selection state
string | nulldefaultValues?string[]
Initial checkbox selection state
string[]closeOnClickOutside?boolean
Close when clicking outside
booleancloseOnEscape?boolean
Close when pressing Escape
booleancloseOnSelect?boolean
Close when an item is selected
booleanhighlightItemOnHover?boolean
Whether moving the pointer over items should highlight and focus them.
booleantrueavoidCollisions?boolean
When true, overrides side/align preferences to prevent collisions with viewport edges.
booleantruecollisionPadding?number
The padding between the content and the viewport edges when avoiding collisions.
number8lockScroll?boolean
Lock body scroll when open.
booleantrueContextMenuContentProps
side?Side
The preferred side of the trigger to render against. Will be reversed when collisions occur and `avoidCollisions` is enabled.
Side"bottom"align?Align
The preferred alignment against the trigger. May change when collisions occur.
Align"start"sideOffset?number
The distance in pixels from the trigger.
number4alignOffset?number
An offset in pixels from the "start" or "end" alignment options.
number0avoidCollisions?boolean
When true, overrides side/align preferences to prevent collisions with viewport edges.
booleantruecollisionPadding?number
The padding between the content and the viewport edges when avoiding collisions.
number8ContextMenuItemProps
variant?'default' | 'destructive'
Visual style of the action. `destructive` uses the destructive foreground color.
'default' | 'destructive'"default"inset?boolean
Indent the label so it lines up with checkbox and radio labels.
booleanfalseContextMenuCheckboxItemProps
valuestring
Value committed when the item is checked.
stringdefaultChecked?boolean
Check this item when the menu root has no `defaultValues`.
booleanfalsevariant?'default' | 'destructive'
Visual style of the action.
'default' | 'destructive'"default"inset?boolean
Indent the label.
booleanfalseContextMenuRadioItemProps
valuestring
Value committed when this choice is selected.
stringdefaultChecked?boolean
Select this choice when the menu root has no `defaultValue`.
booleanfalsevariant?'default' | 'destructive'
Visual style of the choice.
'default' | 'destructive'"default"inset?boolean
Indent the label.
booleanfalseContextMenuLabelProps
inset?boolean
Indent the label so it lines up with checkbox and radio labels.
booleanfalseEvents
Dispatch inbound events on the context menu root (data-slot="context-menu"). The root emits the outbound events.
Outbound events
| Event | Detail |
|---|---|
context-menu:open-change |
{ open: boolean, previousOpen: boolean, source: "pointer" | "keyboard" | "programmatic" | "restore" | "init", reason: "trigger" | "select" | "outside" | "escape" | "tab" | "programmatic" | "init" } |
context-menu:highlight-change |
{ value: string | null, previousValue: string | null, item: HTMLElement | null, previousItem: HTMLElement | null, source: "pointer" | "keyboard" | "programmatic" | "restore" } |
context-menu:select |
{ value: string, item: HTMLElement, itemType: "item" | "radio" | "checkbox", source: "pointer" | "keyboard", checked?: boolean } |
context-menu:value-change |
{ value: string | null, previousValue: string | null, item: HTMLElement | null, previousItem: HTMLElement | null, source: "pointer" | "keyboard" | "programmatic" | "restore" } |
context-menu:values-change |
{ values: string[], previousValues: string[], changedValue: string | null, checked: boolean | null, item: HTMLElement | null, source: "pointer" | "keyboard" | "programmatic" | "restore" } |
context-menu:select is cancelable. Call event.preventDefault() to stop the selection.
Inbound events
| Event | Detail |
|---|---|
context-menu:set |
{ open?: boolean, value?: string | null, values?: string[], highlightedValue?: string | null, source?: "programmatic" | "restore" } |
context-menu:set with open: true opens the menu against the trigger bounds. A right click opens it at the pointer instead.
Read the installed source for the complete prop types. See the dropdown menu data-slot docs for item behavior. create() in context-menu.ts binds the pointer and forwards events with on and emit from @data-slot/core.
When to use Context Menu
Use a context menu for actions tied to one object, such as a file, a row, or a card. Keep the same actions available from a visible control. A pointer user can miss a right click, and a touch user needs the long press.
Use Dropdown Menu when a button should open the menu.
Keyboard and behavior
Right click or long press the trigger. Focus the trigger and press the context-menu key or Shift+F10 to open it from the trigger bounds. Arrow keys move the highlight. Enter and Space activate the highlighted item. Escape closes the menu.
The popup uses the dropdown menu controller. Test activation, outside pointer, and focus return. Page scroll locks while the menu is open. Pass lockScroll={false} to leave the page free.
This port has no submenu parts. Coss ContextMenuSub and the shadcn submenu are not available, because the dropdown menu package has no submenu. A nested list is not a submenu. Coss checkbox variant="switch" is not available. Render a link with as="a" on ContextMenuItem.
Theme and layout
Item padding, separators, and popup shadows use the shared dropdown menu recipes. A long menu can scroll. Keep destructive wording explicit and check disabled items in both modes.