feat: add dropdown menu component

This commit is contained in:
2026-11-08 17:03:38 +07:00
parent 11b29dc91a
commit d8663593b6
10 changed files with 1244 additions and 197 deletions
+450
View File
@@ -0,0 +1,450 @@
//! The dropdown menu: a push button with an attached menu of actions.
use std::cell::RefCell;
use std::rc::Rc;
use gpui::prelude::FluentBuilder as _;
use gpui::{
App, ClickEvent, DispatchPhase, ElementId, InteractiveElement as _, IntoElement, KeyDownEvent,
MouseButton, MouseDownEvent, ParentElement as _, RenderOnce, Role, SharedString,
StatefulInteractiveElement as _, Styled as _, Window, canvas, div, hsla, relative,
};
use gpui_native_icons::{IconRole, icon};
use gpui_native_theme::{ActiveTheme as _, BORDER_WIDTH, Size};
use gpui_native_utils::{focus_handle, focus_ring};
use crate::button::ButtonVariant;
use crate::common::{Sizable, h_flex};
use crate::menu::{ChangeHandler, MenuChrome, MenuItem, TriggerBoundsCell, anchored_menu_panel};
use crate::spinner::Spinner;
/// The main zone's activation handler, shared by pointer, Enter, and Space.
type ClickHandler = Box<dyn Fn(&ClickEvent, &mut Window, &mut App)>;
type ItemsFn = Box<dyn Fn(&mut Window, &mut App) -> Vec<MenuItem>>;
/// A push button with an attached dropdown menu.
#[derive(IntoElement)]
pub struct DropdownMenu {
id: ElementId,
label: Option<SharedString>,
icon: Option<IconRole>,
variant: ButtonVariant,
size: Size,
disabled: bool,
loading: bool,
tab_stop: bool,
open: bool,
a11y_label: Option<SharedString>,
on_click: Option<ClickHandler>,
on_open_change: Option<ChangeHandler>,
items: Option<ItemsFn>,
}
impl DropdownMenu {
/// Creates a closed dropdown menu rendered as a primary button.
pub fn new<I>(id: I) -> Self
where
I: Into<ElementId>,
{
Self {
id: id.into(),
label: None,
icon: None,
variant: ButtonVariant::default(),
size: Size::default(),
disabled: false,
loading: false,
tab_stop: true,
open: false,
a11y_label: None,
on_click: None,
on_open_change: None,
items: None,
}
}
/// Sets the visible label.
pub fn label<L>(mut self, label: L) -> Self
where
L: Into<SharedString>,
{
self.label = Some(label.into());
self
}
/// Shows an icon beside the label.
pub fn icon(mut self, role: IconRole) -> Self {
self.icon = Some(role);
self
}
/// Sets the button's visual language.
pub fn variant(mut self, variant: ButtonVariant) -> Self {
self.variant = variant;
self
}
/// Whether the trigger is a keyboard tab stop, dense toolbars turn it off.
pub fn tab_stop(mut self, tab_stop: bool) -> Self {
self.tab_stop = tab_stop;
self
}
/// Renders the trigger inert, unfocusable, and dimmed.
pub fn disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled;
self
}
/// Shows the spinner in place of the icon and suppresses activation.
pub fn loading(mut self, loading: bool) -> Self {
self.loading = loading;
self
}
/// Sets the current open state.
pub fn open(mut self, open: bool) -> Self {
self.open = open;
self
}
/// Overrides the accessibility label, which defaults to the visible label.
pub fn accessibility_label<L>(mut self, label: L) -> Self
where
L: Into<SharedString>,
{
self.a11y_label = Some(label.into());
self
}
/// The main zone's action. Without one, activating the button opens the menu.
pub fn on_click<F>(mut self, handler: F) -> Self
where
F: Fn(&ClickEvent, &mut Window, &mut App) + 'static,
{
self.on_click = Some(Box::new(handler));
self
}
/// Reports the menu's next open state.
pub fn on_open_change<F>(mut self, handler: F) -> Self
where
F: Fn(bool, &mut Window, &mut App) + 'static,
{
self.on_open_change = Some(Rc::new(handler));
self
}
/// Sets the menu's items, built fresh each render.
pub fn items<F>(mut self, items: F) -> Self
where
F: Fn(&mut Window, &mut App) -> Vec<MenuItem> + 'static,
{
self.items = Some(Box::new(items));
self
}
}
impl Sizable for DropdownMenu {
fn apply_size(&mut self, size: Size) {
self.size = size;
}
}
impl RenderOnce for DropdownMenu {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let theme = cx.theme();
let colors = theme.colors;
let ramps = theme.ramps;
let metrics = theme.sizes.resolve(self.size);
let radius = theme.radius.control;
let ring = colors.ring;
let show_border = theme.borders.buttons && self.variant != ButtonVariant::Ghost;
let (panel_chrome, enter_duration) = MenuChrome::read(cx);
let (background, foreground, hover, pressed) = match self.variant {
ButtonVariant::Primary => (
Some(ramps.primary.base),
colors.primary_foreground,
ramps.primary.hover,
ramps.primary.pressed,
),
ButtonVariant::Secondary => (
Some(colors.secondary),
colors.secondary_foreground,
ramps.secondary.hover,
ramps.secondary.pressed,
),
ButtonVariant::Ghost => (
None,
colors.foreground,
colors.muted_hover,
ramps.secondary.pressed,
),
ButtonVariant::Destructive => (
Some(ramps.destructive.base),
colors.destructive_foreground,
ramps.destructive.hover,
ramps.destructive.pressed,
),
};
let border = if show_border {
colors.border
} else {
background.unwrap_or_else(|| hsla(0.0, 0.0, 0.0, 0.0))
};
let split = self.on_click.is_some();
let inert = self.disabled || self.loading;
let label = self
.a11y_label
.clone()
.unwrap_or_else(|| SharedString::from(self.id.to_string()));
let a11y_label = self.a11y_label.or_else(|| self.label.clone());
let focus = focus_handle(&self.id, window, cx).tab_stop(self.tab_stop);
// How the menu was last opened, read by the frame that mounts the panel.
let keyboard_open = window.use_keyed_state("dropdown-open-origin", cx, |_, _| false);
let on_open: ChangeHandler = {
let focus = focus.clone();
let on_open_change = self.on_open_change.clone();
let keyboard_open = keyboard_open.clone();
Rc::new(move |next, window, cx| {
if !next {
window.focus(&focus, cx);
keyboard_open.update(cx, |keyboard_open, _| *keyboard_open = false);
}
if let Some(on_open_change) = &on_open_change {
on_open_change(next, window, cx);
}
})
};
let trigger_bounds: TriggerBoundsCell = Rc::new(RefCell::new(None));
let chevron_bounds: TriggerBoundsCell = Rc::new(RefCell::new(None));
let main = h_flex()
.id(self.id.clone())
.debug_selector({
let id = self.id.clone();
move || id.to_string()
})
.justify_center()
.h_full()
.gap_2()
.line_height(relative(1.0))
.text_size(metrics.text_size)
.text_color(foreground)
.role(Role::Button)
.when_some(a11y_label, |zone, label| zone.aria_label(label))
.aria_expanded(self.open)
.px(if split && self.icon.is_none() {
metrics.padding_x
} else {
metrics.dense_padding_x
})
.when(split, |zone| zone.rounded_l(radius))
.when(!split, |zone| {
zone.rounded(radius)
.when(self.open, |zone| zone.bg(pressed))
.child(
icon(IconRole::ChevronDown)
.size(metrics.dense_icon_size)
.color(foreground),
)
})
.when(self.loading, |zone| {
zone.child(
Spinner::new((self.id.clone(), "spinner"))
.with_size(self.size)
.variant(crate::spinner::SpinnerVariant::Icon)
.color(foreground),
)
})
.when(!self.loading, |zone| {
zone.when_some(self.icon, |zone, role| {
zone.child(icon(role).size(metrics.icon_size).color(foreground))
})
})
.when_some(self.label, |zone, label| zone.child(label));
let main = if inert {
main
} else {
main.track_focus(&focus)
.cursor_pointer()
.hover(move |style| style.bg(hover))
.active(move |style| style.bg(pressed))
.on_click({
let on_click = self.on_click;
let on_open = on_open.clone();
let keyboard_open = keyboard_open.clone();
let open = self.open;
move |event, window, cx| match (on_click.as_ref(), event) {
(Some(on_click), _) => on_click(event, window, cx),
(None, ClickEvent::Keyboard(_)) => {
keyboard_open.update(cx, |keyboard_open, _| *keyboard_open = true);
on_open(!open, window, cx);
}
(None, _) => {}
}
})
.on_key_down({
let on_open = on_open.clone();
let keyboard_open = keyboard_open.clone();
move |event: &KeyDownEvent, window, cx| {
if event.keystroke.key == "down" {
keyboard_open.update(cx, |keyboard_open, _| *keyboard_open = true);
on_open(true, window, cx);
cx.stop_propagation();
}
}
})
};
let chevron_zone = h_flex()
.id((self.id.clone(), "chevron"))
.debug_selector({
let id = self.id.clone();
move || format!("{id}-chevron")
})
.relative()
.h_full()
.px(metrics.dense_padding_x)
.rounded_r(radius)
.rounded_l_none()
.border_l_1()
.border_color(border)
.when(self.open, |zone| zone.bg(pressed))
.when(!inert, |zone| {
zone.cursor_pointer()
.hover(move |style| style.bg(hover))
.active(move |style| style.bg(pressed))
})
.child(
icon(IconRole::ChevronDown)
.size(metrics.dense_icon_size)
.color(foreground),
)
.child(
canvas(
{
let cell = chevron_bounds.clone();
move |bounds, _window, _cx| *cell.borrow_mut() = Some(bounds)
},
|_, _, _, _| {},
)
.absolute()
.inset_0(),
);
let trigger = h_flex()
.h(metrics.control_height + BORDER_WIDTH * 2.0)
.rounded(radius)
.border_1()
.border_color(border)
.when_some(background, |trigger, background| trigger.bg(background))
.when(self.disabled, |trigger| trigger.opacity(0.5))
.when(!inert, |trigger| {
trigger
.track_focus(&focus)
.focus_visible(move |style| style.shadow(focus_ring(ring)))
})
.child(main);
let trigger = if split {
trigger.child(chevron_zone)
} else {
trigger
};
let mut wrapper = div()
.relative()
.child(
canvas(
{
let cell = trigger_bounds.clone();
move |bounds, _window, _cx| *cell.borrow_mut() = Some(bounds)
},
{
let on_open = on_open.clone();
let trigger_bounds = trigger_bounds.clone();
let chevron_bounds = chevron_bounds.clone();
let keyboard_open = keyboard_open.clone();
let open = self.open;
move |_, _, window, _cx| {
window.on_mouse_event({
let on_open = on_open.clone();
let keyboard_open = keyboard_open.clone();
move |event: &MouseDownEvent, phase, window, cx| {
if phase != DispatchPhase::Bubble
|| event.button != MouseButton::Left
|| inert
{
return;
}
let in_trigger = trigger_bounds
.borrow()
.is_some_and(|bounds| bounds.contains(&event.position));
if !in_trigger {
return;
}
let in_chevron = chevron_bounds
.borrow()
.is_some_and(|bounds| bounds.contains(&event.position));
if !open && split && !in_chevron {
return;
}
keyboard_open
.update(cx, |keyboard_open, _| *keyboard_open = false);
on_open(!open, window, cx);
cx.stop_propagation();
}
});
}
},
)
.absolute()
.inset_0(),
)
.child(trigger);
let items = if self.open {
self.items
.map(|build| build(window, cx))
.unwrap_or_default()
} else {
Vec::new()
};
if let Some(panel) = anchored_menu_panel(
window,
cx,
&self.id,
self.open,
items,
None,
*keyboard_open.read(cx),
Some(on_open),
label,
None,
&trigger_bounds,
&panel_chrome,
enter_duration,
) {
wrapper = wrapper.child(panel);
}
wrapper
}
}
+3
View File
@@ -57,6 +57,9 @@ pub mod empty_state;
#[cfg(feature = "menu")]
pub mod menu;
#[cfg(feature = "dropdown_menu")]
pub mod dropdown_menu;
#[cfg(feature = "alert")]
pub mod alert;
+228 -175
View File
@@ -18,8 +18,10 @@ use crate::scroll_area::{ScrollArea, ScrollAxes};
/// Runs the item's action. The menu closes itself before the handler runs.
pub type ItemHandler = Rc<dyn Fn(&mut Window, &mut App)>;
/// Reports the next open state of a [`Menu`]: `true` to open, `false` to close.
type ChangeHandler = Rc<dyn Fn(bool, &mut Window, &mut App)>;
/// Reports the next open state of a menu: `true` to open, `false` to close.
pub(crate) type ChangeHandler = Rc<dyn Fn(bool, &mut Window, &mut App)>;
/// Bounds captured during the last paint, shared with the dismissal listener.
pub(crate) type TriggerBoundsCell = Rc<RefCell<Option<Bounds<Pixels>>>>;
type TriggerFn = Box<dyn Fn(&mut Window, &mut App) -> AnyElement>;
type ItemsFn = Box<dyn Fn(&mut Window, &mut App) -> Vec<MenuItem>>;
@@ -124,12 +126,13 @@ impl MenuItem {
/// Menu chrome styles.
#[derive(Clone)]
struct MenuChrome {
pub(crate) struct MenuChrome {
surface: gpui::Hsla,
border: gpui::Hsla,
panel_border: gpui::Hsla,
foreground: gpui::Hsla,
muted_foreground: gpui::Hsla,
muted_hover: gpui::Hsla,
primary: gpui::Hsla,
primary_foreground: gpui::Hsla,
destructive: gpui::Hsla,
@@ -158,6 +161,40 @@ pub struct Menu {
items: Option<ItemsFn>,
}
impl MenuChrome {
/// Reads the menu's chrome and enter duration from the active theme.
pub(crate) fn read(cx: &App) -> (Self, std::time::Duration) {
let theme = cx.theme();
(
Self {
surface: theme.colors.surface,
border: theme.colors.border,
panel_border: if theme.borders.overlays {
theme.colors.border
} else {
theme.colors.surface
},
foreground: theme.colors.foreground,
muted_foreground: theme.colors.muted_foreground,
muted_hover: theme.colors.muted_hover,
primary: theme.ramps.primary.base,
primary_foreground: theme.colors.primary_foreground,
destructive: theme.ramps.destructive.base,
destructive_foreground: theme.colors.destructive_foreground,
radius_overlay: theme.radius.overlay,
radius_sm: theme.radius.sm,
icon_size: theme.sizes.medium.icon_size,
dense_icon_size: theme.sizes.medium.dense_icon_size,
menu_item_height: theme.sizes.medium.menu_item_height,
spacing_unit: theme.spacing.unit,
text_size: theme.sizes.medium.text_size,
shadow: theme.elevations.popover.shadows(),
},
theme.motion.overlay,
)
}
}
impl Menu {
/// Creates a closed menu.
pub fn new<I>(id: I) -> Self
@@ -240,41 +277,9 @@ impl Menu {
impl RenderOnce for Menu {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let (chrome, enter_duration) = {
let theme = cx.theme();
(
MenuChrome {
surface: theme.colors.surface,
border: theme.colors.border,
panel_border: if theme.borders.overlays {
theme.colors.border
} else {
theme.colors.surface
},
foreground: theme.colors.foreground,
muted_foreground: theme.colors.muted_foreground,
primary: theme.ramps.primary.base,
primary_foreground: theme.colors.primary_foreground,
destructive: theme.ramps.destructive.base,
destructive_foreground: theme.colors.destructive_foreground,
radius_overlay: theme.radius.overlay,
radius_sm: theme.radius.sm,
icon_size: theme.sizes.medium.icon_size,
dense_icon_size: theme.sizes.medium.dense_icon_size,
menu_item_height: theme.sizes.medium.menu_item_height,
spacing_unit: theme.spacing.unit,
text_size: theme.sizes.medium.text_size,
shadow: theme.elevations.popover.shadows(),
},
theme.motion.overlay,
)
};
let (chrome, enter_duration) = MenuChrome::read(cx);
let trigger_bounds: Rc<RefCell<Option<Bounds<Pixels>>>> = Rc::new(RefCell::new(None));
let selection = window.use_keyed_state("menu-selection", cx, |_, _| 0usize);
let was_open = window.use_keyed_state("menu-was-open", cx, |_, _| self.open);
let fallback_label = self
.a11y_label
.clone()
@@ -293,13 +298,9 @@ impl RenderOnce for Menu {
let open = self.open;
let trigger_button = self.trigger_button;
let cell = trigger_bounds.clone();
let was_open = was_open.clone();
move |_, _, window, cx| {
let trigger_bounds = cell;
if !open {
was_open.update(cx, |was_open, _| *was_open = false);
}
move |_, _, window, _cx| {
let trigger_bounds = cell;
window.on_mouse_event({
let on_change = on_change.clone();
@@ -333,128 +334,179 @@ impl RenderOnce for Menu {
wrapper.child(trigger(window, cx))
});
if self.open {
let on_change = self.on_change.clone();
let label = fallback_label.clone();
let items = match self.items {
let items = if self.open {
match self.items {
Some(build) => build(window, cx),
None => Vec::new(),
};
// Keyboard focus rides the panel across frames.
let focus = gpui_native_utils::focus_handle(&self.id, window, cx);
let scroll = window.use_keyed_state("menu-scroll", cx, |_, _| ScrollHandle::new());
let selected = if *was_open.read(cx) {
*selection.read(cx)
} else if let Some(requested) = self.initial_selection {
requested.min(items.len().saturating_sub(1))
} else {
let first = items.iter().position(|item| item.selectable()).unwrap_or(0);
selection.update(cx, |selection, _| *selection = first);
first
};
was_open.update(cx, |was_open, _| *was_open = true);
let rows: Vec<AnyElement> = items
.iter()
.enumerate()
.map(|(index, item)| {
render_item(
item,
index,
selected == index,
&selection,
&on_change,
&chrome,
)
})
.collect();
let panel = v_flex()
.id("menu-panel")
.debug_selector(|| "menu-panel".to_string())
.occlude()
.track_focus(&focus)
.role(Role::Menu)
.aria_label(label)
.min_w_56()
.p(chrome.spacing_unit)
.bg(chrome.surface)
.text_color(chrome.foreground)
.rounded(chrome.radius_overlay)
.border_1()
.border_color(chrome.panel_border)
.shadow(chrome.shadow.clone())
.overflow_hidden()
.on_mouse_down_out({
let on_change = on_change.clone();
let trigger_bounds = trigger_bounds.clone();
move |event, window, cx| {
if trigger_bounds
.borrow()
.is_some_and(|bounds| bounds.contains(&event.position))
{
return;
}
if let Some(on_change) = &on_change {
on_change(false, window, cx);
}
}
})
.on_key_down({
let items = items.clone();
let on_change = on_change.clone();
let selection = selection.clone();
move |event: &KeyDownEvent, window, cx| {
handle_menu_key(event, &items, &selection, &on_change, window, cx);
}
})
.child(
ScrollArea::new("menu-items")
.handle(scroll.read(cx).clone())
.axes(ScrollAxes::Vertical)
.max_h(px(320.))
.children(rows),
)
.child(
canvas(|_, _, _| {}, {
let focus = focus.clone();
move |_, _, window, cx| {
if !focus.contains_focused(window, cx) {
window.focus(&focus, cx);
}
}
})
.absolute()
.inset_0(),
);
let anchored = match self.open_at {
Some(position) => anchored().position(position),
None => anchored(),
}
.offset(point(px(0.), chrome.spacing_unit));
} else {
Vec::new()
};
wrapper = wrapper.child(deferred(anchored.child(panel.with_animation(
"menu-enter",
Animation::new(enter_duration).with_easing(ease_out_quint()),
|panel, delta| panel.opacity(delta),
))));
if let Some(panel) = anchored_menu_panel(
window,
cx,
&self.id,
self.open,
items,
self.initial_selection,
false,
self.on_change,
fallback_label,
self.open_at,
&trigger_bounds,
&chrome,
enter_duration,
) {
wrapper = wrapper.child(panel);
}
wrapper
}
}
/// Assembles the floating menu panel.
#[allow(clippy::too_many_arguments)]
pub(crate) fn anchored_menu_panel(
window: &mut Window,
cx: &mut App,
id: &ElementId,
open: bool,
items: Vec<MenuItem>,
initial_selection: Option<usize>,
preselect: bool,
on_change: Option<ChangeHandler>,
label: SharedString,
position: Option<Point<Pixels>>,
trigger_bounds: &TriggerBoundsCell,
chrome: &MenuChrome,
enter_duration: std::time::Duration,
) -> Option<AnyElement> {
let was_open = window.use_keyed_state("menu-was-open", cx, |_, _| false);
if !open {
was_open.update(cx, |was_open, _| *was_open = false);
return None;
}
let on_change = on_change.clone();
// Keyboard focus rides the panel across frames
let focus = gpui_native_utils::focus_handle(&(id.clone(), "panel").into(), window, cx);
let scroll = window.use_keyed_state("menu-scroll", cx, |_, _| ScrollHandle::new());
let selection = window.use_keyed_state("menu-selection", cx, |_, _| None);
let selected = if *was_open.read(cx) {
*selection.read(cx)
} else {
let requested = initial_selection
.map(|index| index.min(items.len().saturating_sub(1)))
.or_else(|| {
preselect
.then(|| items.iter().position(|item| item.selectable()))
.flatten()
});
selection.update(cx, |selection, _| *selection = requested);
requested
};
was_open.update(cx, |was_open, _| *was_open = true);
let rows: Vec<AnyElement> = items
.iter()
.enumerate()
.map(|(index, item)| {
render_item(
item,
index,
selected == Some(index),
&selection,
&on_change,
chrome,
)
})
.collect();
let panel = v_flex()
.id("menu-panel")
.debug_selector(|| "menu-panel".to_string())
.occlude()
.track_focus(&focus)
.role(Role::Menu)
.aria_label(label)
.min_w_56()
.p(chrome.spacing_unit)
.bg(chrome.surface)
.text_color(chrome.foreground)
.rounded(chrome.radius_overlay)
.border_1()
.border_color(chrome.panel_border)
.shadow(chrome.shadow.clone())
.overflow_hidden()
.on_mouse_down_out({
let on_change = on_change.clone();
let trigger_bounds = trigger_bounds.clone();
move |event, window, cx| {
if trigger_bounds
.borrow()
.is_some_and(|bounds| bounds.contains(&event.position))
{
return;
}
if let Some(on_change) = &on_change {
on_change(false, window, cx);
}
}
})
.on_key_down({
let items = items.clone();
let on_change = on_change.clone();
let selection = selection.clone();
move |event: &KeyDownEvent, window, cx| {
handle_menu_key(event, &items, &selection, &on_change, window, cx);
}
})
.child(
ScrollArea::new("menu-items")
.handle(scroll.read(cx).clone())
.axes(ScrollAxes::Vertical)
.max_h(px(320.))
.child(v_flex().gap_0p5().children(rows)),
)
.child(
canvas(|_, _, _| {}, {
let focus = focus.clone();
move |_, _, window, cx| {
if !focus.contains_focused(window, cx) {
window.focus(&focus, cx);
}
}
})
.absolute()
.inset_0(),
);
let anchored = match position {
Some(position) => anchored().position(position),
None => anchored(),
}
.offset(point(px(0.), chrome.spacing_unit));
Some(
deferred(anchored.child(panel.with_animation(
"menu-enter",
Animation::new(enter_duration).with_easing(ease_out_quint()),
|panel, delta| panel.opacity(delta),
)))
.into_any_element(),
)
}
/// Renders one menu row.
fn render_item(
item: &MenuItem,
index: usize,
selected: bool,
selection: &Entity<usize>,
selection: &Entity<Option<usize>>,
on_change: &Option<ChangeHandler>,
chrome: &MenuChrome,
) -> AnyElement {
@@ -469,6 +521,7 @@ fn render_item(
MenuItemKind::Action => {
let label_color = row_color(item, selected, chrome);
let disabled = item.disabled;
let selectable = item.selectable();
let destructive = item.destructive;
let checked = item.checked;
let shortcut = item.shortcut.clone();
@@ -495,17 +548,15 @@ fn render_item(
chrome.primary
};
row.bg(highlight)
} else if destructive {
row.hover(|row| row.bg(chrome.destructive))
} else {
row.hover(|row| row.bg(chrome.muted_foreground))
row.hover(|row| row.bg(chrome.muted_hover))
}
})
.on_mouse_move({
let selection = selection.clone();
move |_, _window, cx| {
if *selection.read(cx) != index {
selection.update(cx, |selection, _| *selection = index);
if selectable && *selection.read(cx) != Some(index) {
selection.update(cx, |selection, _| *selection = Some(index));
}
}
})
@@ -579,7 +630,7 @@ fn row_color(item: &MenuItem, selected: bool, chrome: &MenuChrome) -> gpui::Hsla
fn handle_menu_key(
event: &KeyDownEvent,
items: &[MenuItem],
selection: &Entity<usize>,
selection: &Entity<Option<usize>>,
on_change: &Option<ChangeHandler>,
window: &mut Window,
cx: &mut App,
@@ -592,32 +643,34 @@ fn handle_menu_key(
.collect();
let current = *selection.read(cx);
let position = selectable.iter().position(|index| *index == current);
let position =
current.and_then(|current| selectable.iter().position(|index| *index == current));
match event.keystroke.key.as_str() {
"down" => {
let next = match position {
Some(pos) => (pos + 1).min(selectable.len() - 1),
None => 0,
"down" | "up" | "home" | "end" => {
if selectable.is_empty() {
return;
}
let next = match event.keystroke.key.as_str() {
"down" => match position {
Some(pos) => (pos + 1).min(selectable.len() - 1),
None => 0,
},
"up" => match position {
Some(pos) => pos.saturating_sub(1),
None => selectable.len() - 1,
},
"home" => 0,
_ => selectable.len() - 1,
};
selection.update(cx, |selection, _| *selection = selectable[next]);
selection.update(cx, |selection, _| *selection = Some(selectable[next]));
}
"up" => {
let next = match position {
Some(pos) => pos.saturating_sub(1),
None => selectable.len() - 1,
};
selection.update(cx, |selection, _| *selection = selectable[next]);
}
"home" => selection.update(cx, |selection, _| *selection = selectable[0]),
"end" => selection.update(cx, |selection, _| {
*selection = selectable[selectable.len() - 1]
}),
"enter" | "space" => {
if let Some(item) = items.get(current)
if let Some(current) = current
&& let Some(item) = items.get(current)
&& item.selectable()
{
if let Some(on_change) = on_change {
if let Some(on_change) = &on_change {
on_change(false, window, cx);
}
if let Some(handler) = &item.handler {
@@ -626,7 +679,7 @@ fn handle_menu_key(
}
}
"escape" => {
if let Some(on_change) = on_change {
if let Some(on_change) = &on_change {
on_change(false, window, cx);
}
}