Submenu context menus
Five right-click menus with nested submenus that open on hover or with the right arrow key and close with the left arrow: nested, flyout, inline, deep and wide. 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-submenuDependencies, the @ai2/tokens theme and the component file are installed together.
Install dependencies
npm install motion lucide-reactCopy the source
components/ui/context-menu-submenu.tsx"use client"
import * as React from "react"
import { ChevronDown, ChevronRight, ClipboardPaste, Copy, Share2 } from "lucide-react"
import { AnimatePresence, motion, useReducedMotion } from "motion/react"
import { cn } from "@/lib/utils"
/* Submenu context menu family: 5 nested menus. 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: rows can carry a `sub`; the submenu opens on hover
or with ArrowRight and closes with ArrowLeft. There are two modes: flyout (a panel
opening to the side) and inline (a list expanding beneath the row). NO radix.
Color comes ONLY from tokens, via alpha color-mix. */
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
sub?: StyledContextMenuItem[]
}
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"
/* The submenu can extend outside the panel, so there is NO overflow-hidden here. */
const menuBase =
"fixed z-50 origin-top-left rounded-xl border border-border bg-popover p-1.5 text-sm text-popover-foreground shadow-lg outline-none"
const subPanel =
"absolute top-0 z-50 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-3 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-3 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"
const defaultItems: StyledContextMenuItem[] = [
{ label: "Copy", icon: <Copy />, shortcut: "Ctrl C" },
{ label: "Paste", icon: <ClipboardPaste />, shortcut: "Ctrl V" },
{
label: "Share",
icon: <Share2 />,
sub: [{ label: "Copy link" }, { label: "Email" }, { label: "Embed" }],
},
{
label: "Move to",
sub: [{ label: "Inbox" }, { label: "Archive" }, { label: "Trash" }],
},
]
const deepItems: StyledContextMenuItem[] = [
{ label: "Open", icon: <Copy /> },
{
label: "Export as",
sub: [
{ label: "Image" },
{
label: "Document",
sub: [{ label: "PDF" }, { label: "Word" }, { label: "Markdown" }],
},
{
label: "Data",
sub: [{ label: "CSV" }, { label: "JSON" }],
},
],
},
{ label: "Rename" },
]
function focusFirstIn(node: HTMLElement | null) {
const first = node?.querySelector<HTMLElement>('[data-menu-item="true"]')
first?.focus()
}
function MenuItemButton({
item,
close,
}: {
item: StyledContextMenuItem
close: () => void
}) {
return (
<button
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>
)
}
/* A row carrying a submenu. Hover or ArrowRight opens it, ArrowLeft closes it and returns focus to the trigger. With mode="inline" it expands under the row instead of in a panel. */
function SubmenuRow({
item,
close,
mode,
subWidth,
gap,
}: {
item: StyledContextMenuItem
close: () => void
mode: "flyout" | "inline"
subWidth: string
gap: string
}) {
const [open, setOpen] = React.useState(false)
const reduce = useReducedMotion()
const triggerRef = React.useRef<HTMLButtonElement>(null)
const subRef = React.useRef<HTMLDivElement>(null)
const subId = React.useId()
const closeSub = React.useCallback(() => {
setOpen(false)
triggerRef.current?.focus()
}, [])
const onTriggerKey = (e: React.KeyboardEvent) => {
if (e.key === "ArrowRight") {
e.preventDefault()
e.stopPropagation()
setOpen(true)
window.requestAnimationFrame(() => focusFirstIn(subRef.current))
}
if (e.key === "ArrowLeft") {
e.preventDefault()
e.stopPropagation()
setOpen(false)
}
}
const onSubKey = (e: React.KeyboardEvent) => {
if (e.key === "ArrowLeft") {
e.preventDefault()
e.stopPropagation()
closeSub()
}
}
const anim = reduce
? { initial: { opacity: 1 }, animate: { opacity: 1 }, exit: { opacity: 1 } }
: {
initial: { opacity: 0, x: mode === "flyout" ? -6 : 0, y: mode === "inline" ? -4 : 0 },
animate: { opacity: 1, x: 0, y: 0 },
exit: { opacity: 0, x: mode === "flyout" ? -6 : 0, y: mode === "inline" ? -4 : 0 },
}
return (
<div
className="relative"
onMouseEnter={mode === "flyout" ? () => setOpen(true) : undefined}
onMouseLeave={mode === "flyout" ? () => setOpen(false) : undefined}
>
<button
ref={triggerRef}
type="button"
role="menuitem"
data-menu-item="true"
aria-haspopup="menu"
aria-expanded={open}
aria-controls={open ? subId : undefined}
onKeyDown={onTriggerKey}
onClick={() => setOpen((o) => !o)}
className={itemBase}
>
{item.icon ? (
<span className="inline-flex shrink-0" aria-hidden>
{item.icon}
</span>
) : null}
<span className="flex-1 truncate">{item.label}</span>
<span className="ml-auto inline-flex text-muted-foreground" aria-hidden>
{mode === "inline" ? (
<ChevronDown className={cn("transition-transform", open && "rotate-180")} />
) : (
<ChevronRight />
)}
</span>
</button>
<AnimatePresence>
{open ? (
<motion.div
ref={subRef}
id={subId}
role="menu"
data-slot="styled-context-menu-sub"
onKeyDown={onSubKey}
className={
mode === "inline"
? "mt-0.5 flex flex-col border-l border-border pl-2"
: cn(subPanel, subWidth, "left-full", gap)
}
initial={anim.initial}
animate={anim.animate}
exit={anim.exit}
transition={reduce ? { duration: 0 } : { duration: 0.12, ease: "easeOut" }}
>
<MenuRows
items={item.sub ?? []}
close={close}
mode={mode}
subWidth={subWidth}
gap={gap}
/>
</motion.div>
) : null}
</AnimatePresence>
</div>
)
}
function MenuRows({
items,
close,
mode,
subWidth,
gap,
}: {
items: StyledContextMenuItem[]
close: () => void
mode: "flyout" | "inline"
subWidth: string
gap: string
}) {
return (
<div className="flex flex-col">
{items.map((item, i) =>
item.sub && item.sub.length > 0 ? (
<SubmenuRow key={i} item={item} close={close} mode={mode} subWidth={subWidth} gap={gap} />
) : (
<MenuItemButton key={i} item={item} close={close} />
)
)}
</div>
)
}
/* Shared shell: the target area plus a fixed AnimatePresence menu at the cursor position. */
function SubmenuContextMenuShell({
className,
size = "md",
children,
items,
mode,
subWidth,
gap,
}: ContextMenuProps & {
items: StyledContextMenuItem[]
mode: "flyout" | "inline"
subWidth: string
gap: string
}) {
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" }}
>
<MenuRows items={items} close={close} mode={mode} subWidth={subWidth} gap={gap} />
</motion.div>
) : null}
</AnimatePresence>
</div>
)
}
/* Nested: klasik yandan acilan alt menu, panele bitisik. */
export function NestedContextMenu({ className, size, children, items }: ContextMenuProps) {
return (
<SubmenuContextMenuShell
className={className}
size={size}
items={items ?? defaultItems}
mode="flyout"
subWidth="w-48"
gap="ml-0.5"
>
{children}
</SubmenuContextMenuShell>
)
}
/* Flyout: alt menu belirgin bosluk ve derin golge ile yana ucar. */
export function FlyoutContextMenu({ className, size, children, items }: ContextMenuProps) {
return (
<SubmenuContextMenuShell
className={className}
size={size}
items={items ?? defaultItems}
mode="flyout"
subWidth="w-52 shadow-xl"
gap="ml-2"
>
{children}
</SubmenuContextMenuShell>
)
}
/* Inline: alt menu ucmaz, satirin altinda girintili olarak genisler. */
export function InlineContextMenu({ className, size, children, items }: ContextMenuProps) {
return (
<SubmenuContextMenuShell
className={className}
size={size}
items={items ?? defaultItems}
mode="inline"
subWidth="w-full"
gap=""
>
{children}
</SubmenuContextMenuShell>
)
}
/* Deep: alt menunun alt menusu, uc kademe derinlik. */
export function DeepContextMenu({ className, size, children, items }: ContextMenuProps) {
return (
<SubmenuContextMenuShell
className={className}
size={size}
items={items ?? deepItems}
mode="flyout"
subWidth="w-44"
gap="ml-0.5"
>
{children}
</SubmenuContextMenuShell>
)
}
/* Wide: wide submenu panels, for long labels. */
export function WideContextMenu({ className, size, children, items }: ContextMenuProps) {
return (
<SubmenuContextMenuShell
className={className}
size={size}
items={items ?? defaultItems}
mode="flyout"
subWidth="w-72"
gap="ml-1"
>
{children}
</SubmenuContextMenuShell>
)
}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.
Nested
A classic submenu that opens flush to the panel.
import { NestedContextMenu } from "@/components/ui/context-menu-submenu"
<NestedContextMenu />Flyout
The submenu flies out with a gap and a deeper shadow.
import { FlyoutContextMenu } from "@/components/ui/context-menu-submenu"
<FlyoutContextMenu />Inline
The submenu expands indented under its row instead of flying out.
import { InlineContextMenu } from "@/components/ui/context-menu-submenu"
<InlineContextMenu />Deep
A submenu inside a submenu, three levels deep.
import { DeepContextMenu } from "@/components/ui/context-menu-submenu"
<DeepContextMenu />Wide
Wide submenu panels for longer labels.
import { WideContextMenu } from "@/components/ui/context-menu-submenu"
<WideContextMenu />ai2 Submenu context menus: 5 styled variations on the token system
The ai2 Submenu 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 nested submenus that open on hover or the right arrow key. 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 the menu in at the cursor and slides each submenu out. The styled layer is opt-in, so the dependency only lands if you use it; the base components stay lean. Under reduced motion, the transforms are skipped and both the menu and the submenus appear instantly.
What is in the ai2 Submenu context menus?
5 exports in one file: Nested, Flyout, Inline, Deep and Wide. 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 the menu in at the cursor and slides each submenu out.
- Reduced-motion aware: Under prefers-reduced-motion, the transforms are skipped and both the menu and the submenus appear 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 Submenu 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.