Menu styled for right-click use, built on the @foldkit/ui Menu submodel. Opens at the pointer when the caller records the pointer position as maybePoint; keyboard open anchors to the trigger region.

Preview
Style

Last action: none yet · Bookmarks off · Full URLs on · Person: Pedro Duarte

Basic

Right-click (or touch long-press) opens the menu at the pointer. Tab to the region and press Enter to open it from the keyboard.

With Icons
Anchored Above
src/demo/views/context-menu.ts449 lines
import { Update } from 'foldkit'
import { Option } from 'effect'
import { Schema as S } from 'effect'
import { modifyFields } from 'foldkit/struct'
import { defineMessageUnion } from 'foldkit/message'
import type { Html, HtmlBuilder } from 'foldkit/html'
import { Clipboard, Copy, Scissors, Trash2 } from 'lucide'

import { Menu as FoldkitMenu } from '@foldkit/ui'

import * as ContextMenu from '../../generated/registry/ui/context-menu'
import { icon } from '../../generated/registry/lib/icons'
import { DemoMenu } from '../bundles'
import { keepOpenOnSelect, subMenu } from '../menu-family'
import { cn } from '../../generated/registry/lib/utils'

import { defineSlice, type UpdateReturn } from '../slice'
import type { Model, Message as AppMessage } from '../assemble'

export const Message = defineMessageUnion({
  GotCtxBasicMenuMessage: { message: ContextMenu.Message },
  GotCtxIconsMenuMessage: { message: ContextMenu.Message },
  GotCtxTopMenuMessage: { message: ContextMenu.Message },
  RecordedCtxPoint: { maybePoint: S.Option(ContextMenu.Point) },
  GotCtxBasicSubMenuMessage: { message: ContextMenu.Message },
  OpenedCtxBasicSubMenu: {},
  ClosedCtxBasicSubMenu: {},
})

// Sections mirror apps/v4/examples/base/context-menu-demo.tsx. Right-click on
// a region opens its menu: foldkit's `h.OnContextMenu` suppresses the native
// menu and the handler injects the primitive's `Opened` message. The panel
// anchors to the pointer: pointerdown (right button, or touch/pen) records the
// client point in `ctxPoint`, which moves the zero-size trigger there before
// the menu opens. Keyboard open (Tab to the trigger, Enter/ArrowDown) has no
// point and anchors to the region. Item kinds are foldcn-built over the
// primitive's flat `{ className, content }` rows: the checkbox/radio rows keep
// the panel open (`keepOpenOnSelect`), "More Tools" is a nested menu
// (`subMenu`), and Delete uses the destructive row class. See menu-family.ts.

const BASIC_ITEMS = [
  'Back',
  'Forward',
  'Reload',
  'More Tools',
  'Show Bookmarks',
  'Show Full URLs',
  'Pedro Duarte',
  'Colm Tuite',
] as const

const BASIC_SUB_INDEX = BASIC_ITEMS.indexOf('More Tools')
const BASIC_SUB_ITEMS = [
  'Save Page...',
  'Create Shortcut...',
  'Name Window...',
  'Developer Tools',
  'Delete',
] as const

const BASIC_SHORTCUTS = new Map<string, string>([
  ['Back', '⌘['],
  ['Forward', '⌘]'],
  ['Reload', '⌘R'],
])

const basicGroupKey = (item: string): string => {
  if (item === 'Back' || item === 'Forward' || item === 'Reload') return 'nav'
  if (item === 'More Tools') return 'tools'
  if (item === 'Show Bookmarks' || item === 'Show Full URLs') return 'appearance'
  return 'people'
}

const ICON_ITEMS = ['Copy', 'Cut', 'Paste', 'Delete'] as const

const ICONS = new Map<string, typeof Copy>([
  ['Copy', Copy],
  ['Cut', Scissors],
  ['Paste', Clipboard],
  ['Delete', Trash2],
])

const ICON_SHORTCUTS = new Map<string, string>([
  ['Copy', '⌘C'],
  ['Cut', '⌘X'],
  ['Paste', '⌘V'],
  ['Delete', '⌫'],
])

const TOP_ITEMS = ['Back', 'Forward', 'Reload'] as const

const fields = {
  ctxPoint: S.Option(ContextMenu.Point),
  ctxBasicMenu: ContextMenu.Model,
  ctxIconsMenu: ContextMenu.Model,
  ctxTopMenu: ContextMenu.Model,
  ctxBasicSubMenu: ContextMenu.Model,
  showBookmarks: S.Boolean,
  showFullUrls: S.Boolean,
  person: S.String,
  lastContextAction: S.String,
}

