Right click here

Installation

  1. Set up the project

    Once per project: the packages, Tailwind CSS, the theme tokens and the cn helper. Follow Installation.

  2. Copy the component into your project

    The kit owns behaviour, ARIA and data attributes. This file is the look, written with Tailwind classes, and it is yours to change.

    src/ui/context-menu.ts
    import type { Component } from "@effect/ui"
    import type { Html } from "@effect/ui/html"
    import type { ContextMenuParts, Menu } from "@effect/ui-kit"
    import { cn } from "#lib/cn"
    import {
      MenuCheckboxItem,
      MenuGroup,
      MenuItem,
      MenuLabel,
      MenuLinkItem,
      MenuPopup,
      MenuPositioner,
      MenuRadioGroup,
      MenuRadioItem,
      MenuSeparator,
      MenuShortcut,
      MenuSubTrigger
    } from "#ui/menu"
    
    type MenuParts = Component.Headless.Parts<typeof Menu>
    
    /**
     * The area a right click or a long press opens the menu over. It has no look of
     * its own beyond a focus ring: pass the area's classes as `class`, and an `id`
     * when several triggers share one menu, which also keys the element.
     */
    export const ContextMenuTrigger = <Msg>(
      h: Html.H<Msg>,
      contextMenu: Pick<ContextMenuParts, "trigger">,
      options: { readonly class?: string | undefined; readonly id?: string | undefined } = {}
    ) =>
      contextMenu.trigger(
        (options.id === undefined ? h.div : h.div.key(options.id))
          .class(cn(
            "outline-none select-none [-webkit-touch-callout:none] focus-visible:ring-2 focus-visible:ring-ring",
            options.class
          ))
          .attr("id", options.id)
      )
    
    /**
     * The item of the context menu that opens `submenu`, a `Menu` with `parentItem`
     * drawn inside the popup.
     */
    export const ContextMenuSubTrigger = <Msg>(
      h: Html.H<Msg>,
      contextMenu: Pick<ContextMenuParts, "item">,
      submenu: Pick<MenuParts, "submenuTrigger">,
      options: { readonly value: string; readonly inset?: boolean | undefined; readonly class?: string | undefined }
    ) => MenuSubTrigger(h, contextMenu, submenu, options)
    
    // The popup and the items are a Menu's: each helper takes the context menu's parts, or a submenu's.
    export const ContextMenuPositioner = MenuPositioner
    export const ContextMenuPopup = MenuPopup
    export const ContextMenuItem = MenuItem
    export const ContextMenuLinkItem = MenuLinkItem
    export const ContextMenuCheckboxItem = MenuCheckboxItem
    export const ContextMenuRadioGroup = MenuRadioGroup
    export const ContextMenuRadioItem = MenuRadioItem
    export const ContextMenuGroup = MenuGroup
    export const ContextMenuLabel = MenuLabel
    export const ContextMenuSeparator = MenuSeparator
    export const ContextMenuShortcut = MenuShortcut
    
  3. Import it

    import { ContextMenuTrigger, ContextMenuSubTrigger, ContextMenuPositioner, ContextMenuPopup, ContextMenuItem, ContextMenuLinkItem, ContextMenuCheckboxItem, ContextMenuRadioGroup, ContextMenuRadioItem, ContextMenuGroup, ContextMenuLabel, ContextMenuSeparator, ContextMenuShortcut } from "#ui/context-menu"
    

Usage

Basic.ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { ContextMenu } from "@effect/ui-kit"
import { Schema } from "effect"
import { ContextMenuItem, ContextMenuPopup, ContextMenuPositioner, ContextMenuSeparator, ContextMenuShortcut, ContextMenuTrigger } from "#ui/context-menu"

const ContextMenuBasicMessage = UiSchema.TaggedEnum({
  RequestedOpenContextMenu: {},
  RequestedCloseContextMenu: {},
  PickedContextMenuItem: { value: Schema.String }
})

const navigation = [
  { value: "back", label: "Back", shortcut: "⌘[" },
  { value: "forward", label: "Forward", shortcut: "⌘]", disabled: true },
  { value: "reload", label: "Reload", shortcut: "⌘R" }
]

const page = [
  { value: "save", label: "Save page as…", shortcut: "⌘S" },
  { value: "print", label: "Print…", shortcut: "⌘P" },
  { value: "source", label: "View page source", shortcut: "⌥⌘U" }
]

const area =
  "grid min-h-36 w-80 max-w-full place-items-center rounded-md border border-dashed border-input p-4 text-center " +
  "text-[13px] text-muted-foreground transition-colors data-[popup-open]:border-ring data-[popup-open]:bg-brand-wash"

