A menu that opens at the pointer on right-click.
use gpui::{div, prelude::*, px, Context, Window};
use crate::theme::ActiveTheme;
use crate::ui::context_menu::ContextMenu;
use crate::ui::dropdown_menu::MenuItem;
#[derive(Default)]
pub struct CanvasView {
open: bool,
}
impl Render for CanvasView {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let theme = cx.theme();
let area = div()
.w(px(300.0))
.h(px(150.0))
.flex()
.items_center()
.justify_center()
.rounded(theme.radius)
.border_1()
.border_dashed()
.border_color(theme.border)
.text_sm()
.child("Right click here");
ContextMenu::new("canvas-menu", self.open)
.trigger(area)
.on_open_change(cx.listener(|this, open: &bool, _, cx| {
this.open = *open;
cx.notify();
}))
.item(MenuItem::new("Back").shortcut("Alt+Left"))
.item(MenuItem::new("Forward").shortcut("Alt+Right").disabled(true))
.item(MenuItem::new("Reload").shortcut("Ctrl+R"))
.separator()
.label("Developer")
.item(MenuItem::new("Inspect element").on_select(|_, _, _| println!("inspect")))
}
}Installation
Copies src/ui/context_menu.rs into your project, along with any components it depends on, and registers the module in src/ui/mod.rs.
Install the theme
Every component reads colors from
crate::theme. Follow the installation guide if you have not added it yet.Copy the source
Paste the code below into
src/ui/context_menu.rs.src/ui/context_menu.rs use std::rc::Rc; use gpui::{ anchored, deferred, div, point, prelude::*, px, AnyElement, App, ElementId, FocusHandle, MouseButton, Pixels, Point, SharedString, Window, }; use crate::theme::ActiveTheme; use crate::ui::dropdown_menu::{menu_list_with_submenus, MenuEntry, MenuItem, Submenu, SubmenuTracker}; use crate::ui::popover::{animate_overlay, Presence, Side, Transition, SLIDE_IN}; type OpenChangeHandler = Rc<dyn Fn(&bool, &mut Window, &mut App) + 'static>; /// A menu that opens at the pointer when the trigger area is right-clicked. /// The parent view owns `open`. #[derive(IntoElement)] pub struct ContextMenu { id: ElementId, open: bool, trigger: Option<AnyElement>, entries: Vec<MenuEntry>, on_open_change: Option<OpenChangeHandler>, } /// The right-click position belongs to the gesture, not the app, so it is kept here alongside /// the focus handle Escape needs. struct ContextMenuState { position: Point<Pixels>, focus: FocusHandle, was_open: bool, submenus: Rc<SubmenuTracker>, /// Keeps the menu up while it animates out. presence: Presence, } impl ContextMenu { pub fn new(id: impl Into<ElementId>, open: bool) -> Self { Self { id: id.into(), open, trigger: None, entries: Vec::new(), on_open_change: None, } } /// The area that opens the menu on right-click. pub fn trigger(mut self, trigger: impl IntoElement) -> Self { self.trigger = Some(trigger.into_any_element()); self } pub fn item(mut self, item: MenuItem) -> Self { self.entries.push(MenuEntry::Item(item)); self } /// A non-interactive heading. pub fn label(mut self, label: impl Into<SharedString>) -> Self { self.entries.push(MenuEntry::Label(label.into())); self } pub fn separator(mut self) -> Self { self.entries.push(MenuEntry::Separator); self } /// A row that opens a nested menu to the right on hover. pub fn submenu(mut self, submenu: Submenu) -> Self { self.entries.push(MenuEntry::Submenu(submenu)); self } /// Receives the *next* open value. pub fn on_open_change( mut self, handler: impl Fn(&bool, &mut Window, &mut App) + 'static, ) -> Self { self.on_open_change = Some(Rc::new(handler)); self } } impl RenderOnce for ContextMenu { fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement { let open = self.open; let state = window.use_keyed_state(self.id.clone(), cx, |_, cx| ContextMenuState { position: point(px(0.0), px(0.0)), focus: cx.focus_handle(), was_open: false, submenus: Rc::default(), presence: Presence::default(), }); let (position, focus, just_opened, submenus, frame) = state.update(cx, |state, cx| { let just_opened = open && !state.was_open; state.was_open = open; // Reset on opening rather than closing, so an open submenu fades out with the menu. if just_opened { state.submenus.reset(); } let frame = state.presence.update(open, Transition::POPOVER, window, cx); (state.position, state.focus.clone(), just_opened, state.submenus.clone(), frame) }); if just_opened { // Deferred content joins the dispatch tree a frame late; Zed's menus wait two frames. let focus = focus.clone(); window.on_next_frame(move |window, _| { window.on_next_frame(move |window, cx| window.focus(&focus, cx)); }); } let theme = cx.theme(); let on_open_change = self.on_open_change; let menu = frame.visible().then(|| { let close = on_open_change.clone(); let escape = on_open_change.clone(); let close_guard = submenus.clone(); // A menu animating out no longer blocks the page or answers to the pointer. let panel = div() .when(open, |this| this.occlude()) .track_focus(&focus) .min_w(px(192.0)) .rounded(theme.radius) .border_1() .border_color(theme.border) .bg(theme.background) .text_color(theme.foreground) .shadow_md() .when(open, |this| { this.on_mouse_down_out(move |event, window, cx| { // A submenu hangs outside this panel, so a click in it isn't outside the menu. if close_guard.contains(event.position) { return; } if let Some(close) = &close { close(&false, window, cx); } }) .on_key_down(move |event, window, cx| { if event.keystroke.key == "escape" { if let Some(escape) = &escape { escape(&false, window, cx); } cx.stop_propagation(); } }) }) .child(menu_list_with_submenus(self.entries, on_open_change.clone(), submenus, cx)); // Radix opens a context menu on the pointer's right, so it slides in from the left. let panel = animate_overlay(panel, Side::Right, frame, SLIDE_IN); deferred( anchored() // The default fit mode flips the menu to the other side of the cursor // instead of sliding it under the pointer. .position(position) .child(panel), ) .with_priority(1) }); let handler = on_open_change; div() .id(self.id) .on_mouse_down(MouseButton::Right, move |event, window, cx| { state.update(cx, |state, _| state.position = event.position); if let Some(handler) = &handler { handler(&true, window, cx); } // A menu that was already open must move to the new click, so force a redraw. window.refresh(); }) .children(self.trigger) .children(menu) } }Register the module
// src/ui/mod.rs pub mod context_menu;
Usage
use crate::ui::context_menu::*;Examples
Basic
A right-click area with a few actions. Selecting one runs its on_select and closes the menu.
use gpui::{div, prelude::*, px, App, Context, Window};
use crate::theme::ActiveTheme;
use crate::ui::context_menu::ContextMenu;
use crate::ui::dropdown_menu::MenuItem;
#[derive(Default)]
pub struct ContextMenuBasic {
open: bool,
}
impl Render for ContextMenuBasic {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
ContextMenu::new("context-menu-basic", self.open)
.trigger(area(cx))
.on_open_change(cx.listener(|this, open: &bool, _, cx| {
this.open = *open;
cx.notify();
}))
.item(MenuItem::new("Back"))
.item(MenuItem::new("Forward").disabled(true))
.item(MenuItem::new("Reload"))
.item(MenuItem::new("Save page as..."))
}
}
fn area(cx: &App) -> impl IntoElement {
let theme = cx.theme();
div()
.w(px(300.0))
.h(px(150.0))
.flex()
.items_center()
.justify_center()
.rounded(theme.radius)
.border_1()
.border_dashed()
.border_color(theme.border)
.text_sm()
.child("Right click here")
}Submenu
submenu adds a row that opens a nested Submenu to its right when hovered.
use gpui::{div, prelude::*, px, App, Context, Window};
use crate::theme::ActiveTheme;
use crate::ui::context_menu::ContextMenu;
use crate::ui::dropdown_menu::{MenuItem, Submenu};
#[derive(Default)]
pub struct ContextMenuSubmenu {
open: bool,
}
impl Render for ContextMenuSubmenu {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
// Wide enough for the submenu to open beside the menu inside the preview.
div().w(px(560.0)).child(
ContextMenu::new("context-menu-submenu", self.open)
.trigger(area(cx))
.on_open_change(cx.listener(|this, open: &bool, _, cx| {
this.open = *open;
cx.notify();
}))
.item(MenuItem::new("Back"))
.item(MenuItem::new("Forward"))
.item(MenuItem::new("Reload"))
.submenu(
Submenu::new("More tools")
.item(MenuItem::new("Save page as..."))
.item(MenuItem::new("Create shortcut..."))
.item(MenuItem::new("Name window..."))
.separator()
.item(MenuItem::new("Developer tools")),
)
.separator()
.item(MenuItem::new("Delete").destructive(true)),
)
}
}
fn area(cx: &App) -> impl IntoElement {
let theme = cx.theme();
div()
.w(px(300.0))
.h(px(150.0))
.flex()
.items_center()
.justify_center()
.rounded(theme.radius)
.border_1()
.border_dashed()
.border_color(theme.border)
.text_sm()
.child("Right click here")
}Shortcuts
shortcut shows a key hint at the right of an item. It is display only: bind the keys in your app.
use gpui::{div, prelude::*, px, App, Context, Window};
use crate::theme::ActiveTheme;
use crate::ui::context_menu::ContextMenu;
use crate::ui::dropdown_menu::MenuItem;
#[derive(Default)]
pub struct ContextMenuShortcuts {
open: bool,
}
impl Render for ContextMenuShortcuts {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
ContextMenu::new("context-menu-shortcuts", self.open)
.trigger(area(cx))
.on_open_change(cx.listener(|this, open: &bool, _, cx| {
this.open = *open;
cx.notify();
}))
.item(MenuItem::new("Back").shortcut("Alt+Left"))
.item(MenuItem::new("Forward").shortcut("Alt+Right"))
.item(MenuItem::new("Reload").shortcut("Ctrl+R"))
.separator()
.item(MenuItem::new("Save page as...").shortcut("Ctrl+S"))
.item(MenuItem::new("Print...").shortcut("Ctrl+P"))
}
}
fn area(cx: &App) -> impl IntoElement {
let theme = cx.theme();
div()
.w(px(300.0))
.h(px(150.0))
.flex()
.items_center()
.justify_center()
.rounded(theme.radius)
.border_1()
.border_dashed()
.border_color(theme.border)
.text_sm()
.child("Right click here")
}Groups
label and separator split related actions into titled groups.
use gpui::{div, prelude::*, px, App, Context, Window};
use crate::theme::ActiveTheme;
use crate::ui::context_menu::ContextMenu;
use crate::ui::dropdown_menu::MenuItem;
#[derive(Default)]
pub struct ContextMenuGroups {
open: bool,
}
impl Render for ContextMenuGroups {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
ContextMenu::new("context-menu-groups", self.open)
.trigger(area(cx))
.on_open_change(cx.listener(|this, open: &bool, _, cx| {
this.open = *open;
cx.notify();
}))
.label("File")
.item(MenuItem::new("New file").shortcut("Ctrl+N"))
.item(MenuItem::new("Open file").shortcut("Ctrl+O"))
.item(MenuItem::new("Save").shortcut("Ctrl+S"))
.separator()
.label("Edit")
.item(MenuItem::new("Undo").shortcut("Ctrl+Z"))
.item(MenuItem::new("Redo").shortcut("Ctrl+Y"))
.separator()
.item(MenuItem::new("Delete").destructive(true))
}
}
fn area(cx: &App) -> impl IntoElement {
let theme = cx.theme();
div()
.w(px(300.0))
.h(px(150.0))
.flex()
.items_center()
.justify_center()
.rounded(theme.radius)
.border_1()
.border_dashed()
.border_color(theme.border)
.text_sm()
.child("Right click here")
}Icons
icon puts an icon before an item's label.
use gpui::{div, prelude::*, px, svg, App, Context, Hsla, Window};
use crate::theme::ActiveTheme;
use crate::ui::context_menu::ContextMenu;
use crate::ui::dropdown_menu::MenuItem;
use crate::icons::{CLIPBOARD, COPY, SCISSORS, TRASH_2};
#[derive(Default)]
pub struct ContextMenuIcons {
open: bool,
}
impl Render for ContextMenuIcons {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let (fg, destructive) = (cx.theme().foreground, cx.theme().destructive);
ContextMenu::new("context-menu-icons", self.open)
.trigger(area(cx))
.on_open_change(cx.listener(|this, open: &bool, _, cx| {
this.open = *open;
cx.notify();
}))
.item(MenuItem::new("Copy").icon(icon(COPY, fg)))
.item(MenuItem::new("Cut").icon(icon(SCISSORS, fg)))
.item(MenuItem::new("Paste").icon(icon(CLIPBOARD, fg)))
.separator()
.item(MenuItem::new("Delete").icon(icon(TRASH_2, destructive)).destructive(true))
}
}
fn icon(data: &'static [u8], color: Hsla) -> impl IntoElement {
svg().data(data).flex_none().size(px(16.0)).text_color(color)
}
fn area(cx: &App) -> impl IntoElement {
let theme = cx.theme();
div()
.w(px(300.0))
.h(px(150.0))
.flex()
.items_center()
.justify_center()
.rounded(theme.radius)
.border_1()
.border_dashed()
.border_color(theme.border)
.text_sm()
.child("Right click here")
}Checkboxes
checked turns an item into a checkbox. The menu stays open so several can be toggled.
use gpui::{div, prelude::*, px, App, ClickEvent, Context, Window};
use crate::theme::ActiveTheme;
use crate::ui::context_menu::ContextMenu;
use crate::ui::dropdown_menu::MenuItem;
pub struct ContextMenuCheckboxes {
open: bool,
bookmarks_bar: bool,
full_urls: bool,
developer_tools: bool,
}
// The bookmarks bar starts on, so `Default` is written out instead of derived.
impl Default for ContextMenuCheckboxes {
fn default() -> Self {
Self {
open: false,
bookmarks_bar: true,
full_urls: false,
developer_tools: false,
}
}
}
impl Render for ContextMenuCheckboxes {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
ContextMenu::new("context-menu-checkboxes", self.open)
.trigger(area(cx))
.on_open_change(cx.listener(|this, open: &bool, _, cx| {
this.open = *open;
cx.notify();
}))
.label("View")
.separator()
.item(
MenuItem::new("Show bookmarks bar")
.checked(self.bookmarks_bar)
.on_select(cx.listener(|this, _: &ClickEvent, _, cx| {
this.bookmarks_bar = !this.bookmarks_bar;
cx.notify();
})),
)
.item(
MenuItem::new("Show full URLs")
.checked(self.full_urls)
.on_select(cx.listener(|this, _: &ClickEvent, _, cx| {
this.full_urls = !this.full_urls;
cx.notify();
})),
)
.item(
MenuItem::new("Show developer tools")
.checked(self.developer_tools)
.on_select(cx.listener(|this, _: &ClickEvent, _, cx| {
this.developer_tools = !this.developer_tools;
cx.notify();
})),
)
}
}
fn area(cx: &App) -> impl IntoElement {
let theme = cx.theme();
div()
.w(px(300.0))
.h(px(150.0))
.flex()
.items_center()
.justify_center()
.rounded(theme.radius)
.border_1()
.border_dashed()
.border_color(theme.border)
.text_sm()
.child("Right click here")
}Radio
radio marks one option of a group with a dot. The view keeps which one is chosen.
use gpui::{div, prelude::*, px, App, ClickEvent, Context, Window};
use crate::theme::ActiveTheme;
use crate::ui::context_menu::ContextMenu;
use crate::ui::dropdown_menu::MenuItem;
const PEOPLE: [&str; 3] = ["Pedro Duarte", "Colm Tuite", "Ada Lovelace"];
#[derive(Default)]
pub struct ContextMenuRadio {
open: bool,
person: usize,
}
impl Render for ContextMenuRadio {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let menu = ContextMenu::new("context-menu-radio", self.open)
.trigger(area(cx))
.on_open_change(cx.listener(|this, open: &bool, _, cx| {
this.open = *open;
cx.notify();
}))
.label("People")
.separator();
PEOPLE.iter().enumerate().fold(menu, |menu, (ix, name)| {
menu.item(
MenuItem::new(*name)
.radio(self.person == ix)
.on_select(cx.listener(move |this, _: &ClickEvent, _, cx| {
this.person = ix;
cx.notify();
})),
)
})
}
}
fn area(cx: &App) -> impl IntoElement {
let theme = cx.theme();
div()
.w(px(300.0))
.h(px(150.0))
.flex()
.items_center()
.justify_center()
.rounded(theme.radius)
.border_1()
.border_dashed()
.border_color(theme.border)
.text_sm()
.child("Right click here")
}Destructive
destructive(true) colors an irreversible action red, apart from the safe ones above it.
use gpui::{div, prelude::*, px, svg, App, Context, Hsla, Window};
use crate::theme::ActiveTheme;
use crate::ui::context_menu::ContextMenu;
use crate::ui::dropdown_menu::MenuItem;
use crate::icons::{ARCHIVE, PENCIL, SHARE, TRASH_2};
#[derive(Default)]
pub struct ContextMenuDestructive {
open: bool,
}
impl Render for ContextMenuDestructive {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let (fg, destructive) = (cx.theme().foreground, cx.theme().destructive);
ContextMenu::new("context-menu-destructive", self.open)
.trigger(area(cx))
.on_open_change(cx.listener(|this, open: &bool, _, cx| {
this.open = *open;
cx.notify();
}))
.item(MenuItem::new("Edit").icon(icon(PENCIL, fg)))
.item(MenuItem::new("Share").icon(icon(SHARE, fg)))
.item(MenuItem::new("Archive").icon(icon(ARCHIVE, fg)))
.separator()
.item(MenuItem::new("Delete").icon(icon(TRASH_2, destructive)).destructive(true))
}
}
fn icon(data: &'static [u8], color: Hsla) -> impl IntoElement {
svg().data(data).flex_none().size(px(16.0)).text_color(color)
}
fn area(cx: &App) -> impl IntoElement {
let theme = cx.theme();
div()
.w(px(300.0))
.h(px(150.0))
.flex()
.items_center()
.justify_center()
.rounded(theme.radius)
.border_1()
.border_dashed()
.border_color(theme.border)
.text_sm()
.child("Right click here")
}API Reference
ContextMenu
A menu that opens at the pointer when the trigger area is right-clicked. The parent view owns open.
ContextMenu::new(id: impl Into<ElementId>, open: bool) -> Self.trigger(trigger: impl IntoElement)The area that opens the menu on right-click.
.item(item: MenuItem).label(label: impl Into<SharedString>)A non-interactive heading.
.separator().submenu(submenu: Submenu)A row that opens a nested menu to the right on hover.
.on_open_change(handler: impl Fn(&bool, &mut Window, &mut App) + 'static)Receives the *next* open value.