const stateSchema = S.Struct(fields)
type State = typeof stateSchema.Type

const basicCheckOn = (model: State, item: string): boolean => {
  if (item === 'Show Bookmarks') return model.showBookmarks
  if (item === 'Show Full URLs') return model.showFullUrls
  return false
}

const isBasicRadio = (item: string): boolean => item === 'Pedro Duarte' || item === 'Colm Tuite'

const basicItemConfig = (
  model: State,
  h: HtmlBuilder<AppMessage>,
  item: string,
): ContextMenu.ItemConfig => {
  const shortcut = BASIC_SHORTCUTS.get(item)
  if (item === 'Show Bookmarks' || item === 'Show Full URLs') {
    return {
      className: ContextMenu.contextMenuCheckboxItemClass,
      content: h.span(
        [h.Class('contents')],
        [item, ContextMenu.contextMenuItemIndicator(h, basicCheckOn(model, item))],
      ),
    }
  }
  if (isBasicRadio(item)) {
    return {
      className: ContextMenu.contextMenuRadioItemClass,
      content: h.span(
        [h.Class('contents')],
        [item, ContextMenu.contextMenuItemIndicator(h, model.person === item)],
      ),
    }
  }
  return {
    content:
      shortcut === undefined
        ? h.span([], [item])
        : h.span(
            [h.Class('flex w-full items-center gap-2')],
            [
              h.span([], [item]),
              h.span([h.Class(ContextMenu.contextMenuShortcutClass)], [shortcut]),
            ],
          ),
  }
}

// Region wiring shared by the three demos: keydown clears the stale point so
// a keyboard open anchors to the region, pointerdown records the new one.
const regionAttributes = (h: HtmlBuilder<AppMessage>, opened: AppMessage) => [
  h.OnPointerDown((pointerType, button, _sx, _sy, _t, clientX, clientY) =>
    Option.some(
      Message.RecordedCtxPoint({
        maybePoint: ContextMenu.pointFromPointerDown(pointerType, button, clientX, clientY),
      }),
    ),
  ),
  h.OnKeyDown(() => Message.RecordedCtxPoint({ maybePoint: Option.none() })),
  h.OnContextMenu(opened),
]

const pointWhileOpen = (
  menu: ContextMenu.Model,
  point: Option.Option<ContextMenu.Point>,
): Option.Option<ContextMenu.Point> => (menu.isOpen ? point : Option.none())

