Check context menus
Five right-click menus with real working selection state: checkboxes, a radio group, switches, a mixed menu and a multi-select list. Selection rows keep the menu open so the state stays visible, and the state survives a close and reopen. Each is self-contained (no radix), sized, token-driven, and opens at the cursor on right click.
Installation
The styled layer is free and installs like any other ai2 component.
Run the following command
npx shadcn@latest add @ai2/context-menu-checkDependencies, the @ai2/tokens theme and the component file are installed together.
Install dependencies
npm install motion lucide-reactCopy the source
components/ui/context-menu-check.tsx"use client"
import * as React from "react"
import { Check, Circle } from "lucide-react"
import { AnimatePresence, motion, useReducedMotion } from "motion/react"
import { cn } from "@/lib/utils"
/* Check context menu family: 5 menus with selection controls. The shell is the same
as context-menu-styled - the target area opens a fixed menu at the cursor via
onContextMenu (preventDefault), and it closes on an outside pointerdown / Escape /
item selection. The difference: the rows carry real working selection state.
Checkbox rows use menuitemcheckbox + aria-checked, radio rows use menuitemradio +
aria-checked; the state is held in React state and survives the menu closing and
reopening. NO radix. Color comes ONLY from tokens. */
export type StyledSize = "sm" | "md" | "lg" | "xl"
export type StyledContextMenuItem = {
label: React.ReactNode
icon?: React.ReactNode
onSelect?: () => void
shortcut?: React.ReactNode
group?: string
danger?: boolean
/* "check" and "toggle" are independently on or off; "radio" is a single choice within a group; when undefined it is a plain row (selecting closes the menu). */
kind?: "check" | "radio" | "toggle"
value?: string
defaultChecked?: boolean
}
type ContextMenuProps = {
className?: string
size?: StyledSize
children?: React.ReactNode
items?: StyledContextMenuItem[]
}
const menuSize: Record<StyledSize, string> = {
sm: "w-48",
md: "w-56",
lg: "w-64",
xl: "w-72",
}
const targetBox =
"flex h-28 w-full select-none items-center justify-center rounded-xl border border-dashed border-border bg-[color-mix(in_oklab,var(--color-foreground)_3%,transparent)] px-6 text-center text-sm text-muted-foreground"
const menuBase =
"fixed z-50 origin-top-left overflow-hidden rounded-xl border border-border bg-popover p-1.5 text-sm text-popover-foreground shadow-lg outline-none"
const itemBase =
"flex w-full cursor-default items-center gap-2 rounded-md px-2 py-2 text-left text-sm text-popover-foreground outline-none transition-colors hover:bg-accent hover:text-accent-foreground focus-visible:bg-accent focus-visible:text-accent-foreground focus-visible:ring-[3px] focus-visible:ring-ring/50 [&>svg]:size-4 [&>svg]:shrink-0 [&>i]:text-base [&>i]:leading-none [&_svg]:size-4 [&_svg]:shrink-0 [&_i]:text-base [&_i]:leading-none"
const itemDanger =
"flex w-full cursor-default items-center gap-2 rounded-md px-2 py-2 text-left text-sm text-danger outline-none transition-colors hover:bg-[color-mix(in_oklab,var(--color-danger)_12%,transparent)] focus-visible:bg-[color-mix(in_oklab,var(--color-danger)_12%,transparent)] focus-visible:ring-[3px] focus-visible:ring-danger/40 [&>svg]:size-4 [&>svg]:shrink-0 [&>i]:text-base [&>i]:leading-none [&_svg]:size-4 [&_svg]:shrink-0 [&_i]:text-base [&_i]:leading-none"
const shortcutChip =
"ml-auto inline-flex h-5 items-center rounded border border-border bg-[color-mix(in_oklab,var(--color-foreground)_5%,transparent)] px-1.5 font-mono text-[11px] text-muted-foreground"
/* Sol taraftaki isaret kutusu: checkbox kare, radio yuvarlak. */
const markBox =
"inline-flex size-4 shrink-0 items-center justify-center rounded border border-border text-primary-foreground transition-colors"
const markBoxOn =
"border-[color-mix(in_oklab,var(--color-primary)_60%,transparent)] bg-primary"
const markDot =
"inline-flex size-4 shrink-0 items-center justify-center rounded-full border border-border transition-colors"
const markDotOn = "border-[color-mix(in_oklab,var(--color-primary)_60%,transparent)]"
/* Toggle satirlarinin sagindaki minik anahtar. */
const switchTrack =
"ml-auto inline-flex h-4 w-7 shrink-0 items-center rounded-full border border-border bg-[color-mix(in_oklab,var(--color-foreground)_10%,transparent)] p-0.5 transition-colors"
const switchTrackOn = "border-[color-mix(in_oklab,var(--color-primary)_60%,transparent)] bg-primary"
const switchThumb = "size-3 rounded-full bg-background transition-transform"
const checkItems: StyledContextMenuItem[] = [
{ label: "Show toolbar", kind: "check", value: "toolbar", defaultChecked: true },
{ label: "Show sidebar", kind: "check", value: "sidebar" },
{ label: "Show status bar", kind: "check", value: "status", defaultChecked: true },
]
const radioItems: StyledContextMenuItem[] = [
{ label: "Small", kind: "radio", value: "sm", group: "density" },
{ label: "Medium", kind: "radio", value: "md", group: "density", defaultChecked: true },
{ label: "Large", kind: "radio", value: "lg", group: "density" },
]
const toggleItems: StyledContextMenuItem[] = [
{ label: "Word wrap", kind: "toggle", value: "wrap", defaultChecked: true },
{ label: "Minimap", kind: "toggle", value: "minimap" },
{ label: "Line numbers", kind: "toggle", value: "lines", defaultChecked: true },
]
const mixedItems: StyledContextMenuItem[] = [
{ label: "Refresh", shortcut: "Ctrl R" },
{ label: "Show grid", kind: "check", value: "grid", defaultChecked: true },
{ label: "Snap to grid", kind: "check", value: "snap" },
{ label: "List", kind: "radio", value: "list", group: "view", defaultChecked: true },
{ label: "Board", kind: "radio", value: "board", group: "view" },
]
const multiItems: StyledContextMenuItem[] = [
{ label: "Design", kind: "check", value: "design", defaultChecked: true },
{ label: "Engineering", kind: "check", value: "eng", defaultChecked: true },
{ label: "Marketing", kind: "check", value: "mkt" },
{ label: "Support", kind: "check", value: "support" },
{ label: "Sales", kind: "check", value: "sales" },
]
function keyOf(item: StyledContextMenuItem, index: number) {
return item.value ?? `item-${index}`
}
/* Baslangic secim durumu itemlarin defaultChecked degerinden turer, rastgelelik yok. */
function useSelection(list: StyledContextMenuItem[]) {
const [checks, setChecks] = React.useState<Record<string, boolean>>(() => {
const next: Record<string, boolean> = {}
list.forEach((item, i) => {
if (item.kind === "check" || item.kind === "toggle") {
next[keyOf(item, i)] = item.defaultChecked ?? false
}
})
return next
})
const [radios, setRadios] = React.useState<Record<string, string>>(() => {
const next: Record<string, string> = {}
list.forEach((item, i) => {
if (item.kind === "radio" && item.defaultChecked) {
next[item.group ?? "default"] = keyOf(item, i)
}
})
return next
})
const toggle = React.useCallback((key: string) => {
setChecks((prev) => ({ ...prev, [key]: !prev[key] }))
}, [])
const pick = React.useCallback((group: string, key: string) => {
setRadios((prev) => ({ ...prev, [group]: key }))
}, [])
return { checks, radios, toggle, pick }
}
/* Shared shell: the target area plus a fixed AnimatePresence menu at the cursor position. render(close) produces the menu body. */
function CheckContextMenuShell({
className,
size = "md",
children,
render,
}: {
className?: string
size?: StyledSize
children?: React.ReactNode
render: (close: () => void) => React.ReactNode
}) {
const [open, setOpen] = React.useState(false)
const [coords, setCoords] = React.useState({ x: 0, y: 0 })
const reduce = useReducedMotion()
const menuRef = React.useRef<HTMLDivElement>(null)
const menuId = React.useId()
const close = React.useCallback(() => setOpen(false), [])
const onContextMenu = (e: React.MouseEvent) => {
e.preventDefault()
setCoords({ x: e.clientX, y: e.clientY })
setOpen(true)
}
React.useEffect(() => {
if (!open) return
const onKey = (e: KeyboardEvent) => {
if (e.key === "Escape") {
setOpen(false)
return
}
if (e.key !== "ArrowDown" && e.key !== "ArrowUp") return
const node = menuRef.current
if (!node) return
const rows = Array.from(
node.querySelectorAll<HTMLElement>('[data-menu-item="true"]')
)
if (rows.length === 0) return
e.preventDefault()
const current = rows.indexOf(document.activeElement as HTMLElement)
const next =
e.key === "ArrowDown"
? (current + 1) % rows.length
: current <= 0
? rows.length - 1
: current - 1
rows[next]?.focus()
}
const onPointer = (e: PointerEvent) => {
const node = menuRef.current
if (node && e.target instanceof Node && !node.contains(e.target)) {
setOpen(false)
}
}
window.addEventListener("keydown", onKey)
window.addEventListener("pointerdown", onPointer)
return () => {
window.removeEventListener("keydown", onKey)
window.removeEventListener("pointerdown", onPointer)
}
}, [open])
const anim = reduce
? { initial: { opacity: 1 }, animate: { opacity: 1 }, exit: { opacity: 1 } }
: {
initial: { opacity: 0, scale: 0.96 },
animate: { opacity: 1, scale: 1 },
exit: { opacity: 0, scale: 0.96 },
}
return (
<div data-slot="styled-context-menu" className="w-full">
<div
data-slot="styled-context-menu-target"
onContextMenu={onContextMenu}
className={cn(targetBox, className)}
>
{children ?? "Right-click here"}
</div>
<AnimatePresence>
{open ? (
<motion.div
ref={menuRef}
id={menuId}
role="menu"
data-slot="styled-context-menu-content"
style={{ left: coords.x, top: coords.y }}
className={cn(menuBase, menuSize[size])}
initial={anim.initial}
animate={anim.animate}
exit={anim.exit}
transition={reduce ? { duration: 0 } : { duration: 0.14, ease: "easeOut" }}
>
{render(close)}
</motion.div>
) : null}
</AnimatePresence>
</div>
)
}
/* Row rendering: menuitem / menuitemcheckbox / menuitemradio depending on kind. Selection rows leave the menu open (so the state is visible); plain rows close it. */
function SelectionRows({
list,
close,
variant,
selection,
}: {
list: StyledContextMenuItem[]
close: () => void
variant: "mark" | "switch"
selection: ReturnType<typeof useSelection>
}) {
const { checks, radios, toggle, pick } = selection
return (
<div className="flex flex-col">
{list.map((item, i) => {
const key = keyOf(item, i)
if (item.kind === "check" || item.kind === "toggle") {
const on = checks[key] ?? false
const asSwitch = variant === "switch" || item.kind === "toggle"
return (
<button
key={key}
type="button"
role="menuitemcheckbox"
aria-checked={on}
data-menu-item="true"
onClick={() => {
toggle(key)
item.onSelect?.()
}}
className={item.danger ? itemDanger : itemBase}
>
{asSwitch ? null : (
<span className={cn(markBox, on && markBoxOn)} aria-hidden>
{on ? <Check className="size-3" /> : null}
</span>
)}
<span className="flex-1 truncate">{item.label}</span>
{asSwitch ? (
<span className={cn(switchTrack, on && switchTrackOn)} aria-hidden>
<span className={cn(switchThumb, on && "translate-x-3")} />
</span>
) : null}
{item.shortcut ? <kbd className={shortcutChip}>{item.shortcut}</kbd> : null}
</button>
)
}
if (item.kind === "radio") {
const group = item.group ?? "default"
const on = radios[group] === key
return (
<button
key={key}
type="button"
role="menuitemradio"
aria-checked={on}
data-menu-item="true"
onClick={() => {
pick(group, key)
item.onSelect?.()
}}
className={item.danger ? itemDanger : itemBase}
>
<span className={cn(markDot, on && markDotOn)} aria-hidden>
{on ? <Circle className="size-2 fill-primary text-primary" /> : null}
</span>
<span className="flex-1 truncate">{item.label}</span>
{item.shortcut ? <kbd className={shortcutChip}>{item.shortcut}</kbd> : null}
</button>
)
}
return (
<button
key={key}
type="button"
role="menuitem"
data-menu-item="true"
onClick={() => {
item.onSelect?.()
close()
}}
className={item.danger ? itemDanger : itemBase}
>
{item.icon ? (
<span className="inline-flex shrink-0" aria-hidden>
{item.icon}
</span>
) : null}
<span className="flex-1 truncate">{item.label}</span>
{item.shortcut ? <kbd className={shortcutChip}>{item.shortcut}</kbd> : null}
</button>
)
})}
</div>
)
}
/* Check: bagimsiz onay kutulari, isaretliyken primary kare + tik. */
export function CheckContextMenu({ className, size, children, items }: ContextMenuProps) {
const list = items ?? checkItems
const selection = useSelection(list)
return (
<CheckContextMenuShell
className={className}
size={size}
render={(close) => (
<SelectionRows list={list} close={close} variant="mark" selection={selection} />
)}
>
{children}
</CheckContextMenuShell>
)
}
/* Radio: grup icinde tekli secim, yuvarlak isaret. */
export function RadioContextMenu({ className, size, children, items }: ContextMenuProps) {
const list = items ?? radioItems
const selection = useSelection(list)
return (
<CheckContextMenuShell
className={className}
size={size}
render={(close) => (
<SelectionRows list={list} close={close} variant="mark" selection={selection} />
)}
>
{children}
</CheckContextMenuShell>
)
}
/* Toggle: a tiny right-aligned switch instead of a checkbox. */
export function ToggleContextMenu({ className, size, children, items }: ContextMenuProps) {
const list = items ?? toggleItems
const selection = useSelection(list)
return (
<CheckContextMenuShell
className={className}
size={size}
render={(close) => (
<SelectionRows list={list} close={close} variant="switch" selection={selection} />
)}
>
{children}
</CheckContextMenuShell>
)
}
/* Mixed: plain rows, checkboxes and a radio group together. */
export function MixedContextMenu({ className, size, children, items }: ContextMenuProps) {
const list = items ?? mixedItems
const selection = useSelection(list)
return (
<CheckContextMenuShell
className={className}
size={size}
render={(close) => (
<SelectionRows list={list} close={close} variant="mark" selection={selection} />
)}
>
{children}
</CheckContextMenuShell>
)
}
/* Multi: a long multi-select list where everything can be checked at once. */
export function MultiContextMenu({ className, size, children, items }: ContextMenuProps) {
const list = items ?? multiItems
const selection = useSelection(list)
return (
<CheckContextMenuShell
className={className}
size={size}
render={(close) => (
<SelectionRows list={list} close={close} variant="mark" selection={selection} />
)}
>
{children}
</CheckContextMenuShell>
)
}Manual installs skip the @ai2/tokens theme, so add the token CSS from the theming guide or the tone colors will be missing.
Variations
5 takes on the same idea. Each is its own export, and every one accepts a size prop (sm, md, lg, xl) aligned to the base Button scale.
Check
Independent checkboxes with a primary mark when checked.
import { CheckContextMenu } from "@/components/ui/context-menu-check"
<CheckContextMenu />Radio
A single choice inside one radio group.
import { RadioContextMenu } from "@/components/ui/context-menu-check"
<RadioContextMenu />Toggle
A small right-aligned switch instead of a checkbox.
import { ToggleContextMenu } from "@/components/ui/context-menu-check"
<ToggleContextMenu />Mixed
Plain rows, checkboxes and a radio group in one menu.
import { MixedContextMenu } from "@/components/ui/context-menu-check"
<MixedContextMenu />Multi
A longer multi-select list where every row can be checked.
import { MultiContextMenu } from "@/components/ui/context-menu-check"
<MultiContextMenu />ai2 Check context menus: 5 styled variations on the token system
The ai2 Check context menus are a set of 5 decorative button variations from the styled layer of the @ai2 design system, built around right-click menus with working checkbox, radio and switch selection state. They are free and MIT licensed, and every color comes from a semantic token, so they theme with the rest of ai2 in light and dark.
Motion runs on framer-motion: framer-motion fades and scales the menu in at the cursor. The styled layer is opt-in, so the dependency only lands if you use it; the base components stay lean. Under reduced motion, the scale is skipped and the menu appears instantly.
What is in the ai2 Check context menus?
5 exports in one file: Check, Radio, Toggle, Mixed and Multi. Each renders a native button and takes a size prop (sm, md, lg, xl) aligned to the base Button. They are separate from the base Button on purpose: the base keeps its clean variant, tone and size axes, while the styled layer carries the effects.
You own the file. Copy the one category file and you have all 5 variations, with no runtime dependency on ai2 itself.
Why use it
- On-system by construction: Every color resolves to an ai2 semantic token, so the buttons follow your theme in light and dark with no extra work.
- Effect without the sprawl: The decorations live in a dedicated styled file, so the base Button keeps its clean, predictable API.
- Accessible and honest: Each renders a real button element, keeps a visible focus ring, and respects prefers-reduced-motion.
Features
- Token-driven color: No hardcoded hex or oklch; the look recolors with your theme tokens.
- framer-motion: framer-motion fades and scales the menu in at the cursor.
- Reduced-motion aware: Under prefers-reduced-motion, the scale is skipped and the menu appears instantly.
- Size aligned to the base: Every variation takes sm, md, lg and xl matching the base Button height scale, so styled and base buttons line up in a row.
Production tips
- Use it for emphasis, not everywhere: Styled buttons draw the eye. Reserve them for the one action you want people to take on a screen, and use the base Button for the rest.
- Keep labels as verbs: The decoration adds weight, so a clear action label keeps the button scannable.
- Pick one variation per surface: The variations share a family; using two different ones in the same view competes for attention.
Works with the rest of ai2
The Check context menus sit alongside the base Button and the rest of the @ai2 registry. They share the same token file, so a styled action next to a base button or a badge stays visually consistent in both modes.