Context Menu
Displays a menu to the user — such as a set of actions or functions — triggered by a right click.
Usage
Basic
Right click the trigger, or press the ContextMenu key while it has focus (give it tabindex: 0 if it holds nothing focusable): the menu opens at the pointer and takes focus. Arrow keys, Home/End and typing a letter move through the items; Enter or Space picks one, Esc closes. While it is open the page behind is inert and doesn't scroll.
ContextMenu do
ContextMenuTrigger(class: "flex h-[150px] w-[300px] items-center justify-center rounded-md border border-dashed text-sm") { "Right click here" }
ContextMenuContent do
ContextMenuGroup do
ContextMenuItem { "Back" }
ContextMenuItem(disabled: true) { "Forward" }
ContextMenuItem { "Reload" }
end
end
end
With shortcuts
ContextMenuShortcut shows the key combination; shortcut: on ContextMenuItem is a shorthand for it. It only displays the keys: binding them is up to you.
ContextMenu do
ContextMenuTrigger(class: "flex h-[150px] w-[300px] items-center justify-center rounded-md border border-dashed text-sm") { "Right click here" }
ContextMenuContent(class: "w-64") do
ContextMenuGroup do
ContextMenuItem do
plain "Back"
ContextMenuShortcut { "⌘[" }
end
ContextMenuItem(shortcut: "⌘]", disabled: true) { "Forward" }
ContextMenuItem(shortcut: "⌘R") { "Reload" }
end
ContextMenuSeparator()
ContextMenuGroup do
ContextMenuItem(shortcut: "⌘S") { "Save Page As…" }
ContextMenuItem(shortcut: "⇧⌘I") { "Developer Tools" }
end
end
end
With groups
ContextMenuGroup groups items; a ContextMenuLabel inside it names the group for assistive tech.
ContextMenu do
ContextMenuTrigger(class: "flex h-[150px] w-[300px] items-center justify-center rounded-md border border-dashed text-sm") { "Right click here" }
ContextMenuContent(class: "w-48") do
ContextMenuGroup do
ContextMenuLabel { "File" }
ContextMenuItem { "New File" }
ContextMenuItem { "Open File" }
end
ContextMenuSeparator()
ContextMenuGroup do
ContextMenuLabel { "Edit" }
ContextMenuItem { "Undo" }
ContextMenuItem { "Redo" }
end
end
end
Links
Items render as divs; href: turns one into a link that navigates when picked.
ContextMenu do
ContextMenuTrigger(class: "flex h-[150px] w-[300px] items-center justify-center rounded-md border border-dashed text-sm") { "Right click here" }
ContextMenuContent do
ContextMenuItem(href: "#links") { "History" }
ContextMenuItem(href: "#links") { "Settings" }
end
end
Checkboxes
ContextMenuCheckboxItem toggles aria-checked and keeps the menu open. Listen to ruby-ui--context-menu:change; event.detail.checked has the new state.
ContextMenu do
ContextMenuTrigger(class: "flex h-[150px] w-[300px] items-center justify-center rounded-md border border-dashed text-sm") { "Right click here" }
ContextMenuContent(class: "w-64") do
ContextMenuCheckboxItem(checked: true) { "Show Bookmarks Bar" }
ContextMenuCheckboxItem { "Show Full URLs" }
ContextMenuCheckboxItem(shortcut: "⌘⇧D") { "Show Developer Tools" }
end
end
Radio group
ContextMenuRadioItems in a ContextMenuRadioGroup: checking one unchecks the rest. In ruby-ui--context-menu:change, event.detail.value carries the item's value: argument.
ContextMenu do
ContextMenuTrigger(class: "flex h-[150px] w-[300px] items-center justify-center rounded-md border border-dashed text-sm") { "Right click here" }
ContextMenuContent(class: "w-48") do
ContextMenuRadioGroup do
ContextMenuLabel(inset: true) { "People" }
ContextMenuRadioItem(value: "pedro", checked: true) { "Pedro Duarte" }
ContextMenuRadioItem(value: "colm") { "Colm Tuite" }
end
end
end
Destructive
variant: :destructive marks an item that deletes or can't be undone.
ContextMenu do
ContextMenuTrigger(class: "flex h-[150px] w-[300px] items-center justify-center rounded-md border border-dashed text-sm") { "Right click here" }
ContextMenuContent do
ContextMenuGroup do
ContextMenuItem { "Edit" }
ContextMenuItem { "Share" }
end
ContextMenuSeparator()
ContextMenuGroup do
ContextMenuItem(variant: :destructive) { "Delete" }
end
end
end
Inset
inset: indents an item or label (pl-8), e.g. to line it up with items that start with an icon.
ContextMenu do
ContextMenuTrigger(class: "flex h-[150px] w-[300px] items-center justify-center rounded-md border border-dashed text-sm") { "Right click here" }
ContextMenuContent(class: "w-52") do
ContextMenuGroup do
ContextMenuItem(inset: true) { "Copy" }
ContextMenuItem(inset: true) { "Cut" }
end
ContextMenuSeparator()
ContextMenuCheckboxItem(checked: true) { "Show Bookmarks Bar" }
ContextMenuSeparator()
ContextMenuGroup do
ContextMenuLabel(inset: true) { "More Tools" }
ContextMenuItem(inset: true) { "Developer Tools" }
end
end
end
Side
side: (top, right, bottom, left) and align: (start, center, end) place the menu relative to the pointer; side_offset: and align_offset: set the gap. The defaults are right, start, 0 and 4.
div(class: "grid gap-4 sm:grid-cols-2") do
ContextMenu do
ContextMenuTrigger(class: "flex h-[100px] items-center justify-center rounded-md border border-dashed text-sm") { "Right click (top)" }
ContextMenuContent(side: :top) do
ContextMenuItem { "Back" }
ContextMenuItem { "Forward" }
ContextMenuItem { "Reload" }
end
end
ContextMenu do
ContextMenuTrigger(class: "flex h-[100px] items-center justify-center rounded-md border border-dashed text-sm") { "Right click (right)" }
ContextMenuContent(side: :right) do
ContextMenuItem { "Back" }
ContextMenuItem { "Forward" }
ContextMenuItem { "Reload" }
end
end
ContextMenu do
ContextMenuTrigger(class: "flex h-[100px] items-center justify-center rounded-md border border-dashed text-sm") { "Right click (bottom)" }
ContextMenuContent(side: :bottom) do
ContextMenuItem { "Back" }
ContextMenuItem { "Forward" }
ContextMenuItem { "Reload" }
end
end
ContextMenu do
ContextMenuTrigger(class: "flex h-[100px] items-center justify-center rounded-md border border-dashed text-sm") { "Right click (left)" }
ContextMenuContent(side: :left) do
ContextMenuItem { "Back" }
ContextMenuItem { "Forward" }
ContextMenuItem { "Reload" }
end
end
end
Installation
Using RubyUI CLI
Run the install command
rails g ruby_ui:component ContextMenu
Manual installation
1
Add RubyUI::ContextMenu to app/components/ruby_ui/context_menu/context_menu.rb
# frozen_string_literal: true
module RubyUI
# The root. Placement lives on ContextMenuContent (side:, align:, offsets).
class ContextMenu < Base
def initialize(**attrs)
if attrs.key?(:options)
raise ArgumentError, "ContextMenu(options:) was removed; use ContextMenuContent(side:, align:, side_offset:, align_offset:)"
end
super
end
def view_template(&)
div(**attrs, &)
end
private
def default_attrs
{
data: {
slot: "context-menu",
controller: "ruby-ui--context-menu"
}
}
end
end
end
2
Add RubyUI::ContextMenuCheckboxItem to app/components/ruby_ui/context_menu/context_menu_checkbox_item.rb
# frozen_string_literal: true
module RubyUI
# A toggle in the menu (role menuitemcheckbox). Activating it flips
# aria-checked, keeps the menu open and fires ruby-ui--context-menu:change
# with {checked} in the detail.
class ContextMenuCheckboxItem < Base
ITEM = [
"group/context-menu-checkbox-item relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-8 pl-2 text-sm outline-hidden select-none",
"focus:bg-accent focus:text-accent-foreground",
"data-disabled:pointer-events-none data-disabled:opacity-50 data-inset:pl-8",
"[&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4"
].freeze
def initialize(checked: false, inset: false, disabled: false, shortcut: nil, **)
@checked = checked
@inset = inset
@disabled = disabled
@shortcut = shortcut
super(**)
end
def view_template(&block)
div(**attrs) do
render ContextMenuItemIndicator.new(kind: :checkbox)
yield if block
render ContextMenuShortcut.new { @shortcut } if @shortcut
end
end
private
def default_attrs
{
role: "menuitemcheckbox",
tabindex: "-1",
aria: {checked: @checked.to_s, disabled: (@disabled ? "true" : nil)},
data: {
slot: "context-menu-checkbox-item",
inset: @inset,
disabled: @disabled,
action: "click->ruby-ui--context-menu#activate pointermove->ruby-ui--context-menu#hover pointerleave->ruby-ui--context-menu#leave"
},
class: ITEM
}
end
end
end
3
Add RubyUI::ContextMenuContent to app/components/ruby_ui/context_menu/context_menu_content.rb
# frozen_string_literal: true
module RubyUI
# The menu. A native popover (top layer), opened at the pointer and placed
# by Floating UI; side:/align: pick the placement, side_offset:/align_offset:
# the gap, with the defaults of shadcn's ContextMenuContent.
class ContextMenuContent < Base
SIDES = %i[top right bottom left].freeze
ALIGNS = %i[start center end].freeze
def initialize(side: :right, side_offset: 0, align: :start, align_offset: 4, **)
@side = SIDES.include?(side.to_sym) ? side.to_sym : :right
@side_offset = side_offset
@align = ALIGNS.include?(align.to_sym) ? align.to_sym : :start
@align_offset = align_offset
super(**)
end
def view_template(&)
div(**attrs, &)
end
private
def default_attrs
{
role: "menu",
tabindex: "-1",
popover: "manual",
data: {
slot: "context-menu-content",
# Kept in sync with data-open/data-closed for CSS that targets data-[state=...].
state: "closed",
ruby_ui__context_menu_target: "content",
action: "keydown->ruby-ui--context-menu#keydown",
closed: "",
side: @side,
align: @align,
preferred_side: @side,
side_offset: @side_offset,
align_offset: @align_offset
},
class: [
"fixed inset-auto m-0 border-0 z-50 max-h-(--available-height) origin-(--transform-origin)",
"overflow-x-hidden overflow-y-auto outline-none",
"bg-popover text-popover-foreground ring-1 ring-foreground/10 min-w-36 rounded-md p-1 shadow-md duration-100",
"data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95",
"data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95 data-closed:fill-mode-forwards",
"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"
]
}
end
end
end
4
Add RubyUI::ContextMenuDocs to app/components/ruby_ui/context_menu/context_menu_docs.rb
# frozen_string_literal: true
class Views::Docs::ContextMenu < Views::Base
def view_template
component = "ContextMenu"
div(class: "max-w-2xl mx-auto w-full py-10 space-y-10") do
render Docs::Header.new(title: "Context Menu", description: "Displays a menu to the user — such as a set of actions or functions — triggered by a right click.")
Heading(level: 2) { "Usage" }
render Docs::VisualCodeExample.new(title: "Basic", description: "Right click the trigger, or press the ContextMenu key while it has focus (give it tabindex: 0 if it holds nothing focusable): the menu opens at the pointer and takes focus. Arrow keys, Home/End and typing a letter move through the items; Enter or Space picks one, Esc closes. While it is open the page behind is inert and doesn't scroll.", context: self) do
<<~RUBY
ContextMenu do
ContextMenuTrigger(class: "flex h-[150px] w-[300px] items-center justify-center rounded-md border border-dashed text-sm") { "Right click here" }
ContextMenuContent do
ContextMenuGroup do
ContextMenuItem { "Back" }
ContextMenuItem(disabled: true) { "Forward" }
ContextMenuItem { "Reload" }
end
end
end
RUBY
end
render Docs::VisualCodeExample.new(title: "With shortcuts", description: "ContextMenuShortcut shows the key combination; shortcut: on ContextMenuItem is a shorthand for it. It only displays the keys: binding them is up to you.", context: self) do
<<~RUBY
ContextMenu do
ContextMenuTrigger(class: "flex h-[150px] w-[300px] items-center justify-center rounded-md border border-dashed text-sm") { "Right click here" }
ContextMenuContent(class: "w-64") do
ContextMenuGroup do
ContextMenuItem do
plain "Back"
ContextMenuShortcut { "⌘[" }
end
ContextMenuItem(shortcut: "⌘]", disabled: true) { "Forward" }
ContextMenuItem(shortcut: "⌘R") { "Reload" }
end
ContextMenuSeparator()
ContextMenuGroup do
ContextMenuItem(shortcut: "⌘S") { "Save Page As…" }
ContextMenuItem(shortcut: "⇧⌘I") { "Developer Tools" }
end
end
end
RUBY
end
render Docs::VisualCodeExample.new(title: "With groups", description: "ContextMenuGroup groups items; a ContextMenuLabel inside it names the group for assistive tech.", context: self) do
<<~RUBY
ContextMenu do
ContextMenuTrigger(class: "flex h-[150px] w-[300px] items-center justify-center rounded-md border border-dashed text-sm") { "Right click here" }
ContextMenuContent(class: "w-48") do
ContextMenuGroup do
ContextMenuLabel { "File" }
ContextMenuItem { "New File" }
ContextMenuItem { "Open File" }
end
ContextMenuSeparator()
ContextMenuGroup do
ContextMenuLabel { "Edit" }
ContextMenuItem { "Undo" }
ContextMenuItem { "Redo" }
end
end
end
RUBY
end
render Docs::VisualCodeExample.new(title: "Links", description: "Items render as divs; href: turns one into a link that navigates when picked.", context: self) do
<<~RUBY
ContextMenu do
ContextMenuTrigger(class: "flex h-[150px] w-[300px] items-center justify-center rounded-md border border-dashed text-sm") { "Right click here" }
ContextMenuContent do
ContextMenuItem(href: "#links") { "History" }
ContextMenuItem(href: "#links") { "Settings" }
end
end
RUBY
end
render Docs::VisualCodeExample.new(title: "Checkboxes", description: "ContextMenuCheckboxItem toggles aria-checked and keeps the menu open. Listen to ruby-ui--context-menu:change; event.detail.checked has the new state.", context: self) do
<<~RUBY
ContextMenu do
ContextMenuTrigger(class: "flex h-[150px] w-[300px] items-center justify-center rounded-md border border-dashed text-sm") { "Right click here" }
ContextMenuContent(class: "w-64") do
ContextMenuCheckboxItem(checked: true) { "Show Bookmarks Bar" }
ContextMenuCheckboxItem { "Show Full URLs" }
ContextMenuCheckboxItem(shortcut: "⌘⇧D") { "Show Developer Tools" }
end
end
RUBY
end
render Docs::VisualCodeExample.new(title: "Radio group", description: "ContextMenuRadioItems in a ContextMenuRadioGroup: checking one unchecks the rest. In ruby-ui--context-menu:change, event.detail.value carries the item's value: argument.", context: self) do
<<~RUBY
ContextMenu do
ContextMenuTrigger(class: "flex h-[150px] w-[300px] items-center justify-center rounded-md border border-dashed text-sm") { "Right click here" }
ContextMenuContent(class: "w-48") do
ContextMenuRadioGroup do
ContextMenuLabel(inset: true) { "People" }
ContextMenuRadioItem(value: "pedro", checked: true) { "Pedro Duarte" }
ContextMenuRadioItem(value: "colm") { "Colm Tuite" }
end
end
end
RUBY
end
render Docs::VisualCodeExample.new(title: "Destructive", description: "variant: :destructive marks an item that deletes or can't be undone.", context: self) do
<<~RUBY
ContextMenu do
ContextMenuTrigger(class: "flex h-[150px] w-[300px] items-center justify-center rounded-md border border-dashed text-sm") { "Right click here" }
ContextMenuContent do
ContextMenuGroup do
ContextMenuItem { "Edit" }
ContextMenuItem { "Share" }
end
ContextMenuSeparator()
ContextMenuGroup do
ContextMenuItem(variant: :destructive) { "Delete" }
end
end
end
RUBY
end
render Docs::VisualCodeExample.new(title: "Inset", description: "inset: indents an item or label (pl-8), e.g. to line it up with items that start with an icon.", context: self) do
<<~RUBY
ContextMenu do
ContextMenuTrigger(class: "flex h-[150px] w-[300px] items-center justify-center rounded-md border border-dashed text-sm") { "Right click here" }
ContextMenuContent(class: "w-52") do
ContextMenuGroup do
ContextMenuItem(inset: true) { "Copy" }
ContextMenuItem(inset: true) { "Cut" }
end
ContextMenuSeparator()
ContextMenuCheckboxItem(checked: true) { "Show Bookmarks Bar" }
ContextMenuSeparator()
ContextMenuGroup do
ContextMenuLabel(inset: true) { "More Tools" }
ContextMenuItem(inset: true) { "Developer Tools" }
end
end
end
RUBY
end
render Docs::VisualCodeExample.new(title: "Side", description: "side: (top, right, bottom, left) and align: (start, center, end) place the menu relative to the pointer; side_offset: and align_offset: set the gap. The defaults are right, start, 0 and 4.", context: self) do
<<~RUBY
div(class: "grid gap-4 sm:grid-cols-2") do
ContextMenu do
ContextMenuTrigger(class: "flex h-[100px] items-center justify-center rounded-md border border-dashed text-sm") { "Right click (top)" }
ContextMenuContent(side: :top) do
ContextMenuItem { "Back" }
ContextMenuItem { "Forward" }
ContextMenuItem { "Reload" }
end
end
ContextMenu do
ContextMenuTrigger(class: "flex h-[100px] items-center justify-center rounded-md border border-dashed text-sm") { "Right click (right)" }
ContextMenuContent(side: :right) do
ContextMenuItem { "Back" }
ContextMenuItem { "Forward" }
ContextMenuItem { "Reload" }
end
end
ContextMenu do
ContextMenuTrigger(class: "flex h-[100px] items-center justify-center rounded-md border border-dashed text-sm") { "Right click (bottom)" }
ContextMenuContent(side: :bottom) do
ContextMenuItem { "Back" }
ContextMenuItem { "Forward" }
ContextMenuItem { "Reload" }
end
end
ContextMenu do
ContextMenuTrigger(class: "flex h-[100px] items-center justify-center rounded-md border border-dashed text-sm") { "Right click (left)" }
ContextMenuContent(side: :left) do
ContextMenuItem { "Back" }
ContextMenuItem { "Forward" }
ContextMenuItem { "Reload" }
end
end
end
RUBY
end
render Components::ComponentSetup::Tabs.new(component_name: component)
render Docs::ComponentsTable.new(component_files(component))
end
end
end
5
Add RubyUI::ContextMenuGroup to app/components/ruby_ui/context_menu/context_menu_group.rb
# frozen_string_literal: true
require "securerandom"
module RubyUI
# A group of items (role group), named by the ContextMenuLabel inside it.
class ContextMenuGroup < Base
def initialize(id: nil, **)
@id = id || "context-menu-group-#{SecureRandom.hex(4)}"
super(id: @id, **)
end
# The children are captured first, so aria-labelledby only points at a
# ContextMenuLabel that actually rendered.
def view_template(&block)
previous = context[:ruby_ui_context_menu_group]
names = context[:ruby_ui_context_menu_group] = {label_id: "#{@id}-label"}
body = block ? capture(&block) : ""
group_attrs = names[:labelledby] ? mix({aria: {labelledby: names[:labelledby]}}, attrs) : attrs
div(**group_attrs) { raw(safe(body)) }
ensure
context[:ruby_ui_context_menu_group] = previous
end
private
def default_attrs
{
role: "group",
data: {slot: "context-menu-group"}
}
end
end
end
6
Add RubyUI::ContextMenuItem to app/components/ruby_ui/context_menu/context_menu_item.rb
# frozen_string_literal: true
module RubyUI
# An action. A div by default; href: makes it a link. variant: :destructive
# paints it red, inset: lines it up with items that have an indicator.
# shortcut: renders a ContextMenuShortcut; checked: true (kept for
# compatibility) renders a ContextMenuCheckboxItem instead, while
# checked: false stays a plain item, as before.
class ContextMenuItem < Base
ITEM = [
"group/context-menu-item relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none",
"focus:bg-accent focus:text-accent-foreground focus:*:[svg]:text-accent-foreground",
"data-disabled:pointer-events-none data-disabled:opacity-50 data-inset:pl-8",
"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",
"[&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4"
].freeze
def initialize(href: nil, variant: :default, inset: false, disabled: false, shortcut: nil, checked: false, **attrs)
@href = href
@variant = (variant.to_sym == :destructive) ? :destructive : :default
@inset = inset
@disabled = disabled
@shortcut = shortcut
@checked = checked
@user_attrs = attrs
super(**attrs)
end
def view_template(&block)
if @checked == true
return render ContextMenuCheckboxItem.new(checked: @checked, inset: @inset, disabled: @disabled, shortcut: @shortcut, **@user_attrs), &block
end
tag = @href ? :a : :div
send(tag, **attrs) do
yield if block
render ContextMenuShortcut.new { @shortcut } if @shortcut
end
end
private
def default_attrs
{
href: @href,
role: "menuitem",
tabindex: "-1",
aria: {disabled: (@disabled ? "true" : nil)},
data: {
slot: "context-menu-item",
variant: @variant,
inset: @inset,
disabled: @disabled,
action: "click->ruby-ui--context-menu#activate pointermove->ruby-ui--context-menu#hover pointerleave->ruby-ui--context-menu#leave"
},
class: ITEM
}
end
end
end
7
Add RubyUI::ContextMenuItemIndicator to app/components/ruby_ui/context_menu/context_menu_item_indicator.rb
# frozen_string_literal: true
module RubyUI
# The check of a ContextMenuCheckboxItem / ContextMenuRadioItem, shown only
# while the item is aria-checked="true". Rendered by those items.
class ContextMenuItemIndicator < Base
# Full class names, so Tailwind finds them when it scans the source.
SHOW_WHEN_CHECKED = {
checkbox: "group-aria-checked/context-menu-checkbox-item:flex",
radio: "group-aria-checked/context-menu-radio-item:flex"
}.freeze
def initialize(kind:, **)
@kind = kind
super(**)
end
def view_template
span(**attrs) do
svg(
xmlns: "http://www.w3.org/2000/svg",
viewbox: "0 0 24 24",
fill: "none",
stroke: "currentColor",
stroke_width: "2",
stroke_linecap: "round",
stroke_linejoin: "round",
aria_hidden: "true"
) { |s| s.path(d: "M20 6 9 17l-5-5") }
end
end
private
def default_attrs
{
aria: {hidden: "true"},
data: {slot: "context-menu-item-indicator"},
class: ["pointer-events-none absolute right-2 hidden items-center justify-center", SHOW_WHEN_CHECKED.fetch(@kind)]
}
end
end
end
8
Add RubyUI::ContextMenuLabel to app/components/ruby_ui/context_menu/context_menu_label.rb
# frozen_string_literal: true
module RubyUI
# A heading. Inside a ContextMenuGroup the first label names the group
# (aria-labelledby) and its own text is hidden from the accessibility tree.
class ContextMenuLabel < Base
def initialize(inset: false, **)
@inset = inset
super(**)
end
def view_template(&)
names = context[:ruby_ui_context_menu_group]
# Only the first label names the group; later ones stay plain headings.
return div(**attrs, &) if names.nil? || names[:labelledby]
id = attrs[:id] || names[:label_id]
names[:labelledby] ||= id
div(**mix({aria: {hidden: "true"}}, attrs.merge(id: id)), &)
end
private
def default_attrs
{
data: {slot: "context-menu-label", inset: @inset},
class: "text-muted-foreground px-2 py-1.5 text-xs font-medium data-inset:pl-8"
}
end
end
end
9
Add RubyUI::ContextMenuRadioGroup to app/components/ruby_ui/context_menu/context_menu_radio_group.rb
# frozen_string_literal: true
module RubyUI
# Groups ContextMenuRadioItems: checking one unchecks the others. Like
# ContextMenuGroup, a ContextMenuLabel inside it names the group.
class ContextMenuRadioGroup < ContextMenuGroup
private
def default_attrs
{
role: "group",
data: {slot: "context-menu-radio-group"}
}
end
end
end
10
Add RubyUI::ContextMenuRadioItem to app/components/ruby_ui/context_menu/context_menu_radio_item.rb
# frozen_string_literal: true
module RubyUI
# One choice of a ContextMenuRadioGroup (role menuitemradio). Activating it
# checks it, unchecks its siblings, keeps the menu open and fires
# ruby-ui--context-menu:change with {checked, value} in the detail.
class ContextMenuRadioItem < Base
ITEM = [
"group/context-menu-radio-item relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-8 pl-2 text-sm outline-hidden select-none",
"focus:bg-accent focus:text-accent-foreground",
"data-disabled:pointer-events-none data-disabled:opacity-50 data-inset:pl-8",
"[&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4"
].freeze
def initialize(value: nil, checked: false, inset: false, disabled: false, **)
@value = value
@checked = checked
@inset = inset
@disabled = disabled
super(**)
end
def view_template(&block)
div(**attrs) do
render ContextMenuItemIndicator.new(kind: :radio)
yield if block
end
end
private
def default_attrs
{
role: "menuitemradio",
tabindex: "-1",
aria: {checked: @checked.to_s, disabled: (@disabled ? "true" : nil)},
data: {
slot: "context-menu-radio-item",
value: @value,
inset: @inset,
disabled: @disabled,
action: "click->ruby-ui--context-menu#activate pointermove->ruby-ui--context-menu#hover pointerleave->ruby-ui--context-menu#leave"
},
class: ITEM
}
end
end
end
11
Add RubyUI::ContextMenuSeparator to app/components/ruby_ui/context_menu/context_menu_separator.rb
# frozen_string_literal: true
module RubyUI
class ContextMenuSeparator < Base
def view_template
div(**attrs)
end
private
def default_attrs
{
role: "separator",
aria_orientation: "horizontal",
data: {slot: "context-menu-separator"},
class: "bg-border -mx-1 my-1 h-px"
}
end
end
end
12
Add RubyUI::ContextMenuShortcut to app/components/ruby_ui/context_menu/context_menu_shortcut.rb
# frozen_string_literal: true
module RubyUI
class ContextMenuShortcut < Base
def view_template(&)
span(**attrs, &)
end
private
def default_attrs
{
data: {slot: "context-menu-shortcut"},
class: "ml-auto text-xs tracking-widest text-muted-foreground group-focus/context-menu-item:text-accent-foreground"
}
end
end
end
13
Add RubyUI::ContextMenuTrigger to app/components/ruby_ui/context_menu/context_menu_trigger.rb
# frozen_string_literal: true
module RubyUI
# The area that opens the menu on right click (or the ContextMenu key).
class ContextMenuTrigger < Base
def view_template(&)
div(**attrs, &)
end
private
def default_attrs
{
data: {
slot: "context-menu-trigger",
ruby_ui__context_menu_target: "trigger",
action: "contextmenu->ruby-ui--context-menu#handleContextMenu"
},
class: "select-none"
}
end
end
end
14
Add context_menu_controller.js to app/javascript/controllers/ruby_ui/context_menu_controller.js
import { Controller } from "@hotwired/stimulus";
import { computePosition, offset, flip, shift, size } from "@floating-ui/dom";
// Connects to data-controller="ruby-ui--context-menu"
//
// Behaves like Base UI's ContextMenu: the menu opens at the pointer, takes
// focus, and moves real focus between items (roving focus) on arrow keys,
// Home/End and typeahead. While open it is modal: the page scroll is locked
// and everything outside the menu is inert.
const ITEM_SELECTOR = "[role=menuitem], [role=menuitemcheckbox], [role=menuitemradio]";
const TYPEAHEAD_RESET_MS = 500;
export default class extends Controller {
static targets = ["trigger", "content"];
connect() {
this.point = null;
this.returnFocus = null;
// The menu element while open: listeners and teardown use it even if the
// content target has left the DOM (e.g. a Turbo Stream replaced it).
this.openContent = null;
this.inerted = [];
this.addedScrollLock = false;
this.typeahead = "";
// A morph or a Turbo restore can bring back an open menu: settle on closed.
if (this.hasContentTarget && (this.contentTarget.hasAttribute("data-open") || this.contentTarget.matches(":popover-open"))) {
this.contentTarget.removeAttribute("data-open");
this.settleExit(this.contentTarget);
}
document.addEventListener("turbo:before-cache", this.handleBeforeCache);
}
disconnect() {
document.removeEventListener("turbo:before-cache", this.handleBeforeCache);
this.close({ restoreFocus: false, animate: false });
}
// The open menu was removed on its own: release the page and the listeners.
contentTargetDisconnected(content) {
if (content === this.openContent) this.teardown();
}
get isOpen() {
return this.openContent !== null;
}
// Only items that render: hidden ones (attribute, CSS or a hidden ancestor) are skipped.
get items() {
if (!this.openContent) return [];
return [...this.openContent.querySelectorAll(ITEM_SELECTOR)].filter((item) => item.getClientRects().length > 0);
}
// --- Opening and closing ----------------------------------------------------
handleContextMenu(event) {
event.preventDefault();
this.point = this.pointFrom(event, this.triggerTarget);
this.isOpen ? this.position() : this.open();
}
// The ContextMenu key fires contextmenu without pointer coordinates.
pointFrom(event, fallback) {
if (event.clientX || event.clientY) return { x: event.clientX, y: event.clientY };
const rect = fallback.getBoundingClientRect();
return { x: rect.left, y: rect.top };
}
open() {
if (!this.hasContentTarget || this.isOpen) return;
const content = (this.openContent = this.contentTarget);
const active = document.activeElement;
this.returnFocus = active && active !== document.body ? active : null;
// Set the origin before the enter animation starts; position() refines it.
const align = content.dataset.align || "start";
content.style.setProperty("--transform-origin", this.transformOrigin(content.dataset.preferredSide || "right", align));
content.removeAttribute("data-closed");
content.setAttribute("data-open", "");
content.dataset.state = "open";
if (!content.matches(":popover-open")) content.showPopover();
this.position();
this.makeModal();
content.focus({ preventScroll: true });
document.addEventListener("pointerdown", this.handleOutsidePointerDown, true);
document.addEventListener("contextmenu", this.handleOutsideContextMenu, true);
window.addEventListener("resize", this.handleResize);
}
close({ restoreFocus = true, animate = true } = {}) {
const content = this.openContent;
this.teardown();
if (!content) return;
const focusWasInside = content.contains(document.activeElement);
content.removeAttribute("data-open");
content.setAttribute("data-closed", "");
content.dataset.state = "closed";
animate ? this.hideAfterExitAnimation(content) : this.settleExit(content);
if (focusWasInside) {
// Leave the menu: back to what had focus before, or out of the popup.
if (restoreFocus && this.returnFocus?.isConnected) this.returnFocus.focus({ preventScroll: true });
else document.activeElement.blur();
}
this.returnFocus = null;
}
// Everything open() took from the page: listeners, inert, scroll lock.
teardown() {
document.removeEventListener("pointerdown", this.handleOutsidePointerDown, true);
document.removeEventListener("contextmenu", this.handleOutsideContextMenu, true);
window.removeEventListener("resize", this.handleResize);
clearTimeout(this.typeaheadTimeout);
this.typeahead = "";
this.releaseModal();
this.openContent = null;
}
// The viewport changed: keep the menu at the pointer and inside the screen.
handleResize = () => {
if (this.openContent) this.position();
};
handleOutsidePointerDown = (event) => {
if (this.openContent?.contains(event.target)) return;
// A right button press is handled by the contextmenu event that follows.
if (event.button === 2) return;
this.close({ restoreFocus: false });
};
// The page is inert while open, so a right click on the trigger lands on an
// ancestor: tell it apart by position and move the menu there, as Base UI does.
handleOutsideContextMenu = (event) => {
if (this.openContent?.contains(event.target)) {
event.preventDefault();
return;
}
const rect = this.hasTriggerTarget ? this.triggerTarget.getBoundingClientRect() : null;
const inTrigger =
rect && event.clientX >= rect.left && event.clientX <= rect.right && event.clientY >= rect.top && event.clientY <= rect.bottom;
if (inTrigger) {
event.preventDefault();
this.point = { x: event.clientX, y: event.clientY };
this.position();
this.openContent.focus({ preventScroll: true });
return;
}
this.close({ restoreFocus: false });
};
// Turbo snapshots the page right after this event: never cache an open menu.
handleBeforeCache = () => {
this.close({ restoreFocus: false, animate: false });
};
// --- Modal: scroll lock + inert page ----------------------------------------
makeModal() {
// A lock someone else already holds stays theirs: only one this menu added is released.
if (!document.body.classList.contains("overflow-hidden")) {
document.body.classList.add("overflow-hidden");
this.addedScrollLock = true;
}
// Everything but the menu's own branch of the tree, the trigger included.
for (let node = this.openContent; node && node !== document.body; node = node.parentElement) {
const parent = node.parentElement;
if (!parent) break;
for (const sibling of parent.children) {
if (sibling === node || sibling.inert || sibling.tagName === "SCRIPT") continue;
sibling.inert = true;
this.inerted.push(sibling);
}
}
}
// Only undo what this menu did, and keep the lock while another modal is open.
releaseModal() {
this.inerted.forEach((element) => (element.inert = false));
this.inerted = [];
if (!this.addedScrollLock) return;
this.addedScrollLock = false;
const otherMenuOpen = [...document.querySelectorAll("[data-slot=context-menu-content][data-open]")].some(
(menu) => menu !== this.openContent
);
if (!otherMenuOpen && !document.querySelector("dialog:modal")) document.body.classList.remove("overflow-hidden");
}
// --- Items ----------------------------------------------------------------
activate(event) {
const item = event.currentTarget;
if (this.isDisabled(item)) {
event.preventDefault();
return;
}
const role = item.getAttribute("role");
if (role === "menuitemcheckbox") {
const checked = item.getAttribute("aria-checked") !== "true";
item.setAttribute("aria-checked", String(checked));
this.dispatch("change", { target: item, detail: { checked } });
} else if (role === "menuitemradio") {
const group = item.closest("[data-slot=context-menu-radio-group], [role=menu]");
group.querySelectorAll("[role=menuitemradio]").forEach((radio) => radio.setAttribute("aria-checked", String(radio === item)));
this.dispatch("change", { target: item, detail: { checked: true, value: item.dataset.value } });
} else {
// Plain items act and close; a link keeps its default navigation.
this.close();
}
}
hover(event) {
const item = event.currentTarget;
if (document.activeElement !== item && !this.isDisabled(item)) item.focus({ preventScroll: true });
}
// Leaving an item drops the highlight back to the menu itself.
leave(event) {
if (document.activeElement === event.currentTarget) this.openContent?.focus({ preventScroll: true });
}
// --- Keyboard -------------------------------------------------------------
keydown(event) {
if (!this.isOpen) return;
const items = this.items;
const current = items.indexOf(document.activeElement);
switch (event.key) {
case "ArrowDown":
event.preventDefault();
this.focusItem(items, current === -1 ? 0 : (current + 1) % items.length);
break;
case "ArrowUp":
event.preventDefault();
this.focusItem(items, current === -1 ? items.length - 1 : (current - 1 + items.length) % items.length);
break;
case "Home":
event.preventDefault();
this.focusItem(items, 0);
break;
case "End":
event.preventDefault();
this.focusItem(items, items.length - 1);
break;
case "Enter":
case " ":
event.preventDefault();
if (current === -1) return;
// Disabled items take focus (APG) but are never activated.
if (!this.isDisabled(items[current])) items[current].click();
break;
case "Escape":
event.preventDefault();
event.stopPropagation();
this.close();
break;
case "Tab":
// Like Base UI's modal menu, focus stays in the menu (the page behind is inert).
event.preventDefault();
break;
default:
if (event.key.length === 1 && !event.ctrlKey && !event.metaKey && !event.altKey) {
this.typeaheadTo(items, current, event.key);
}
}
}
focusItem(items, index) {
items[index]?.focus({ preventScroll: false });
}
// Characters typed in quick succession build a prefix; a single repeated
// character cycles through the items that start with it.
typeaheadTo(items, current, key) {
clearTimeout(this.typeaheadTimeout);
this.typeaheadTimeout = setTimeout(() => (this.typeahead = ""), TYPEAHEAD_RESET_MS);
this.typeahead += key.toLowerCase();
const repeated = [...this.typeahead].every((char) => char === this.typeahead[0]);
const prefix = repeated ? this.typeahead[0] : this.typeahead;
const start = repeated || current === -1 ? current + 1 : current;
const ordered = [...items.slice(start), ...items.slice(0, start)];
const match = ordered.find((item) => this.labelOf(item).toLowerCase().startsWith(prefix));
if (match) match.focus({ preventScroll: false });
}
// The item's own text, without its shortcut or indicator. Comment nodes
// (e.g. Rails' annotate_rendered_view_with_filenames) are not text.
labelOf(item) {
return [...item.childNodes]
.filter((node) => node.nodeType === Node.TEXT_NODE || (node.nodeType === Node.ELEMENT_NODE && !node.matches("[data-slot$=-shortcut], [data-slot$=-indicator]")))
.map((node) => node.textContent)
.join("")
.trim();
}
isDisabled(item) {
return item.getAttribute("aria-disabled") === "true" || item.hasAttribute("data-disabled");
}
// --- Positioning ----------------------------------------------------------
// A zero-size rect at the pointer stands in for the anchor.
position() {
const content = this.openContent;
if (!content) return;
const trigger = this.hasTriggerTarget ? this.triggerTarget : content;
const { x, y } = this.point || this.pointFrom({}, trigger);
const anchor = {
getBoundingClientRect: () => ({ x, y, left: x, top: y, right: x, bottom: y, width: 0, height: 0 }),
contextElement: trigger,
};
const side = content.dataset.preferredSide || "right";
const align = content.dataset.align || "start";
const placement = align === "center" ? side : `${side}-${align}`;
const sideOffset = Number(content.dataset.sideOffset ?? 0);
const alignOffset = Number(content.dataset.alignOffset ?? 4);
computePosition(anchor, content, {
strategy: "fixed",
placement,
middleware: [
// alignmentAxis flips the offset for align: :end, as Base UI does.
offset({ mainAxis: sideOffset, crossAxis: alignOffset, alignmentAxis: alignOffset }),
flip(),
shift({ padding: 5 }),
size({
padding: 5,
apply({ availableHeight }) {
content.style.setProperty("--available-height", `${availableHeight}px`);
},
}),
],
}).then(({ x: left, y: top, placement: resolved }) => {
if (!content.isConnected) return;
const [resolvedSide, resolvedAlign] = resolved.split("-");
Object.assign(content.style, { left: `${left}px`, top: `${top}px` });
content.dataset.side = resolvedSide;
content.style.setProperty("--transform-origin", this.transformOrigin(resolvedSide, resolvedAlign));
});
}
// The menu grows out of the pointer.
transformOrigin(side, align) {
const opposite = { top: "bottom", bottom: "top", left: "right", right: "left" }[side];
const vertical = side === "top" || side === "bottom";
const cross = { start: vertical ? "left" : "top", end: vertical ? "right" : "bottom" }[align] || "center";
return vertical ? `${cross} ${opposite}` : `${opposite} ${cross}`;
}
// --- Exit animation (same block as the other overlay controllers) --------
exitAnimationNames = new WeakMap();
hideAfterExitAnimation(animated) {
const exitAnimations = animated.getAnimations().filter((animation) => animation instanceof CSSAnimation);
// No exit animation, or no box to run it in: animationend would never fire.
if (exitAnimations.length === 0) {
this.settleExit(animated);
return;
}
this.exitAnimationNames.set(animated, exitAnimations.map((animation) => animation.animationName));
animated.addEventListener("animationend", this.handleExitAnimationEnd);
animated.addEventListener("animationcancel", this.handleExitAnimationEnd);
}
handleExitAnimationEnd = (event) => {
// animationend bubbles — an animated child must not hide its container.
if (event.target !== event.currentTarget) return;
// Closing mid-open cancels the enter animation; only the exit run settles this.
if (!this.exitAnimationNames.get(event.currentTarget)?.includes(event.animationName)) return;
this.settleExit(event.currentTarget);
};
settleExit(animated) {
animated.removeEventListener("animationend", this.handleExitAnimationEnd);
animated.removeEventListener("animationcancel", this.handleExitAnimationEnd);
// Reopened mid-exit: it is on its way back in, leave it showing.
if (animated.hasAttribute("data-open")) return;
animated.removeAttribute("data-open");
animated.setAttribute("data-closed", "");
animated.dataset.state = "closed";
if (animated.matches(":popover-open")) animated.hidePopover();
}
}
15
Update the Stimulus controllers manifest file
rake stimulus:manifest:update16
Install @floating-ui/dom Javascript dependency
// with yarn
yarn add @floating-ui/dom
// with npm
npm install @floating-ui/dom
// with importmaps
bin/importmap pin @floating-ui/dom
Components
| Component | Built using | Source |
|---|---|---|
ContextMenu | Phlex | |
ContextMenuCheckboxItem | Phlex | |
ContextMenuContent | Phlex | |
ContextMenuDocs | Phlex | |
ContextMenuGroup | Phlex | |
ContextMenuItem | Phlex | |
ContextMenuItemIndicator | Phlex | |
ContextMenuLabel | Phlex | |
ContextMenuRadioGroup | Phlex | |
ContextMenuRadioItem | Phlex | |
ContextMenuSeparator | Phlex | |
ContextMenuShortcut | Phlex | |
ContextMenuTrigger | Phlex | |
ContextMenuController | Stimulus JS |