export const contextMenuView = (model: Model, h: HtmlBuilder<AppMessage>): Html =>
  h.div(
    [h.Class('flex w-full flex-col gap-8')],
    [
      h.p(
        [h.Class('px-1 text-xs text-muted-foreground')],
        [
          `Last action: ${model.lastContextAction} · Bookmarks ${model.showBookmarks ? 'on' : 'off'} · Full URLs ${model.showFullUrls ? 'on' : 'off'} · Person: ${model.person}`,
        ],
      ),
      h.div(
        [h.Class('flex w-full flex-col gap-2')],
        [
          h.div([h.Class('px-1 text-xs font-medium text-muted-foreground')], ['Basic']),
          h.div(
            [
              h.Class(
                'flex aspect-[2/0.5] w-full items-center justify-center rounded-lg border border-dashed text-sm',
              ),
              ...regionAttributes(
                h,
                Message.GotCtxBasicMenuMessage({
                  message: ContextMenu.Message.Opened({ maybeActiveItemIndex: Option.none() }),
                }),
              ),
            ],
            [
              h.submodel({
                slotId: model.ctxBasicMenu.id,
                model: model.ctxBasicMenu,
                view: DemoMenu.view,
                viewInputs: ContextMenu.viewInputs<string>({
                  maybePoint: pointWhileOpen(model.ctxBasicMenu, model.ctxPoint),
                  items: BASIC_ITEMS,
                  buttonContent: h.span([], ['Right click here']),
                  itemsClass: 'w-48',
                  itemGroupKey: (item) => basicGroupKey(item),
                  groupToHeading: (groupKey) =>
                    groupKey === 'people' ? { content: h.span([], ['People']) } : undefined,
                  isItemDisabled: (item) => item === 'Forward',
                  contentAttributes: basicSub.parentKeys(h, model, Message.OpenedCtxBasicSubMenu()),
                  itemToConfig: (item) =>
                    item === 'More Tools'
                      ? {
                          className: cn(
                            ContextMenu.contextMenuSubTriggerClass,
                            model.ctxBasicSubMenu.isOpen &&
                              ContextMenu.contextMenuSubTriggerOpenClass,
                          ),
                          content: h.submodel({
                            slotId: model.ctxBasicSubMenu.id,
                            model: model.ctxBasicSubMenu,
                            view: DemoMenu.view,
                            viewInputs: ContextMenu.subViewInputs<string>({
                              items: BASIC_SUB_ITEMS,
                              buttonContent: h.span(
                                [h.Class('flex w-full items-center')],
                                [h.span([], [item]), ContextMenu.contextMenuSubTriggerChevron(h)],
                              ),
                              itemsClass: 'w-44',
                              contentAttributes: basicSub.subKeys(
                                h,
                                Message.ClosedCtxBasicSubMenu(),
                              ),
                              itemToConfig: (subItem) =>
                                subItem === 'Delete'
                                  ? {
                                      className: ContextMenu.contextMenuItemDestructiveClass,
                                      content: h.span([], [subItem]),
                                    }
                                  : { content: h.span([], [subItem]) },
                            }),
                            toParentMessage: (message) =>
                              Message.GotCtxBasicSubMenuMessage({ message }),
                          }),
                        }
                      : basicItemConfig(model, h, item),
                }),
                toParentMessage: (message) => Message.GotCtxBasicMenuMessage({ message }),
              }),
            ],
          ),
          h.p(
            [h.Class('px-1 text-xs text-muted-foreground')],
            [
              'Right-click (or touch long-press) opens the menu at the pointer. Tab to the region and press Enter to open it from the keyboard.',
            ],
          ),
        ],
      ),
      h.div(
        [h.Class('flex w-full flex-col gap-2')],
        [
          h.div([h.Class('px-1 text-xs font-medium text-muted-foreground')], ['With Icons']),
          h.div(
            [
              h.Class(
                'flex aspect-[2/0.5] w-full items-center justify-center rounded-lg border border-dashed text-sm',
              ),
              ...regionAttributes(
                h,
                Message.GotCtxIconsMenuMessage({
                  message: ContextMenu.Message.Opened({ maybeActiveItemIndex: Option.none() }),
                }),
              ),
            ],
            [
              h.submodel({
                slotId: model.ctxIconsMenu.id,
                model: model.ctxIconsMenu,
                view: DemoMenu.view,
                viewInputs: ContextMenu.viewInputs<string>({
                  maybePoint: pointWhileOpen(model.ctxIconsMenu, model.ctxPoint),
                  items: ICON_ITEMS,
                  buttonContent: h.span([], ['Right click — Copy / Cut / Paste']),
                  itemsClass: 'w-44',
                  itemToConfig: (item) => ({
                    className: item === 'Delete' ? ContextMenu.contextMenuItemDestructiveClass : '',
                    content: h.span(
                      [h.Class('flex w-full items-center gap-2')],
                      [
                        icon(h, ICONS.get(item) ?? Copy),
                        h.span([], [item]),
                        h.span(
                          [h.Class(ContextMenu.contextMenuShortcutClass)],
                          [ICON_SHORTCUTS.get(item) ?? ''],
                        ),
                      ],
                    ),
                  }),
                }),
                toParentMessage: (message) => Message.GotCtxIconsMenuMessage({ message }),
              }),
            ],
          ),
        ],
      ),
      h.div(
        [h.Class('flex w-full flex-col gap-2')],
        [
          h.div([h.Class('px-1 text-xs font-medium text-muted-foreground')], ['Anchored Above']),
          h.div(
            [
              h.Class(
                'flex aspect-[2/0.5] w-full items-center justify-center rounded-lg border border-dashed text-sm',
              ),
              ...regionAttributes(
                h,
                Message.GotCtxTopMenuMessage({
                  message: ContextMenu.Message.Opened({ maybeActiveItemIndex: Option.none() }),
                }),
              ),
            ],
            [
              h.submodel({
                slotId: model.ctxTopMenu.id,
                model: model.ctxTopMenu,
                view: DemoMenu.view,
                viewInputs: ContextMenu.viewInputs<string>({
                  maybePoint: pointWhileOpen(model.ctxTopMenu, model.ctxPoint),
                  items: TOP_ITEMS,
                  buttonContent: h.span([], ['Right click — opens above']),
                  anchor: { placement: 'top-start', gap: 4, padding: 8 },
                  itemsClass: 'w-36',
                  isItemDisabled: (item) => item === 'Forward',
                  itemToConfig: (item) => ({ content: h.span([], [item]) }),
                }),
                toParentMessage: (message) => Message.GotCtxTopMenuMessage({ message }),
              }),
            ],
          ),
        ],
      ),
    ],
  )