export const ContextMenuBasic = Html.component({
  name: "ContextMenuBasic",
  model: Schema.Struct({ open: Schema.Boolean, picked: Schema.NullOr(Schema.String) }),
  message: ContextMenuBasicMessage
}).make({
  init: () => ({ open: false, picked: null }),
  update: {
    RequestedOpenContextMenu: ($) => $.evolve({ open: true }),
    RequestedCloseContextMenu: ($) => $.evolve({ open: false }),
    PickedContextMenuItem: ($, { value }) => $.evolve({ picked: value })
  },
  view: (h, model) =>
    ContextMenu(h, {
      props: { open: model.open, items: [...navigation, ...page] },
      onEmit: {
        RequestedOpen: () => ContextMenuBasicMessage.RequestedOpenContextMenu(),
        RequestedClose: () => ContextMenuBasicMessage.RequestedCloseContextMenu(),
        Picked: ({ value }) => ContextMenuBasicMessage.PickedContextMenuItem({ value }),
        Highlighted: () => undefined,
        Settled: () => undefined
      },
      view: (contextMenu) => {
        const item = ({ label, shortcut, value }: { readonly value: string; readonly label: string; readonly shortcut: string }) =>
          ContextMenuItem(h, contextMenu, { value }).children(
            label,
            ContextMenuShortcut(h).children(shortcut)
          )
        return h.div.class("flex flex-col items-center gap-4").children(
          ContextMenuTrigger(h, contextMenu, { class: area }).children(
            model.picked === null ? "Right click here" : `Picked ${model.picked}`
          ),
          ContextMenuPositioner(h, contextMenu).children(
            ContextMenuPopup(h, contextMenu).children(
              navigation.map(item),
              ContextMenuSeparator(h, contextMenu),
              page.map(item)
            )
          )
        )
      }
    })
})

Examples

A submenu is a Menu with parentItem, drawn inside the context menu's popup.

Right click report.pdf

Checkbox and radio items

Checkable items keep the menu open, and the area reflects the Model as it changes.

Canvas at 100%, with grid

One menu for every row

Several triggers open one menu. RequestedOpen reports the row's id, and the actions change that row.

README.md★
package.json
tsconfig.json

Right click a file

Anatomy

The parts the view closure receives. Apply each one to an element of your own.

PartDescription
triggerThe <div> area a right click or a long press opens the menu over. Gets tabindex="0".
positionerA <div>, a manual popover placed at the pointer.
popupThe <div> inside the positioner with role="menu".
item / linkItemA <div> or an <a> per value, { element, value }.
checkboxItem / checkboxItemIndicatorAn item with a checked state and the <span> shown while it is checked.
radioGroup / radioItem / radioItemIndicatorA <div> with the checked value around radio items, and the <span> shown in the checked one.
group / groupLabelA <div> around items and its label, tied together by { group }.
separatorA <div> between items.
backdrop / arrow / finalFocusA <div> under the popup, an arrow, and an element to focus on close.

API reference

Props

PropTypeDescription
openbooleanWhether the popup shows. The menu only asks, with RequestedOpen and RequestedClose.
itemsArray<{ value, label, disabled? }>Every item in the order it is drawn.
disabledbooleanThe menu ignores the user, and the browser's own menu shows instead.
side / alignSide / Align"bottom" and "start" by default, so the popup's corner sits under the pointer.
loopFocusbooleanThe arrow keys wrap from the last item to the first. True by default.
finalFocusbooleanOn close, focus goes back to the element that had it. False leaves it where it is.

Events

EventDescription
RequestedOpenAsks for open to be true. triggerId is the id the consumer gave the trigger, or null.
RequestedCloseAsks for open to be false: item-press, outside-press, escape-key, focus-out or cancel-open.
PickedAn item was picked. checked is the new state of a checkbox item.
HighlightedThe highlighted item changed.
SettledThe popup's transitions ended.

Data attributes

AttributeDescription
data-popup-open / data-pressedOn the trigger while the menu is open from it.
data-starting-style / data-ending-styleOn the popup while it enters and exits.
data-side / data-alignOn the positioner and the popup.
data-nestedOn the popup of a submenu.
data-highlightedOn the item the pointer or the keyboard is on.
data-checked / data-uncheckedOn checkbox and radio items and their indicators.
data-disabledOn a disabled item.

The components this page's file and examples import.

  • Menu: A button that opens a list of actions, links, checkbox and radio items, and submenus.

effectcn is built with Effect UI and @effect/ui-kit. Not affiliated with Effectful Technologies.