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
+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);
}
}