const recordAction = (action: string) => (model: State) => ({
  model: modifyFields(model, { lastContextAction: () => action }),
})

const foldActionOutMessage =
  (prefix: string) =>
  ({ value }: FoldkitMenu.OutMessage): Update.Step<State, AppMessage> =>
    recordAction(`${prefix}: ${value}`)

// Checkbox/radio rows keep the panel open: the slice applies the toggle for
// `SelectedItem` and never forwards it to the primitive (`keepOpenOnSelect`).
const isKeptOpen = (value: string): boolean =>
  value === 'Show Bookmarks' || value === 'Show Full URLs' || isBasicRadio(value)

const toggleBasic =
  (value: string): Update.Step<State, AppMessage> =>
  (model) => ({
    model: modifyFields(model, {
      showBookmarks: () =>
        value === 'Show Bookmarks' ? !model.showBookmarks : model.showBookmarks,
      showFullUrls: () => (value === 'Show Full URLs' ? !model.showFullUrls : model.showFullUrls),
      person: () => (isBasicRadio(value) ? value : model.person),
      lastContextAction: () => value,
    }),
  })

// "More Tools" is the nested menu (menu-family.ts).
const basicSub = subMenu<State, AppMessage>({
  readParent: (model) => model.ctxBasicMenu,
  writeParent: (model, next) => modifyFields(model, { ctxBasicMenu: () => next }),
  readSub: (model) => model.ctxBasicSubMenu,
  writeSub: (model, next) => modifyFields(model, { ctxBasicSubMenu: () => next }),
  toParentMessage: (message) => Message.GotCtxBasicMenuMessage({ message }),
  toSubMessage: (message) => Message.GotCtxBasicSubMenuMessage({ message }),
  subIndex: BASIC_SUB_INDEX,
  foldParentSelected: foldActionOutMessage('Basic'),
  foldSubSelected: foldActionOutMessage('More Tools'),
})

const foldCtxIcons = Update.foldChild({
  update: DemoMenu.update,
  read: (model: State) => Option.some(model.ctxIconsMenu),
  write: (model, next) => modifyFields(model, { ctxIconsMenu: () => next }),
  toParentMessage: (message) => Message.GotCtxIconsMenuMessage({ message }),
  foldOutMessage: foldActionOutMessage('Icons'),
})

const foldCtxTop = Update.foldChild({
  update: DemoMenu.update,
  read: (model: State) => Option.some(model.ctxTopMenu),
  write: (model, next) => modifyFields(model, { ctxTopMenu: () => next }),
  toParentMessage: (message) => Message.GotCtxTopMenuMessage({ message }),
  foldOutMessage: foldActionOutMessage('Above'),
})

export const slice = defineSlice({
  fields,
  init: {
    ctxPoint: Option.none(),
    ctxBasicMenu: ContextMenu.init({ id: 'context-menu-basic' }),
    ctxBasicSubMenu: ContextMenu.init({ id: 'context-menu-basic-sub', isAnimated: false }),
    ctxIconsMenu: ContextMenu.init({ id: 'context-menu-icons' }),
    ctxTopMenu: ContextMenu.init({ id: 'context-menu-top' }),
    showBookmarks: true,
    showFullUrls: false,
    person: 'Pedro Duarte',
    lastContextAction: 'none yet',
  },
  messages: [
    Message.GotCtxBasicMenuMessage,
    Message.GotCtxIconsMenuMessage,
    Message.GotCtxTopMenuMessage,
    Message.RecordedCtxPoint,
    Message.GotCtxBasicSubMenuMessage,
    Message.OpenedCtxBasicSubMenu,
    Message.ClosedCtxBasicSubMenu,
  ],
  handlers: (model: State) => ({
    GotCtxBasicMenuMessage: (payload: typeof Message.GotCtxBasicMenuMessage.Type): UpdateReturn =>
      keepOpenOnSelect<State, AppMessage>({
        items: BASIC_ITEMS,
        readMenu: (state) => state.ctxBasicMenu,
        isKept: isKeptOpen,
        onSelected: toggleBasic,
        forward: basicSub.handleParent,
      })(model, payload.message),
    GotCtxIconsMenuMessage: (payload: typeof Message.GotCtxIconsMenuMessage.Type): UpdateReturn =>
      foldCtxIcons(model, payload.message),
    GotCtxTopMenuMessage: (payload: typeof Message.GotCtxTopMenuMessage.Type): UpdateReturn =>
      foldCtxTop(model, payload.message),
    GotCtxBasicSubMenuMessage: (
      payload: typeof Message.GotCtxBasicSubMenuMessage.Type,
    ): UpdateReturn => basicSub.handleSub(model, payload.message),
    RecordedCtxPoint: (payload: typeof Message.RecordedCtxPoint.Type): UpdateReturn => ({
      model: modifyFields(model, { ctxPoint: () => payload.maybePoint }),
    }),
    OpenedCtxBasicSubMenu: (): UpdateReturn => basicSub.openSub(model),
    ClosedCtxBasicSubMenu: (): UpdateReturn => basicSub.closeSub(model),
  }),
  samples: [],
})

