The platform for continuously improving AI agents.
import type { KeyboardEvent, ReactElement, ReactNode } from "react";
import { ContextMenu as Menu } from "radix-ui";
import { cn } from "@/lib/utils";
export type RowAction = {
label: string;
icon?: ReactNode;
destructive?: boolean;
disabled?: boolean;
onSelect: () => void;
};
// Radix opens only on the native contextmenu event, so Shift+F10 and the ContextMenu key fire one.
function openFromKeyboard(event: KeyboardEvent<HTMLElement>) {
const menuKey = event.key === "ContextMenu" || (event.shiftKey && event.key === "F10");
if (!menuKey || event.target !== event.currentTarget) return;
event.preventDefault();
const { bottom, left } = event.currentTarget.getBoundingClientRect();
event.currentTarget.dispatchEvent(
new MouseEvent("contextmenu", {
bubbles: true,
cancelable: true,
clientX: left + 8,
clientY: bottom,
})
);
}
/** Right-click, Shift+F10 or the ContextMenu key on the row opens its actions. */
export function TableRowMenu({
actions,
children,
}: {
actions: RowAction[];
children: ReactElement;
}) {
if (actions.length === 0) return children;
return (
<Menu.Root>
<Menu.Trigger
aria-haspopup="menu"
aria-keyshortcuts="Shift+F10"
asChild
onKeyDown={openFromKeyboard}
tabIndex={0}
>
{children}
</Menu.Trigger>
<Menu.Portal>
<Menu.Content
aria-label="Row actions"
className="z-60 max-h-(--radix-context-menu-content-available-height) min-w-36 overflow-y-auto rounded-md border bg-popover p-1 text-popover-foreground"
>
{actions.map(({ destructive, disabled, icon, label, onSelect }) => (
<Menu.Item
className={cn(
"flex cursor-default select-none items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:opacity-50 [&_svg]:size-4 [&_svg]:shrink-0",
destructive && "text-destructive focus:bg-destructive/20 focus:text-destructive"
)}
disabled={disabled}
key={label}
onSelect={onSelect}
>
{icon}
{label}
</Menu.Item>
))}
</Menu.Content>
</Menu.Portal>
</Menu.Root>
);
}