A menu of actions that opens from a trigger.
use gpui::{div, prelude::*, px, Context, Window};
use crate::ui::button::{Button, ButtonVariant};
use crate::ui::dropdown_menu::{DropdownMenu, MenuItem};
#[derive(Default)]
pub struct AccountMenuView {
open: bool,
}
impl Render for AccountMenuView {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
// Top-aligned so the menu has room to open downward in the preview.
div().h(px(300.0)).w(px(224.0)).child(
DropdownMenu::new("account-menu", self.open)
.trigger(Button::new("account-trigger", "My account").variant(ButtonVariant::Outline))
.on_open_change(cx.listener(|this, open: &bool, _, cx| {
this.open = *open;
cx.notify();
}))
.label("ada@hyuskui.com")
.separator()
.item(MenuItem::new("Profile").shortcut("Ctrl+P"))
.item(MenuItem::new("Billing").shortcut("Ctrl+B"))
.item(MenuItem::new("Team").disabled(true))
.separator()
.item(MenuItem::new("Log out").destructive(true).on_select(|_, _, _| {
println!("logged out");
})),
)
}
}Installation
Copies src/ui/dropdown_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.Install the icons
This component draws icons from
crate::icons. Copy src/icons.rs into your project and declaremod icons;next tomod theme;.Copy the source
Paste the code below into
src/ui/dropdown_menu.rs.src/ui/dropdown_menu.rs use std::{ cell::{Cell, RefCell}, collections::HashMap, rc::Rc, sync::Arc, time::Duration, }; use gpui::{ canvas, div, prelude::*, px, relative, svg, Animation, AnimationExt, AnyElement, App, Bounds, ClickEvent, ElementId, FontWeight, Hsla, Pixels, Point, SharedString, Window, }; use crate::theme::ActiveTheme; use crate::ui::popover::{animation_clock, ease, Align, Popover, Side, Transition, SLIDE_IN}; use crate::icons::{CHECK, CHEVRON_RIGHT}; type SelectHandler = Rc<dyn Fn(&ClickEvent, &mut Window, &mut App) + 'static>; type OpenChangeHandler = Rc<dyn Fn(&bool, &mut Window, &mut App) + 'static>; /// The menu panel's border plus padding: a submenu opens this far right of its row so it /// lines up with the outside of the parent panel. const SUBMENU_GAP: Pixels = px(5.0); #[derive(Clone, Copy, PartialEq)] enum Indicator { Check(bool), Radio(bool), } /// One clickable row. Selecting it runs `on_select` and closes the menu. pub struct MenuItem { label: SharedString, shortcut: Option<SharedString>, icon: Option<AnyElement>, indicator: Option<Indicator>, close_on_select: Option<bool>, disabled: bool, destructive: bool, on_select: Option<SelectHandler>, } impl MenuItem { pub fn new(label: impl Into<SharedString>) -> Self { Self { label: label.into(), shortcut: None, icon: None, indicator: None, close_on_select: None, disabled: false, destructive: false, on_select: None, } } /// Right-aligned hint such as "Ctrl+S". Display only: bind the keys in your app. pub fn shortcut(mut self, shortcut: impl Into<SharedString>) -> Self { self.shortcut = Some(shortcut.into()); self } /// An icon before the label. Size it to 16px and give it a color: GPUI doesn't pass the /// text color down to SVGs. pub fn icon(mut self, icon: impl IntoElement) -> Self { self.icon = Some(icon.into_any_element()); self } /// Makes this a checkbox item that shows a check mark while `checked`. Flip your value /// in `on_select`. The menu stays open so several options can be toggled. pub fn checked(mut self, checked: bool) -> Self { self.indicator = Some(Indicator::Check(checked)); self } /// Makes this a radio item that shows a check while `selected`. Give each option in a group /// its own item and set your value in `on_select`. The menu stays open, as with /// checkbox items. pub fn radio(mut self, selected: bool) -> Self { self.indicator = Some(Indicator::Radio(selected)); self } /// Whether selecting the item closes the menu. Defaults to `true`, or `false` for /// `checked` and `radio` items. pub fn close_on_select(mut self, close: bool) -> Self { self.close_on_select = Some(close); self } pub fn disabled(mut self, disabled: bool) -> Self { self.disabled = disabled; self } /// Red text, for actions like "Delete". pub fn destructive(mut self, destructive: bool) -> Self { self.destructive = destructive; self } pub fn on_select( mut self, handler: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static, ) -> Self { self.on_select = Some(Rc::new(handler)); self } } /// A row that opens a nested menu to its right on hover. Build its rows the same way as the /// menu's own. pub struct Submenu { label: SharedString, icon: Option<AnyElement>, entries: Vec<MenuEntry>, } impl Submenu { pub fn new(label: impl Into<SharedString>) -> Self { Self { label: label.into(), icon: None, entries: Vec::new(), } } /// An icon before the label, as with [`MenuItem::icon`]. pub fn icon(mut self, icon: impl IntoElement) -> Self { self.icon = Some(icon.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 further nested menu. pub fn submenu(mut self, submenu: Submenu) -> Self { self.entries.push(MenuEntry::Submenu(submenu)); self } } /// The rows of a menu. Context menu renders the same list. pub enum MenuEntry { Item(MenuItem), Label(SharedString), Separator, Submenu(Submenu), } /// Which submenu of one menu level is open, and where its panel was painted. A submenu /// panel hangs outside its menu's bounds, so the menu checks [`SubmenuTracker::contains`] /// before treating a click as outside. Keep one per open menu across frames. #[derive(Default)] pub struct SubmenuTracker { open: Cell<Option<usize>>, area: Cell<Option<Bounds<Pixels>>>, children: RefCell<HashMap<usize, Rc<SubmenuTracker>>>, /// The submenu that just closed and when, so it can animate out. closing: Cell<Option<(usize, Duration)>>, /// Whether the menu this tracker belongs to was open last frame. menu_open: Cell<bool>, } impl SubmenuTracker { /// Whether `position` is over an open submenu panel at any depth. pub fn contains(&self, position: Point<Pixels>) -> bool { let Some(open) = self.open.get() else { return false; }; self.area.get().is_some_and(|area| area.contains(&position)) || self.children.borrow().get(&open).is_some_and(|child| child.contains(position)) } /// Closes every submenu, e.g. when the menu itself closes. pub fn reset(&self) { self.open.set(None); self.area.set(None); self.closing.set(None); self.children.borrow_mut().clear(); } /// Closes every submenu when the menu opens again, so one left open when it closed fades /// out with the menu instead of vanishing first. pub fn track_menu_open(&self, open: bool) { if open && !self.menu_open.get() { self.reset(); } self.menu_open.set(open); } /// Returns whether anything changed, so callers only redraw when needed. fn set_open(&self, open: Option<usize>, cx: &App) -> bool { if self.open.get() == open { return false; } if let Some(previous) = self.open.get() { if let Some(child) = self.children.borrow().get(&previous) { child.reset(); } if !cx.reduce_motion() { self.closing.set(Some((previous, animation_clock(cx)))); } } self.open.set(open); self.area.set(None); true } fn child(&self, ix: usize) -> Rc<SubmenuTracker> { self.children.borrow_mut().entry(ix).or_default().clone() } } #[derive(Clone, Copy)] struct MenuColors { foreground: Hsla, background: Hsla, accent: Hsla, accent_fg: Hsla, muted_fg: Hsla, border: Hsla, destructive: Hsla, } /// Renders `entries` as a padded column. `close` runs after an item's own handler. /// Submenus open on hover only when the list is redrawn with the same tracker, so prefer /// [`DropdownMenu`] or the context menu, which keep one; see [`menu_list_with_submenus`]. pub fn menu_list(entries: Vec<MenuEntry>, close: Option<OpenChangeHandler>, cx: &App) -> impl IntoElement { menu_list_with_submenus(entries, close, Rc::default(), cx) } /// [`menu_list`] with a [`SubmenuTracker`] that the caller keeps across frames. pub fn menu_list_with_submenus( entries: Vec<MenuEntry>, close: Option<OpenChangeHandler>, submenus: Rc<SubmenuTracker>, cx: &App, ) -> impl IntoElement { let theme = cx.theme(); let colors = MenuColors { foreground: theme.foreground, background: theme.background, accent: theme.accent, accent_fg: theme.accent_foreground, muted_fg: theme.muted_foreground, border: theme.border, destructive: theme.destructive, }; let radius = theme.radius; entry_list(entries, close, submenus, colors, radius, animation_clock(cx)) } fn entry_list( entries: Vec<MenuEntry>, close: Option<OpenChangeHandler>, submenus: Rc<SubmenuTracker>, colors: MenuColors, panel_radius: Pixels, now: Duration, ) -> gpui::Div { let radius = px(4.0); // Hovering any other row closes the open submenu. let hover_closes = |tracker: Rc<SubmenuTracker>| { move |hovered: &bool, window: &mut Window, cx: &mut App| { if *hovered && tracker.set_open(None, cx) { window.refresh(); } } }; div() .flex() .flex_col() .p_1() .children(entries.into_iter().enumerate().map(|(ix, entry)| match entry { // A small muted heading, like shadcn's `px-1.5 py-1 text-xs font-medium`. MenuEntry::Label(label) => div() .px(px(6.0)) .py_1() .text_xs() .line_height(px(16.0)) .font_weight(FontWeight::MEDIUM) .text_color(colors.muted_fg) .child(label) .into_any_element(), MenuEntry::Separator => div() .mx(px(-4.0)) .my_1() .h(px(1.0)) .bg(colors.border) .into_any_element(), MenuEntry::Item(item) => { let disabled = item.disabled; let close_on_select = item.close_on_select.unwrap_or(item.indicator.is_none()); let close = close.clone().filter(|_| close_on_select); let destructive = colors.destructive; let indicator = item.indicator.map(|indicator| { let slot = div().flex().flex_none().items_center().justify_center().size(px(16.0)); match indicator { Indicator::Check(checked) => slot.when(checked, |this| { this.child(svg().data(CHECK).size(px(16.0)).text_color(colors.foreground)) }), // shadcn marks the chosen option of a group with a check too. Indicator::Radio(selected) => slot.when(selected, |this| { this.child(svg().data(CHECK).size(px(16.0)).text_color(colors.foreground)) }), } }); div() .id(("menu-item", ix)) .flex() .items_center() .gap_2() .h(px(32.0)) .px_2() .rounded(radius) .text_sm() .on_hover(hover_closes(submenus.clone())) .when(item.destructive, |this| this.text_color(destructive)) .when(disabled, |this| this.opacity(0.5).cursor_not_allowed()) .when(!disabled, |this| { let destructive_item = item.destructive; this.cursor_pointer().hover(move |style| { let style = style.bg(if destructive_item { destructive.opacity(0.1) } else { colors.accent }); if destructive_item { style } else { style.text_color(colors.accent_fg) } }) }) .when(!disabled, |this| { let on_select = item.on_select.clone(); this.on_click(move |event, window, cx| { if let Some(on_select) = &on_select { on_select(event, window, cx); } if let Some(close) = &close { close(&false, window, cx); } }) }) .children(item.icon) .child(div().flex_1().child(item.label)) .when_some(item.shortcut, |this, shortcut| { this.child(div().text_xs().text_color(colors.muted_fg).child(shortcut)) }) .children(indicator) .into_any_element() } MenuEntry::Submenu(submenu) => { let open = submenus.open.get() == Some(ix); // How far a submenu that just closed is through its exit, if it still is. let exit = Transition::POPOVER.exit; let closing = submenus .closing .get() .filter(|(closed, _)| *closed == ix && !open) .map(|(_, since)| now.saturating_sub(since).as_secs_f32() / exit.as_secs_f32()) .filter(|progress| *progress < 1.0); let panel = (open || closing.is_some()).then(|| { let area = submenus.clone(); let body = div() .when(open, |this| this.occlude()) .min_w(px(192.0)) .rounded(panel_radius) .border_1() .border_color(colors.border) .bg(colors.background) .text_color(colors.foreground) .shadow_md() .child(entry_list( submenu.entries, close.clone(), submenus.child(ix), colors, panel_radius, now, )); let body = match closing { // fade-out-0 zoom-out-95: fades while drifting back toward its row. Some(progress) => { let t = ease(progress); body.opacity(1.0 - t) .left(-px(4.0) * t) // `entry_list` has no window, so the panel asks for its own // frames until the exit is over. .child( canvas(|_, window, _| window.request_animation_frame(), |_, _, _, _| {}) .absolute() .size_0(), ) .into_any_element() } // fade-in-0 zoom-in-95 slide-in-from-left-2, replayed on each mount. None => body .with_animation( ("submenu-in", ix), Animation::new(Transition::POPOVER.enter).with_easing(ease), |body, t| body.opacity(t).left(-SLIDE_IN * (1.0 - t)), ) .into_any_element(), }; div() .absolute() .top(-SUBMENU_GAP) .left(relative(1.0)) .ml(SUBMENU_GAP) .when(open, |this| { this.on_children_prepainted(move |bounds, _, _| { area.area.set(bounds.first().copied()); }) }) .child(body) }); let hover = submenus.clone(); let click = submenus.clone(); div() .id(("menu-submenu", ix)) .relative() .flex() .items_center() .gap_2() .h(px(32.0)) .px_2() .rounded(radius) .text_sm() .cursor_pointer() .when(open, |this| this.bg(colors.accent).text_color(colors.accent_fg)) .hover(move |style| style.bg(colors.accent).text_color(colors.accent_fg)) .on_hover(move |hovered, window, cx| { if *hovered && hover.set_open(Some(ix), cx) { window.refresh(); } }) // A click opens it too, for pointers that can't hover. .on_click(move |_, window, cx| { if click.set_open(Some(ix), cx) { window.refresh(); } }) .children(submenu.icon) .child(div().flex_1().child(submenu.label)) .child(svg().data(CHEVRON_RIGHT).size(px(16.0)).text_color(colors.muted_fg)) .children(panel) .into_any_element() } })) } /// A menu that opens from a trigger. The parent view owns `open`. #[derive(IntoElement)] pub struct DropdownMenu { id: ElementId, open: bool, trigger: Option<AnyElement>, entries: Vec<MenuEntry>, align: Align, width: gpui::Pixels, full_width: bool, side: Side, on_open_change: Option<OpenChangeHandler>, } impl DropdownMenu { pub fn new(id: impl Into<ElementId>, open: bool) -> Self { Self { id: id.into(), open, trigger: None, entries: Vec::new(), align: Align::Start, width: px(224.0), full_width: false, side: Side::Bottom, on_open_change: None, } } /// The element that toggles the menu when clicked. 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 } pub fn align(mut self, align: Align) -> Self { self.align = align; self } /// Which side of the trigger the menu opens on. Below it by default. pub fn side(mut self, side: Side) -> Self { self.side = side; self } /// Stretches the trigger to the menu's full width, such as a switcher filling a sidebar row. pub fn full_width(mut self, full_width: bool) -> Self { self.full_width = full_width; self } pub fn width(mut self, width: impl Into<gpui::Pixels>) -> Self { self.width = width.into(); 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 DropdownMenu { fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement { let submenus = window .use_keyed_state( ElementId::NamedChild(Arc::new(self.id.clone()), "submenus".into()), cx, |_, _| Rc::new(SubmenuTracker::default()), ) .read(cx) .clone(); submenus.track_menu_open(self.open); let on_open_change = self.on_open_change; let list = menu_list_with_submenus(self.entries, on_open_change.clone(), submenus.clone(), cx); Popover::new(self.id, self.open) .side(self.side) .align(self.align) .width(self.width) .padded(false) .full_width(self.full_width) .when_some(self.trigger, |this, trigger| this.trigger(trigger)) .when_some(on_open_change, |this, handler| { this.on_open_change(move |open, window, cx| { // The popover sees a click in a submenu as outside its panel. Escape still // closes, since only a pointer press is over the submenu. let in_submenu = !window.last_input_was_keyboard() && submenus.contains(window.mouse_position()); if *open || !in_submenu { handler(open, window, cx); } }) }) .child(list) } }Register the module
// src/ui/mod.rs pub mod dropdown_menu;
Usage
use crate::ui::dropdown_menu::*;Examples
Basic
A button that opens a menu of labelled groups split by separators.
use gpui::{div, prelude::*, px, Context, Window};
use crate::ui::button::{Button, ButtonVariant};
use crate::ui::dropdown_menu::{DropdownMenu, MenuItem};
#[derive(Default)]
pub struct DropdownMenuBasic {
open: bool,
}
impl Render for DropdownMenuBasic {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
// Tall enough for the menu to open downward inside the preview.
div().h(px(420.0)).w(px(224.0)).child(
DropdownMenu::new("dropdown-menu-basic", self.open)
.trigger(Button::new("dropdown-menu-basic-trigger", "Open").variant(ButtonVariant::Outline))
.on_open_change(cx.listener(|this, open: &bool, _, cx| {
this.open = *open;
cx.notify();
}))
.label("My account")
.item(MenuItem::new("Profile"))
.item(MenuItem::new("Billing"))
.item(MenuItem::new("Settings"))
.separator()
.label("Team")
.item(MenuItem::new("Members"))
.item(MenuItem::new("Invite users"))
.separator()
.item(MenuItem::new("GitHub"))
.item(MenuItem::new("Support"))
.item(MenuItem::new("API").disabled(true)),
)
}
}Submenu
submenu adds a row that opens a nested Submenu to its right when hovered.
use gpui::{div, prelude::*, px, Context, Window};
use crate::ui::button::{Button, ButtonVariant};
use crate::ui::dropdown_menu::{DropdownMenu, MenuItem, Submenu};
#[derive(Default)]
pub struct DropdownMenuSubmenu {
open: bool,
}
impl Render for DropdownMenuSubmenu {
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().h(px(260.0)).w(px(460.0)).child(
DropdownMenu::new("dropdown-menu-submenu", self.open)
.trigger(Button::new("dropdown-menu-submenu-trigger", "Open").variant(ButtonVariant::Outline))
.on_open_change(cx.listener(|this, open: &bool, _, cx| {
this.open = *open;
cx.notify();
}))
.item(MenuItem::new("Team"))
.submenu(
Submenu::new("Invite users")
.item(MenuItem::new("Email"))
.item(MenuItem::new("Message"))
.separator()
.item(MenuItem::new("More...")),
)
.item(MenuItem::new("New team").shortcut("Ctrl+T")),
)
}
}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, Context, Window};
use crate::ui::button::{Button, ButtonVariant};
use crate::ui::dropdown_menu::{DropdownMenu, MenuItem};
#[derive(Default)]
pub struct DropdownMenuShortcuts {
open: bool,
}
impl Render for DropdownMenuShortcuts {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
div().h(px(280.0)).w(px(224.0)).child(
DropdownMenu::new("dropdown-menu-shortcuts", self.open)
.trigger(Button::new("dropdown-menu-shortcuts-trigger", "Open").variant(ButtonVariant::Outline))
.on_open_change(cx.listener(|this, open: &bool, _, cx| {
this.open = *open;
cx.notify();
}))
.label("My account")
.item(MenuItem::new("Profile").shortcut("Shift+Ctrl+P"))
.item(MenuItem::new("Billing").shortcut("Ctrl+B"))
.item(MenuItem::new("Settings").shortcut("Ctrl+,"))
.item(MenuItem::new("Keyboard shortcuts").shortcut("Ctrl+K"))
.separator()
.item(MenuItem::new("Log out").shortcut("Shift+Ctrl+Q")),
)
}
}Icons
icon puts an icon before an item's label.
use gpui::{div, prelude::*, px, svg, Context, Hsla, Window};
use crate::theme::ActiveTheme;
use crate::ui::button::{Button, ButtonVariant};
use crate::ui::dropdown_menu::{DropdownMenu, MenuItem};
use crate::icons::{CREDIT_CARD, LOG_OUT, SETTINGS, USER};
#[derive(Default)]
pub struct DropdownMenuIcons {
open: bool,
}
impl Render for DropdownMenuIcons {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let fg = cx.theme().foreground;
div().h(px(240.0)).w(px(224.0)).child(
DropdownMenu::new("dropdown-menu-icons", self.open)
.trigger(Button::new("dropdown-menu-icons-trigger", "Open").variant(ButtonVariant::Outline))
.on_open_change(cx.listener(|this, open: &bool, _, cx| {
this.open = *open;
cx.notify();
}))
.item(MenuItem::new("Profile").icon(icon(USER, fg)))
.item(MenuItem::new("Billing").icon(icon(CREDIT_CARD, fg)))
.item(MenuItem::new("Settings").icon(icon(SETTINGS, fg)))
.separator()
.item(MenuItem::new("Log out").icon(icon(LOG_OUT, fg))),
)
}
}
fn icon(data: &'static [u8], color: Hsla) -> impl IntoElement {
svg().data(data).flex_none().size(px(16.0)).text_color(color)
}Checkboxes
checked turns an item into a checkbox. The menu stays open so several can be toggled.
use gpui::{div, prelude::*, px, ClickEvent, Context, Window};
use crate::ui::button::{Button, ButtonVariant};
use crate::ui::dropdown_menu::{DropdownMenu, MenuItem};
pub struct DropdownMenuCheckboxes {
open: bool,
status_bar: bool,
panel: bool,
}
// The status bar starts shown, so `Default` is written out instead of derived.
impl Default for DropdownMenuCheckboxes {
fn default() -> Self {
Self {
open: false,
status_bar: true,
panel: false,
}
}
}
impl Render for DropdownMenuCheckboxes {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
div().h(px(220.0)).w(px(224.0)).child(
DropdownMenu::new("dropdown-menu-checkboxes", self.open)
.trigger(Button::new("dropdown-menu-checkboxes-trigger", "Open").variant(ButtonVariant::Outline))
.on_open_change(cx.listener(|this, open: &bool, _, cx| {
this.open = *open;
cx.notify();
}))
.label("Appearance")
.separator()
.item(
MenuItem::new("Status bar")
.checked(self.status_bar)
.on_select(cx.listener(|this, _: &ClickEvent, _, cx| {
this.status_bar = !this.status_bar;
cx.notify();
})),
)
.item(MenuItem::new("Activity bar").checked(false).disabled(true))
.item(
MenuItem::new("Panel")
.checked(self.panel)
.on_select(cx.listener(|this, _: &ClickEvent, _, cx| {
this.panel = !this.panel;
cx.notify();
})),
),
)
}
}Checkboxes Icons
Checkbox items take an icon too, so each notification channel shows what it is.
use gpui::{div, prelude::*, px, svg, ClickEvent, Context, Hsla, Window};
use crate::theme::ActiveTheme;
use crate::ui::button::{Button, ButtonVariant};
use crate::ui::dropdown_menu::{DropdownMenu, MenuItem};
use crate::icons::{BELL, MAIL, MESSAGE_SQUARE};
const CHANNELS: [(&str, &[u8]); 3] = [("Email", MAIL), ("SMS", MESSAGE_SQUARE), ("Push", BELL)];
pub struct DropdownMenuCheckboxesIcons {
open: bool,
enabled: [bool; 3],
}
// Email starts on, so `Default` is written out instead of derived.
impl Default for DropdownMenuCheckboxesIcons {
fn default() -> Self {
Self {
open: false,
enabled: [true, false, true],
}
}
}
impl Render for DropdownMenuCheckboxesIcons {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let fg = cx.theme().foreground;
let menu = DropdownMenu::new("dropdown-menu-checkboxes-icons", self.open)
.trigger(
Button::new("dropdown-menu-checkboxes-icons-trigger", "Notifications")
.variant(ButtonVariant::Outline),
)
.on_open_change(cx.listener(|this, open: &bool, _, cx| {
this.open = *open;
cx.notify();
}))
.label("Notify me by")
.separator();
let menu = CHANNELS.iter().enumerate().fold(menu, |menu, (ix, &(name, data))| {
menu.item(
MenuItem::new(name)
.icon(icon(data, fg))
.checked(self.enabled[ix])
.on_select(cx.listener(move |this, _: &ClickEvent, _, cx| {
this.enabled[ix] = !this.enabled[ix];
cx.notify();
})),
)
});
div().h(px(220.0)).w(px(224.0)).child(menu)
}
}
fn icon(data: &'static [u8], color: Hsla) -> impl IntoElement {
svg().data(data).flex_none().size(px(16.0)).text_color(color)
}Radio Group
radio marks one option of a group with a dot. The view keeps which one is chosen.
use gpui::{div, prelude::*, px, ClickEvent, Context, Window};
use crate::ui::button::{Button, ButtonVariant};
use crate::ui::dropdown_menu::{DropdownMenu, MenuItem};
const POSITIONS: [&str; 3] = ["Top", "Bottom", "Right"];
pub struct DropdownMenuRadioGroup {
open: bool,
position: usize,
}
// The panel starts at the bottom, so `Default` is written out instead of derived.
impl Default for DropdownMenuRadioGroup {
fn default() -> Self {
Self { open: false, position: 1 }
}
}
impl Render for DropdownMenuRadioGroup {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let menu = DropdownMenu::new("dropdown-menu-radio-group", self.open)
.trigger(Button::new("dropdown-menu-radio-group-trigger", "Open").variant(ButtonVariant::Outline))
.on_open_change(cx.listener(|this, open: &bool, _, cx| {
this.open = *open;
cx.notify();
}))
.label("Panel position")
.separator();
let menu = POSITIONS.iter().enumerate().fold(menu, |menu, (ix, name)| {
menu.item(
MenuItem::new(*name)
.radio(self.position == ix)
.on_select(cx.listener(move |this, _: &ClickEvent, _, cx| {
this.position = ix;
cx.notify();
})),
)
});
div().h(px(220.0)).w(px(224.0)).child(menu)
}
}Radio Icons
Radio items take an icon too, here one per payment method.
use gpui::{div, prelude::*, px, svg, ClickEvent, Context, Hsla, Window};
use crate::theme::ActiveTheme;
use crate::ui::button::{Button, ButtonVariant};
use crate::ui::dropdown_menu::{DropdownMenu, MenuItem};
use crate::icons::{CREDIT_CARD, LANDMARK, WALLET};
const METHODS: [(&str, &[u8]); 3] =
[("Credit card", CREDIT_CARD), ("Wallet", WALLET), ("Bank transfer", LANDMARK)];
#[derive(Default)]
pub struct DropdownMenuRadioIcons {
open: bool,
method: usize,
}
impl Render for DropdownMenuRadioIcons {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let fg = cx.theme().foreground;
let menu = DropdownMenu::new("dropdown-menu-radio-icons", self.open)
.trigger(
Button::new("dropdown-menu-radio-icons-trigger", "Payment method")
.variant(ButtonVariant::Outline),
)
.on_open_change(cx.listener(|this, open: &bool, _, cx| {
this.open = *open;
cx.notify();
}))
.label("Pay with")
.separator();
let menu = METHODS.iter().enumerate().fold(menu, |menu, (ix, &(name, data))| {
menu.item(
MenuItem::new(name)
.icon(icon(data, fg))
.radio(self.method == ix)
.on_select(cx.listener(move |this, _: &ClickEvent, _, cx| {
this.method = ix;
cx.notify();
})),
)
});
div().h(px(220.0)).w(px(224.0)).child(menu)
}
}
fn icon(data: &'static [u8], color: Hsla) -> impl IntoElement {
svg().data(data).flex_none().size(px(16.0)).text_color(color)
}Destructive
destructive(true) colors an irreversible action red, apart from the safe ones above it.
use gpui::{div, prelude::*, px, svg, Context, Hsla, Window};
use crate::theme::ActiveTheme;
use crate::ui::button::{Button, ButtonVariant};
use crate::ui::dropdown_menu::{DropdownMenu, MenuItem};
use crate::icons::{PENCIL, SHARE, TRASH_2};
#[derive(Default)]
pub struct DropdownMenuDestructive {
open: bool,
}
impl Render for DropdownMenuDestructive {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let (fg, destructive) = (cx.theme().foreground, cx.theme().destructive);
div().h(px(200.0)).w(px(224.0)).child(
DropdownMenu::new("dropdown-menu-destructive", self.open)
.trigger(Button::new("dropdown-menu-destructive-trigger", "Actions").variant(ButtonVariant::Outline))
.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)))
.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)
}Avatar
Any element can be the trigger. Here an avatar opens the signed-in user's account menu.
use gpui::{div, prelude::*, px, Context, Window};
use crate::ui::avatar::Avatar;
use crate::ui::dropdown_menu::{DropdownMenu, MenuItem};
#[derive(Default)]
pub struct DropdownMenuAvatar {
open: bool,
}
impl Render for DropdownMenuAvatar {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
div().h(px(290.0)).w(px(224.0)).child(
DropdownMenu::new("dropdown-menu-avatar", self.open)
.trigger(div().rounded_full().cursor_pointer().child(Avatar::new("LR")))
.on_open_change(cx.listener(|this, open: &bool, _, cx| {
this.open = *open;
cx.notify();
}))
.label("lee@example.com")
.separator()
.item(MenuItem::new("Account"))
.item(MenuItem::new("Billing"))
.item(MenuItem::new("Notifications"))
.separator()
.item(MenuItem::new("Switch account"))
.item(MenuItem::new("Sign out")),
)
}
}Complex
Groups, icons, shortcuts, checkbox items and a submenu together in one menu.
use gpui::{div, prelude::*, px, svg, ClickEvent, Context, Hsla, Window};
use crate::theme::ActiveTheme;
use crate::ui::button::{Button, ButtonVariant};
use crate::ui::dropdown_menu::{DropdownMenu, MenuItem, Submenu};
use crate::icons::{CREDIT_CARD, LOG_OUT, MAIL, MESSAGE_SQUARE, PLUS, USER, USERS, USER_PLUS};
#[derive(Default)]
pub struct DropdownMenuComplex {
open: bool,
show_status: bool,
}
impl Render for DropdownMenuComplex {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let (fg, destructive) = (cx.theme().foreground, cx.theme().destructive);
// Sized so the menu opens downward and its submenu fits beside it in the preview.
div().h(px(440.0)).w(px(480.0)).child(
DropdownMenu::new("dropdown-menu-complex", self.open)
.trigger(Button::new("dropdown-menu-complex-trigger", "Complex menu").variant(ButtonVariant::Outline))
.on_open_change(cx.listener(|this, open: &bool, _, cx| {
this.open = *open;
cx.notify();
}))
.label("My account")
.item(MenuItem::new("Profile").icon(icon(USER, fg)).shortcut("Shift+Ctrl+P"))
.item(MenuItem::new("Billing").icon(icon(CREDIT_CARD, fg)).shortcut("Ctrl+B"))
.item(
MenuItem::new("Show status")
.checked(self.show_status)
.on_select(cx.listener(|this, _: &ClickEvent, _, cx| {
this.show_status = !this.show_status;
cx.notify();
})),
)
.separator()
.label("Team")
.item(MenuItem::new("Members").icon(icon(USERS, fg)))
.submenu(
Submenu::new("Invite users")
.icon(icon(USER_PLUS, fg))
.item(MenuItem::new("Email").icon(icon(MAIL, fg)))
.item(MenuItem::new("Message").icon(icon(MESSAGE_SQUARE, fg)))
.separator()
.item(MenuItem::new("More...").icon(icon(PLUS, fg))),
)
.item(MenuItem::new("New team").icon(icon(PLUS, fg)).shortcut("Ctrl+T"))
.separator()
.item(MenuItem::new("Log out").icon(icon(LOG_OUT, destructive)).destructive(true)),
)
}
}
fn icon(data: &'static [u8], color: Hsla) -> impl IntoElement {
svg().data(data).flex_none().size(px(16.0)).text_color(color)
}API Reference
MenuItem
One clickable row. Selecting it runs on_select and closes the menu.
MenuItem::new(label: impl Into<SharedString>) -> Self.shortcut(shortcut: impl Into<SharedString>)Right-aligned hint such as "Ctrl+S". Display only: bind the keys in your app.
.icon(icon: impl IntoElement)An icon before the label. Size it to 16px and give it a color: GPUI doesn't pass the text color down to SVGs.
.checked(checked: bool)Makes this a checkbox item that shows a check mark while checked. Flip your value in on_select. The menu stays open so several options can be toggled.
.radio(selected: bool)Makes this a radio item that shows a check while selected. Give each option in a group its own item and set your value in on_select. The menu stays open, as with checkbox items.
.close_on_select(close: bool)Whether selecting the item closes the menu. Defaults to true, or false for checked and radio items.
.disabled(disabled: bool).destructive(destructive: bool)Red text, for actions like "Delete".
.on_select(handler: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static)Submenu
A row that opens a nested menu to its right on hover. Build its rows the same way as the menu's own.
Submenu::new(label: impl Into<SharedString>) -> Self.icon(icon: impl IntoElement)An icon before the label, as with [MenuItem::icon].
.item(item: MenuItem).label(label: impl Into<SharedString>)A non-interactive heading.
.separator().submenu(submenu: Submenu)A further nested menu.
MenuEntry
The rows of a menu. Context menu renders the same list.
MenuEntry::ItemMenuEntry::LabelMenuEntry::SeparatorMenuEntry::SubmenuSubmenuTracker
Which submenu of one menu level is open, and where its panel was painted. A submenu panel hangs outside its menu's bounds, so the menu checks [SubmenuTracker::contains] before treating a click as outside. Keep one per open menu across frames.
.contains(position: Point<Pixels>) -> boolWhether position is over an open submenu panel at any depth.
.reset()Closes every submenu, e.g. when the menu itself closes.
.track_menu_open(open: bool)Closes every submenu when the menu opens again, so one left open when it closed fades out with the menu instead of vanishing first.
DropdownMenu
A menu that opens from a trigger. The parent view owns open.
DropdownMenu::new(id: impl Into<ElementId>, open: bool) -> Self.trigger(trigger: impl IntoElement)The element that toggles the menu when clicked.
.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.
.align(align: Align).side(side: Side)Which side of the trigger the menu opens on. Below it by default.
.full_width(full_width: bool)Stretches the trigger to the menu's full width, such as a switcher filling a sidebar row.
.width(width: impl Into<gpui::Pixels>).on_open_change(handler: impl Fn(&bool, &mut Window, &mut App) + 'static)Receives the *next* open value.