This code is shown verbatim — it’s the exact file used for this preview. Much of the surrounding wiring (slice, fields, messages, handlers) belongs to this site’s demo harness; you only need the view and the state that matters for your own app. Adapt what you need.

Installation

Add this component to your project:

pnpm dlx shadcn@latest add @foldcn/context-menu

Source

The component ships as plain source — no build step, no wrapper. Copy it and make it yours.

registry/default/ui/context-menu.ts297 lines
/** Stateful submodel — import the whole module as a namespace and wire its
 *  Model/Message/init/update into your app:
 *  `import * as ContextMenu from '@/components/ui/context-menu'`
 */
import { Menu as FoldkitMenu } from '@foldkit/ui'
import type { AnchorConfig } from '@foldkit/ui/menu'
import { Option, Schema as S } from 'effect'
import {
  childAttributes,
  inertHtml,
  type ChildAttribute,
  type Html,
  type HtmlBuilder,
} from 'foldkit/html'
import { Check, ChevronRight } from 'lucide'

import { icon } from '@/lib/icons'

import { cn } from '@/lib/utils'

// Re-export the @foldkit/ui Menu surface. A context menu is a Menu variant
// whose trigger is moved to the pointer: the caller records the right-click
// (or touch long-press) position as a `Point`, passes it to `viewInputs` as
// `maybePoint`, and the trigger becomes a zero-size fixed element at that
// point. foldkit's anchor positioning (flip + shift with the anchor padding)
// then places the panel at the pointer and keeps it inside the viewport.
// Without a point (keyboard open) the trigger keeps its normal place. The
// trigger is the anchor, so content passed as `buttonContent` travels with it
// while the menu is open; region content that must stay in place belongs
// beside the submodel.

export const create = FoldkitMenu.create
export const init = (config: InitConfig): Model => FoldkitMenu.init({ isAnimated: true, ...config })
export const buttonId = FoldkitMenu.buttonId
export const Model = FoldkitMenu.Model
export type Model = typeof Model.Type
export const Message = FoldkitMenu.Message
export type Message = typeof Message.Type
export const OutMessage = FoldkitMenu.OutMessage
export type OutMessage = typeof OutMessage.Type

// Remaining gaps vs upstream: items highlight via data-active (upstream
// focus:) per the derivation mapping. The panel's data-side is emitted from
// the anchor placement (foldkit anchors expose placement, not side). Per-item
// data-slot (context-menu-item etc) cannot be stamped — primitive has no
// per-item attribute hook. The primitive's item config is `{ className, content }`
// over one flat level, so item kinds are foldcn-owned: destructive/inset via
// `contextMenuItemDestructiveClass` / `contextMenuItemInsetClass`; checkbox/radio
// via `contextMenuItemIndicator` (keep the panel open by handling `SelectedItem`
// yourself instead of forwarding it to `update`, which would close the menu);
// submenus via a nested bundle built with `subViewInputs` that the consumer
// slice opens/closes and key-coordinates (see the web menu demo).

/** Viewport (client) coordinates of the pointer that requested the menu. */
export const Point = S.Struct({ x: S.Number, y: S.Number })
export type Point = typeof Point.Type

/** Pointer-down handler result: the point for a right-click or a touch/pen
 *  press (which becomes a long-press `contextmenu` on touch browsers that
 *  fire it), none for other buttons. Wire it to the region's `h.OnPointerDown`
 *  alongside `h.OnContextMenu(Opened)`. */
export const pointFromPointerDown = (
  pointerType: string,
  button: number,
  clientX: number,
  clientY: number,
): Option.Option<Point> =>
  button === 2 || pointerType === 'touch' || pointerType === 'pen'
    ? Option.some({ x: clientX, y: clientY })
    : Option.none()

export type Bundle<Item extends string = string> = FoldkitMenu.Bundle<Item>
export type InitConfig = FoldkitMenu.InitConfig
export type ViewInputs<Item extends string = string> = FoldkitMenu.ViewInputs<Item>
export type ItemConfig = FoldkitMenu.ItemConfig
export type GroupHeading = FoldkitMenu.GroupHeading

