Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.
use gpui::{Anchor, AnyView, Axis, Entity, Pixels, Point, Role};
use crate::{ButtonLike, ContextMenu, PopoverMenu, prelude::*};
use super::PopoverMenuHandle;
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
pub enum DropdownStyle {
#[default]
Solid,
Outlined,
Subtle,
Ghost,
}
enum LabelKind {
Text(SharedString),
Element(AnyElement),
}
#[derive(IntoElement, RegisterComponent)]
pub struct DropdownMenu {
id: ElementId,
label: LabelKind,
trigger_size: ButtonSize,
trigger_tooltip: Option<Box<dyn Fn(&mut Window, &mut App) -> AnyView + 'static>>,
trigger_icon: Option<IconName>,
style: DropdownStyle,
menu: Entity<ContextMenu>,
full_width: bool,
disabled: bool,
handle: Option<PopoverMenuHandle<ContextMenu>>,
attach: Option<Anchor>,
offset: Option<Point<Pixels>>,
tab_index: Option<isize>,
chevron: bool,
aria_label: Option<SharedString>,
aria_description: Option<SharedString>,
aria_value: Option<SharedString>,
}
impl DropdownMenu {
pub fn new(
id: impl Into<ElementId>,
label: impl Into<SharedString>,
menu: Entity<ContextMenu>,
) -> Self {
Self {
id: id.into(),
label: LabelKind::Text(label.into()),
trigger_size: ButtonSize::Default,
trigger_tooltip: None,
trigger_icon: Some(IconName::ChevronUpDown),
style: DropdownStyle::default(),
menu,
full_width: false,
disabled: false,
handle: None,
attach: None,
offset: None,
tab_index: None,
chevron: true,
aria_label: None,
aria_description: None,
aria_value: None,
}
}
pub fn new_with_element(
id: impl Into<ElementId>,
label: AnyElement,
menu: Entity<ContextMenu>,
) -> Self {
Self {
id: id.into(),
label: LabelKind::Element(label),
trigger_size: ButtonSize::Default,
trigger_tooltip: None,
trigger_icon: Some(IconName::ChevronUpDown),
style: DropdownStyle::default(),
menu,
full_width: false,
disabled: false,
handle: None,
attach: None,
offset: None,
tab_index: None,
chevron: true,
aria_label: None,
aria_description: None,
aria_value: None,
}
}
pub fn style(mut self, style: DropdownStyle) -> Self {
self.style = style;
self
}
pub fn trigger_size(mut self, size: ButtonSize) -> Self {
self.trigger_size = size;
self
}
pub fn trigger_tooltip(
mut self,
tooltip: impl Fn(&mut Window, &mut App) -> AnyView + 'static,
) -> Self {
self.trigger_tooltip = Some(Box::new(tooltip));
self
}
pub fn trigger_icon(mut self, icon: IconName) -> Self {
self.trigger_icon = Some(icon);
self
}
pub fn full_width(mut self, full_width: bool) -> Self {
self.full_width = full_width;
self
}
pub fn handle(mut self, handle: PopoverMenuHandle<ContextMenu>) -> Self {
self.handle = Some(handle);
self
}
/// Defines which corner of the trigger the menu lines up with. The default,
/// [`Anchor::BottomLeft`], opens the menu below the trigger with their left edges lined
/// up. Use [`Anchor::BottomRight`] to line up the right edges instead, for a trigger at
/// the right end of a row.
pub fn attach(mut self, attach: Anchor) -> Self {
self.attach = Some(attach);
self
}
/// Offsets the position of the menu by that many pixels.
pub fn offset(mut self, offset: Point<Pixels>) -> Self {
self.offset = Some(offset);
self
}
pub fn tab_index(mut self, arg: isize) -> Self {
self.tab_index = Some(arg);
self
}
pub fn no_chevron(mut self) -> Self {
self.chevron = false;
self
}
/// Sets the label announced by assistive technology.
/// Defaults to the trigger's visible label (typically the current value).
pub fn aria_label(mut self, label: impl Into<SharedString>) -> Self {
self.aria_label = Some(label.into());
self
}
/// Sets the supplementary description announced by assistive technology
/// after the combobox's name, role, and value.
pub fn aria_description(mut self, description: impl Into<SharedString>) -> Self {
self.aria_description = Some(description.into());
self
}
/// Sets the current value announced by assistive technology (the selected
/// option). Defaults to the trigger's visible text label.
pub fn aria_value(mut self, value: impl Into<SharedString>) -> Self {
self.aria_value = Some(value.into());
self
}
}
impl Disableable for DropdownMenu {
fn disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled;
self
}
}
impl RenderOnce for DropdownMenu {
fn render(self, _window: &mut Window, _cx: &mut App) -> impl IntoElement {
let button_style = match self.style {
DropdownStyle::Solid => ButtonStyle::Filled,
DropdownStyle::Subtle => ButtonStyle::Subtle,
DropdownStyle::Outlined => ButtonStyle::Outlined,
DropdownStyle::Ghost => ButtonStyle::Transparent,
};
let full_width = self.full_width;
let trigger_size = self.trigger_size;
// Ensure a handle exists so assistive technology can open/close the menu
// via the Expand/Collapse accessibility actions (used by UIA on Windows
// and AX on macOS; on Linux/AT-SPI the click action is used instead).
let handle = self.handle.unwrap_or_default();
let expanded = handle.is_deployed();
// A combobox should announce its current value (the selected option).
// Default to the trigger's visible text label when no explicit value
// is provided.
let aria_value = self.aria_value.clone().or_else(|| match &self.label {
LabelKind::Text(text) => Some(text.clone()),
LabelKind::Element(_) => None,
});
let aria_description = self.aria_description.clone();
let a11y_actions = |button: Button| {
let show_handle = handle.clone();
let hide_handle = handle.clone();
button
.on_a11y_action(gpui::accesskit::Action::Expand, move |_, window, cx| {
show_handle.show(window, cx);
})
.on_a11y_action(gpui::accesskit::Action::Collapse, move |_, _window, cx| {
hide_handle.hide(cx);
})
};
let a11y_actions_element = |button: ButtonLike| {
let show_handle = handle.clone();
let hide_handle = handle.clone();
button
.on_a11y_action(gpui::accesskit::Action::Expand, move |_, window, cx| {
show_handle.show(window, cx);
})
.on_a11y_action(gpui::accesskit::Action::Collapse, move |_, _window, cx| {
hide_handle.hide(cx);
})
};
let (text_button, element_button) = match self.label {
LabelKind::Text(text) => (
Some(
a11y_actions(Button::new(self.id.clone(), text))
.aria_role(Role::ComboBox)
.when_some(self.aria_label, |this, label| this.aria_label(label))
.when_some(aria_description, |this, description| {
this.aria_description(description)
})
.when_some(aria_value, |this, value| this.aria_value(value))
.aria_expanded(expanded)
.style(button_style)
.when_some(self.trigger_icon.filter(|_| self.chevron), |this, icon| {
this.end_icon(
Icon::new(icon).size(IconSize::XSmall).color(Color::Muted),
)
})
.when(full_width, |this| this.full_width())
.size(trigger_size)
.disabled(self.disabled)
.when_some(self.tab_index, |this, tab_index| this.tab_index(tab_index)),
),
None,
),
LabelKind::Element(element) => (
None,
Some(
a11y_actions_element(ButtonLike::new(self.id.clone()))
.aria_role(Role::ComboBox)
.when_some(self.aria_label, |this, label| this.aria_label(label))
.when_some(aria_description, |this, description| {
this.aria_description(description)
})
.when_some(aria_value, |this, value| this.aria_value(value))
.aria_expanded(expanded)
.child(element)
.style(button_style)
.when(self.chevron, |this| {
this.child(
Icon::new(IconName::ChevronUpDown)
.size(IconSize::XSmall)
.color(Color::Muted),
)
})
.when(full_width, |this| this.full_width())
.size(trigger_size)
.disabled(self.disabled)
.when_some(self.tab_index, |this, tab_index| this.tab_index(tab_index)),
),
),
};
// When the menu opens, move the selection to the current value (or the
// first item) so assistive technology announces a meaningful item
// immediately, instead of focusing the bare menu container and
// announcing only "menu". See the ARIA menu button pattern.
let menu_for_open = self.menu.clone();
let mut popover = PopoverMenu::new((self.id.clone(), "popover"))
.full_width(self.full_width)
.with_handle(handle)
.on_open(std::rc::Rc::new(move |window, cx| {
menu_for_open.update(cx, |menu, cx| {
menu.select_toggled_or_first(window, cx);
});
}))
.menu(move |_window, _cx| Some(self.menu.clone()));
popover = match (text_button, element_button, self.trigger_tooltip) {
(Some(text_button), None, Some(tooltip)) => {
popover.trigger_with_tooltip(text_button, tooltip)
}
(Some(text_button), None, None) => popover.trigger(text_button),
(None, Some(element_button), Some(tooltip)) => {
popover.trigger_with_tooltip(element_button, tooltip)
}
(None, Some(element_button), None) => popover.trigger(element_button),
_ => popover,
};
let attach = self.attach.unwrap_or(Anchor::BottomLeft);
popover
.attach(attach)
.anchor(attach.other_side_along(Axis::Vertical))
.when_some(self.offset, |this, offset| this.offset(offset))
}
}
impl Component for DropdownMenu {
fn scope() -> ComponentScope {
ComponentScope::Input
}
fn name() -> &'static str {
"DropdownMenu"
}
fn description() -> &'static str {
"A dropdown menu displays a list of actions or options. \
A dropdown menu is always activated by clicking a trigger (or via a keybinding)."
}
fn preview(window: &mut Window, cx: &mut App) -> AnyElement {
let menu = ContextMenu::build(window, cx, |this, _, _| {
this.entry("Option 1", None, |_, _| {})
.entry("Option 2", None, |_, _| {})
.entry("Option 3", None, |_, _| {})
.separator()
.entry("Option 4", None, |_, _| {})
});
let menu_with_submenu = ContextMenu::build(window, cx, |this, _, _| {
this.entry("Toggle All Docks", None, |_, _| {})
.submenu("Editor Layout", |menu, _, _| {
menu.entry("Split Up", None, |_, _| {})
.entry("Split Down", None, |_, _| {})
.separator()
.entry("Split Side", None, |_, _| {})
})
.separator()
.entry("Project Panel", None, |_, _| {})
.entry("Outline Panel", None, |_, _| {})
.separator()
.submenu("Autofill", |menu, _, _| {
menu.entry("Contact…", None, |_, _| {})
.entry("Passwords…", None, |_, _| {})
})
.submenu_with_icon("Predict", IconName::ZedPredict, |menu, _, _| {
menu.entry("Everywhere", None, |_, _| {})
.entry("At Cursor", None, |_, _| {})
.entry("Over Here", None, |_, _| {})
.entry("Over There", None, |_, _| {})
})
});
v_flex()
.gap_6()
.children(vec![
example_group_with_title(
"Basic Usage",
vec![
single_example(
"Default",
DropdownMenu::new("default", "Select an option", menu.clone())
.into_any_element(),
),
single_example(
"Full Width",
DropdownMenu::new("full-width", "Full Width Dropdown", menu.clone())
.full_width(true)
.into_any_element(),
),
],
),
example_group_with_title(
"Submenus",
vec![single_example(
"With Submenus",
DropdownMenu::new("submenu", "Submenu", menu_with_submenu)
.into_any_element(),
)],
),
example_group_with_title(
"Styles",
vec![
single_example(
"Outlined",
DropdownMenu::new("outlined", "Outlined Dropdown", menu.clone())
.style(DropdownStyle::Outlined)
.into_any_element(),
),
single_example(
"Ghost",
DropdownMenu::new("ghost", "Ghost Dropdown", menu.clone())
.style(DropdownStyle::Ghost)
.into_any_element(),
),
],
),
example_group_with_title(
"States",
vec![single_example(
"Disabled",
DropdownMenu::new("disabled", "Disabled Dropdown", menu)
.disabled(true)
.into_any_element(),
)],
),
])
.into_any_element()
}
}
#[cfg(test)]
mod tests {
use gpui::{Bounds, TestAppContext, VisualTestContext, size};
use super::*;
struct DropdownTestView {
handle: PopoverMenuHandle<ContextMenu>,
menu: Entity<ContextMenu>,
attach: Option<Anchor>,
at_right_edge: bool,
}
impl Render for DropdownTestView {
fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
let trigger = div()
.absolute()
.top(px(40.))
.map(|this| {
if self.at_right_edge {
this.right(px(40.))
} else {
this.left(px(40.))
}
})
.debug_selector(|| "TRIGGER".into())
.child(
DropdownMenu::new("dropdown", "Pick", self.menu.clone())
.handle(self.handle.clone())
.when_some(self.attach, |this, attach| this.attach(attach)),
);
div().size_full().child(trigger)
}
}
fn open_dropdown(
attach: Option<Anchor>,
at_right_edge: bool,
cx: &mut TestAppContext,
) -> (Bounds<Pixels>, Bounds<Pixels>) {
cx.update(|cx| {
let settings_store = settings::SettingsStore::test(cx);
cx.set_global(settings_store);
theme_settings::init(theme::LoadThemes::JustBase, cx);
});
let handle = PopoverMenuHandle::default();
let window = cx.open_window(size(px(800.), px(600.)), |window, cx| {
let menu = ContextMenu::build(window, cx, |menu, _, _| {
menu.custom_row(|_, _| {
div()
.debug_selector(|| "MENU_ROW".into())
.w(px(300.))
.h(px(20.))
.into_any_element()
})
});
DropdownTestView {
handle: handle.clone(),
menu,
attach,
at_right_edge,
}
});
cx.run_until_parked();
let mut cx = VisualTestContext::from_window(window.into(), cx);
cx.update(|window, cx| window.draw(cx).clear(cx));
cx.update(|window, cx| handle.show(window, cx));
for _ in 0..3 {
cx.update(|window, cx| window.draw(cx).clear(cx));
}
let trigger = cx.debug_bounds("TRIGGER").expect("trigger bounds");
let menu_row = cx.debug_bounds("MENU_ROW").expect("menu row bounds");
(trigger, menu_row)
}
#[gpui::test]
fn dropdown_lines_up_with_its_attached_edge(cx: &mut TestAppContext) {
for (attach, at_right_edge) in [(None, false), (Some(Anchor::BottomRight), true)] {
let (trigger, menu_row) = open_dropdown(attach, at_right_edge, cx);
let (menu_edge, trigger_edge) = if at_right_edge {
(menu_row.right(), trigger.right())
} else {
(menu_row.left(), trigger.left())
};
assert!(
menu_row.top() >= trigger.bottom(),
"attach: {attach:?}, trigger: {trigger:?}, menu row: {menu_row:?}"
);
assert!(
(menu_edge - trigger_edge).abs() < px(12.),
"attach: {attach:?}, trigger: {trigger:?}, menu row: {menu_row:?}"
);
}
}
}