export const contextMenuTriggerClass = 'select-none'

export const contextMenuItemsClass =
  'data-enter:animate-in data-leave:animate-out data-leave:fade-out-0 data-enter:fade-in-0 data-leave:zoom-out-95 data-enter:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 ring-foreground/10 text-popover-foreground min-w-36 rounded-lg p-1 shadow-md ring-1 duration-100 not-data-[side=bottom]:data-[placement=bottom]:slide-in-from-top-2 not-data-[side=left]:data-[placement=left]:slide-in-from-right-2 not-data-[side=right]:data-[placement=right]:slide-in-from-left-2 not-data-[side=top]:data-[placement=top]:slide-in-from-bottom-2 data-[side=inline-start]:slide-in-from-right-2 data-[side=inline-end]:slide-in-from-left-2 animate-none! relative before:pointer-events-none before:absolute before:inset-0 before:-z-1 before:rounded-[inherit] before:backdrop-blur-2xl before:backdrop-saturate-150 **:data-[slot$=-item]:focus:bg-foreground/10 **:data-[slot$=-item]:data-highlighted:bg-foreground/10 **:data-[slot$=-separator]:bg-foreground/5 **:data-[slot$=-trigger]:focus:bg-foreground/10 **:data-[slot$=-trigger]:aria-expanded:bg-foreground/10! **:data-[variant=destructive]:focus:bg-foreground/10! **:data-[variant=destructive]:text-accent-foreground! **:data-[variant=destructive]:**:text-accent-foreground! bg-popover z-50 max-h-(--available-height) origin-(--transform-origin) overflow-x-hidden overflow-y-auto outline-none'

export const contextMenuItemsAnimatedClass = contextMenuItemsClass

export const contextMenuItemClass =
  'focus:bg-accent focus:text-accent-foreground data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 dark:data-[variant=destructive]:focus:bg-destructive/20 data-[variant=destructive]:focus:text-destructive data-[variant=destructive]:*:[svg]:text-destructive focus:*:[svg]:text-accent-foreground gap-1.5 rounded-md px-1.5 py-1 text-sm data-inset:pl-7 [&_svg:not([class*=\'size-\'])]:size-4 group/context-menu-item relative flex cursor-default items-center outline-hidden select-none data-active:bg-accent data-active:text-accent-foreground data-disabled:pointer-events-none data-disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0'

export const contextMenuSeparatorClass = 'bg-border -mx-1 my-1 h-px'

export const contextMenuHeadingClass = 'text-muted-foreground px-1.5 py-1 text-xs font-medium data-inset:pl-7'

export const contextMenuShortcutClass = 'text-muted-foreground group-focus/context-menu-item:text-accent-foreground ml-auto text-xs tracking-widest group-data-active/context-menu-item:text-accent-foreground'

export const contextMenuSubTriggerClass =
  'focus:bg-accent focus:text-accent-foreground data-open:bg-accent data-open:text-accent-foreground gap-1.5 rounded-md px-1.5 py-1 text-sm data-inset:pl-7 [&_svg:not([class*=\'size-\'])]:size-4 group/context-menu-item relative flex cursor-default items-center outline-hidden select-none data-active:bg-accent data-active:text-accent-foreground data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0'

/** Highlight for the parent row while its submenu is open. */
export const contextMenuSubTriggerOpenClass = 'bg-accent text-accent-foreground'

/** Upstream `ContextMenuSubContent` string (the nested panel). */
export const contextMenuSubContentClass =
  'data-enter:animate-in data-leave:animate-out data-leave:fade-out-0 data-enter:fade-in-0 data-leave:zoom-out-95 data-enter:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 text-popover-foreground min-w-32 rounded-lg border p-1 shadow-lg duration-100 animate-none! relative before:pointer-events-none before:absolute before:inset-0 before:-z-1 before:rounded-[inherit] before:backdrop-blur-2xl before:backdrop-saturate-150 **:data-[slot$=-item]:focus:bg-foreground/10 **:data-[slot$=-item]:data-highlighted:bg-foreground/10 **:data-[slot$=-separator]:bg-foreground/5 **:data-[slot$=-trigger]:focus:bg-foreground/10 **:data-[slot$=-trigger]:aria-expanded:bg-foreground/10! **:data-[variant=destructive]:focus:bg-foreground/10! **:data-[variant=destructive]:text-accent-foreground! **:data-[variant=destructive]:**:text-accent-foreground! bg-popover z-50 max-h-(--available-height) w-auto origin-(--transform-origin) overflow-x-hidden overflow-y-auto outline-none'

/** Row className for upstream `variant="destructive"`. */
export const contextMenuItemDestructiveClass = 'text-destructive data-active:bg-destructive/10 data-active:text-destructive dark:data-active:bg-destructive/20 [&_svg]:text-destructive!'

/** Row className for upstream `inset`. */
export const contextMenuItemInsetClass = 'pl-7'

/** Upstream `ContextMenuCheckboxItem` / `ContextMenuRadioItem` strings, with
 *  the foldkit highlight twin. */
export const contextMenuCheckboxItemClass =
  'focus:bg-accent focus:text-accent-foreground gap-1.5 rounded-md py-1 pr-8 pl-1.5 text-sm data-inset:pl-7 [&_svg:not([class*=\'size-\'])]:size-4 data-active:bg-accent data-active:text-accent-foreground relative flex cursor-default items-center outline-hidden select-none data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0'

export const contextMenuRadioItemClass =
  'focus:bg-accent focus:text-accent-foreground gap-1.5 rounded-md py-1 pr-8 pl-1.5 text-sm data-inset:pl-7 [&_svg:not([class*=\'size-\'])]:size-4 data-active:bg-accent data-active:text-accent-foreground relative flex cursor-default items-center outline-hidden select-none data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0'

export const contextMenuItemIndicatorClass = 'absolute right-2 pointer-events-none'

/** Check indicator for a checkbox or radio row: render it inside the row's
 *  `content` (empty when unchecked) and give the row `contextMenuCheckboxItemClass`
 *  / `contextMenuRadioItemClass`. */
export const contextMenuItemIndicator = <M>(h: HtmlBuilder<M>, isChecked: boolean): Html =>
  h.span(
    [
      h.Class(contextMenuItemIndicatorClass),
      h.DataAttribute('slot', 'context-menu-item-indicator'),
    ],
    isChecked ? [icon(h, Check)] : [],
  )

/** Trailing chevron for a submenu trigger row. */
export const contextMenuSubTriggerChevron = <M>(h: HtmlBuilder<M>): Html =>
  icon(h, ChevronRight, 'rtl:rotate-180 ml-auto size-4')

export const contextMenuBackdropClass = 'fixed inset-0 z-0'

export const contextMenuWrapperClass = 'relative inline-block'

// Applied only while a pointer point is set: the trigger collapses to an
// invisible zero-size anchor (positioned by inline style) at the pointer.
export const contextMenuTriggerAnchorClass = 'pointer-events-none size-0 opacity-0'

export const CONTEXT_MENU_ANCHOR: AnchorConfig = {
  placement: 'bottom-start',
  gap: 4,
  padding: 8,
}

export type ContextMenuViewInputsConfig<Item extends string> = Readonly<{
  items: ReadonlyArray<Item>
  itemToConfig: ViewInputs<Item>['itemToConfig']
  buttonContent: Html
  /** Where the pointer requested the menu; the panel anchors here. */
  maybePoint?: Option.Option<Point>
  anchor?: AnchorConfig
  isItemDisabled?: (item: Item, index: number) => boolean
  itemToSearchText?: (item: Item, index: number) => string
  isButtonDisabled?: boolean
  isAnimated?: boolean
  itemGroupKey?: (item: Item, index: number) => string
  groupToHeading?: (groupKey: string) => GroupHeading | undefined
  triggerClass?: string
  itemsClass?: string
  itemClass?: string
  backdropClass?: string
  wrapperClass?: string
  separatorClass?: string
  groupClass?: string
  ariaLabel?: string
  ariaLabelledBy?: string
  /** Extra trigger attributes. Build them with `childAttributes` so handlers
   *  dispatch through your own update. */
  triggerAttributes?: ReadonlyArray<ChildAttribute>
  /** Extra panel attributes (used for submenu ArrowRight/ArrowLeft). */
  contentAttributes?: ReadonlyArray<ChildAttribute>
}>

/** Build styled `Menu.ViewInputs` for a context menu with foldcn's classes. */
export const viewInputs = <Item extends string>(
  config: ContextMenuViewInputsConfig<Item>,
): ViewInputs<Item> => {
  // Upstream slide-in variants key on data-side; foldkit anchors expose
  // placement ("bottom-start"), so derive the physical side here.
  const anchor = config.anchor ?? CONTEXT_MENU_ANCHOR
  const side = (anchor.placement ?? 'bottom').split('-')[0] || 'bottom'
  return {
    items: config.items,
    anchor,
    isItemDisabled: config.isItemDisabled,
    itemToSearchText: config.itemToSearchText,
    isButtonDisabled: config.isButtonDisabled,
    buttonContent: config.buttonContent,
    itemGroupKey: config.itemGroupKey,
    groupToHeading: config.groupToHeading
      ? (groupKey) => {
          const heading = config.groupToHeading!(groupKey)
          if (!heading) return undefined
          return {
            content: heading.content,
            className: cn(contextMenuHeadingClass, heading.className),
          }
        }
      : undefined,
    ariaLabel: config.ariaLabel,
    ariaLabelledBy: config.ariaLabelledBy,
    buttonClassName: cn(
      contextMenuTriggerClass,
      Option.isSome(config.maybePoint ?? Option.none()) ? contextMenuTriggerAnchorClass : undefined,
      config.triggerClass,
    ),
    buttonAttributes: [
      ...childAttributes([
        inertHtml.DataAttribute('slot', 'context-menu-trigger'),
        // Replaces the primitive's open-state Style (position: relative) so the
        // zero-size trigger sits at the pointer while the menu is open.
        ...Option.match(config.maybePoint ?? Option.none(), {
          onNone: () => [],
          onSome: ({ x, y }) => [
            inertHtml.Style({ position: 'fixed', left: `${x}px`, top: `${y}px`, zIndex: '1' }),
          ],
        }),
      ]),
      ...(config.triggerAttributes ?? []),
    ],
    itemsClassName: cn(
      config.isAnimated !== false ? contextMenuItemsAnimatedClass : contextMenuItemsClass,
      config.itemsClass,
    ),
    itemsAttributes: [
      ...childAttributes([
        inertHtml.DataAttribute('slot', 'context-menu-content'),
        inertHtml.DataAttribute('side', side),
      ]),
      ...(config.contentAttributes ?? []),
    ],
    itemToConfig: (item, context) => {
      const { className, content } = config.itemToConfig(item, context)
      return { className: cn(contextMenuItemClass, config.itemClass, className), content }
    },
    separatorClassName: cn(contextMenuSeparatorClass, config.separatorClass),
    separatorAttributes: childAttributes([
      inertHtml.DataAttribute('slot', 'context-menu-separator'),
    ]),
    groupClassName: config.groupClass,
    groupAttributes: childAttributes([inertHtml.DataAttribute('slot', 'context-menu-group')]),
    backdropClassName: cn(contextMenuBackdropClass, config.backdropClass),
    className: cn(contextMenuWrapperClass, config.wrapperClass),
    attributes: childAttributes([inertHtml.DataAttribute('slot', 'context-menu')]),
  }
}

// The trigger button sits inside the parent row (px-1.5) inside the parent
// panel (p-1), so the gap clears both and the offset lines the first row up with
// the trigger row (the sub panel's own p-1).
export const CONTEXT_MENU_SUB_ANCHOR: AnchorConfig = {
  placement: 'right-start',
  gap: 14,
  offset: -8,
  padding: 8,
}

/** `viewInputs` for a nested menu, rendered as the `content` of a parent row.
 *  The trigger is a full-width, pointer-transparent button: the parent row owns
 *  the click (its `SelectedItem` message opens the submenu — handle it yourself, do not forward it) and the panel
 *  anchors to the trigger. Pair it with `contextMenuSubTriggerClass` on the
 *  parent row's className and `contextMenuSubTriggerChevron` in the trigger's
 *  content. */
export const subViewInputs = <Item extends string>(
  config: ContextMenuViewInputsConfig<Item>,
): ViewInputs<Item> => {
  const anchor = config.anchor ?? CONTEXT_MENU_SUB_ANCHOR
  const inputs = viewInputs({ wrapperClass: 'block w-full', ...config, anchor })
  return {
    ...inputs,
    buttonClassName: cn(
      'pointer-events-none flex w-full items-center gap-1.5',
      config.triggerClass,
    ),
    buttonAttributes: [
      ...childAttributes([
        inertHtml.DataAttribute('slot', 'context-menu-sub-trigger'),
        inertHtml.Tabindex(-1),
      ]),
      ...(config.triggerAttributes ?? []),
    ],
    itemsClassName: cn(contextMenuSubContentClass, config.itemsClass),
    itemsAttributes: [
      ...childAttributes([
        inertHtml.DataAttribute('slot', 'context-menu-sub-content'),
        inertHtml.DataAttribute('side', anchor.placement?.split('-')[0] ?? 'right'),
      ]),
      ...(config.contentAttributes ?? []),
    ],
  }
}