menu: Fix to support keyboard to select menu items. (#1263)

- And add to support scroll to selected item.

---------

Co-authored-by: Floyd Wang <gassnake999@gmail.com>
This commit is contained in:
Jason Lee 2025-09-22 21:47:30 +08:00 committed by GitHub
parent c80704d4d8
commit 455605d64b
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
6 changed files with 320 additions and 186 deletions

53
Cargo.lock generated
View file

@ -757,7 +757,7 @@ dependencies = [
"bitflags 2.9.1", "bitflags 2.9.1",
"cexpr", "cexpr",
"clang-sys", "clang-sys",
"itertools 0.11.0", "itertools 0.12.1",
"lazy_static", "lazy_static",
"lazycell", "lazycell",
"log", "log",
@ -780,7 +780,7 @@ dependencies = [
"bitflags 2.9.1", "bitflags 2.9.1",
"cexpr", "cexpr",
"clang-sys", "clang-sys",
"itertools 0.11.0", "itertools 0.13.0",
"log", "log",
"prettyplease", "prettyplease",
"proc-macro2", "proc-macro2",
@ -1449,7 +1449,7 @@ dependencies = [
[[package]] [[package]]
name = "collections" name = "collections"
version = "0.1.0" version = "0.1.0"
source = "git+https://github.com/zed-industries/zed.git#53b2f37452189870c93d4514604f903d5ed885d9" source = "git+https://github.com/zed-industries/zed.git#fbe06238e45c2fec6955c70b86eb26fd6a864266"
dependencies = [ dependencies = [
"indexmap 2.10.0", "indexmap 2.10.0",
"rustc-hash 2.1.1", "rustc-hash 2.1.1",
@ -1918,7 +1918,7 @@ dependencies = [
[[package]] [[package]]
name = "derive_refineable" name = "derive_refineable"
version = "0.1.0" version = "0.1.0"
source = "git+https://github.com/zed-industries/zed.git#53b2f37452189870c93d4514604f903d5ed885d9" source = "git+https://github.com/zed-industries/zed.git#fbe06238e45c2fec6955c70b86eb26fd6a864266"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
@ -3112,7 +3112,7 @@ dependencies = [
[[package]] [[package]]
name = "gpui" name = "gpui"
version = "0.1.0" version = "0.1.0"
source = "git+https://github.com/zed-industries/zed.git#53b2f37452189870c93d4514604f903d5ed885d9" source = "git+https://github.com/zed-industries/zed.git#fbe06238e45c2fec6955c70b86eb26fd6a864266"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"as-raw-xcb-connection", "as-raw-xcb-connection",
@ -3184,6 +3184,7 @@ dependencies = [
"thiserror 2.0.14", "thiserror 2.0.14",
"usvg", "usvg",
"util", "util",
"util_macros",
"uuid", "uuid",
"waker-fn", "waker-fn",
"wayland-backend", "wayland-backend",
@ -3296,7 +3297,7 @@ dependencies = [
[[package]] [[package]]
name = "gpui_macros" name = "gpui_macros"
version = "0.1.0" version = "0.1.0"
source = "git+https://github.com/zed-industries/zed.git#53b2f37452189870c93d4514604f903d5ed885d9" source = "git+https://github.com/zed-industries/zed.git#fbe06238e45c2fec6955c70b86eb26fd6a864266"
dependencies = [ dependencies = [
"heck 0.5.0", "heck 0.5.0",
"proc-macro2", "proc-macro2",
@ -3565,7 +3566,7 @@ dependencies = [
[[package]] [[package]]
name = "http_client" name = "http_client"
version = "0.1.0" version = "0.1.0"
source = "git+https://github.com/zed-industries/zed.git#53b2f37452189870c93d4514604f903d5ed885d9" source = "git+https://github.com/zed-industries/zed.git#fbe06238e45c2fec6955c70b86eb26fd6a864266"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"bytes", "bytes",
@ -3585,7 +3586,7 @@ dependencies = [
[[package]] [[package]]
name = "http_client_tls" name = "http_client_tls"
version = "0.1.0" version = "0.1.0"
source = "git+https://github.com/zed-industries/zed.git#53b2f37452189870c93d4514604f903d5ed885d9" source = "git+https://github.com/zed-industries/zed.git#fbe06238e45c2fec6955c70b86eb26fd6a864266"
dependencies = [ dependencies = [
"rustls", "rustls",
"rustls-platform-verifier", "rustls-platform-verifier",
@ -4543,7 +4544,7 @@ dependencies = [
[[package]] [[package]]
name = "media" name = "media"
version = "0.1.0" version = "0.1.0"
source = "git+https://github.com/zed-industries/zed.git#53b2f37452189870c93d4514604f903d5ed885d9" source = "git+https://github.com/zed-industries/zed.git#fbe06238e45c2fec6955c70b86eb26fd6a864266"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"bindgen 0.71.1", "bindgen 0.71.1",
@ -5598,6 +5599,17 @@ version = "2.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e3148f5046208a5d56bcfc03053e3ca6334e51da8dfb19b6cdc8b306fae3283e" checksum = "e3148f5046208a5d56bcfc03053e3ca6334e51da8dfb19b6cdc8b306fae3283e"
[[package]]
name = "perf"
version = "0.1.0"
source = "git+https://github.com/zed-industries/zed.git#fbe06238e45c2fec6955c70b86eb26fd6a864266"
dependencies = [
"collections",
"serde",
"serde_json",
"workspace-hack",
]
[[package]] [[package]]
name = "pest" name = "pest"
version = "2.8.1" version = "2.8.1"
@ -6507,7 +6519,7 @@ dependencies = [
[[package]] [[package]]
name = "refineable" name = "refineable"
version = "0.1.0" version = "0.1.0"
source = "git+https://github.com/zed-industries/zed.git#53b2f37452189870c93d4514604f903d5ed885d9" source = "git+https://github.com/zed-industries/zed.git#fbe06238e45c2fec6955c70b86eb26fd6a864266"
dependencies = [ dependencies = [
"derive_refineable", "derive_refineable",
"workspace-hack", "workspace-hack",
@ -6660,7 +6672,7 @@ dependencies = [
[[package]] [[package]]
name = "reqwest_client" name = "reqwest_client"
version = "0.1.0" version = "0.1.0"
source = "git+https://github.com/zed-industries/zed.git#53b2f37452189870c93d4514604f903d5ed885d9" source = "git+https://github.com/zed-industries/zed.git#fbe06238e45c2fec6955c70b86eb26fd6a864266"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"bytes", "bytes",
@ -6744,7 +6756,7 @@ dependencies = [
[[package]] [[package]]
name = "rope" name = "rope"
version = "0.1.0" version = "0.1.0"
source = "git+https://github.com/zed-industries/zed.git#53b2f37452189870c93d4514604f903d5ed885d9" source = "git+https://github.com/zed-industries/zed.git#fbe06238e45c2fec6955c70b86eb26fd6a864266"
dependencies = [ dependencies = [
"arrayvec", "arrayvec",
"log", "log",
@ -7251,7 +7263,7 @@ checksum = "0f7d95a54511e0c7be3f51e8867aa8cf35148d7b9445d44de2f943e2b206e749"
[[package]] [[package]]
name = "semantic_version" name = "semantic_version"
version = "0.1.0" version = "0.1.0"
source = "git+https://github.com/zed-industries/zed.git#53b2f37452189870c93d4514604f903d5ed885d9" source = "git+https://github.com/zed-industries/zed.git#fbe06238e45c2fec6955c70b86eb26fd6a864266"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"serde", "serde",
@ -7888,7 +7900,7 @@ checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
[[package]] [[package]]
name = "sum_tree" name = "sum_tree"
version = "0.1.0" version = "0.1.0"
source = "git+https://github.com/zed-industries/zed.git#53b2f37452189870c93d4514604f903d5ed885d9" source = "git+https://github.com/zed-industries/zed.git#fbe06238e45c2fec6955c70b86eb26fd6a864266"
dependencies = [ dependencies = [
"arrayvec", "arrayvec",
"log", "log",
@ -9204,7 +9216,7 @@ checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"
[[package]] [[package]]
name = "util" name = "util"
version = "0.1.0" version = "0.1.0"
source = "git+https://github.com/zed-industries/zed.git#53b2f37452189870c93d4514604f903d5ed885d9" source = "git+https://github.com/zed-industries/zed.git#fbe06238e45c2fec6955c70b86eb26fd6a864266"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"async-fs 2.1.3", "async-fs 2.1.3",
@ -9236,6 +9248,17 @@ dependencies = [
"workspace-hack", "workspace-hack",
] ]
[[package]]
name = "util_macros"
version = "0.1.0"
source = "git+https://github.com/zed-industries/zed.git#fbe06238e45c2fec6955c70b86eb26fd6a864266"
dependencies = [
"perf",
"quote",
"syn 2.0.105",
"workspace-hack",
]
[[package]] [[package]]
name = "uuid" name = "uuid"
version = "1.18.0" version = "1.18.0"

View file

@ -8,4 +8,7 @@ pub struct Confirm {
pub secondary: bool, pub secondary: bool,
} }
actions!(list, [Cancel, SelectPrev, SelectNext]); actions!(
list,
[Cancel, SelectPrev, SelectNext, SelectLeft, SelectRight]
);

View file

@ -568,7 +568,7 @@ mod tests {
matcher.update_query("Is", true); matcher.update_query("Is", true);
assert_eq!(matcher.len(), 3); assert_eq!(matcher.len(), 3);
let mut matches = matcher.clone().into_iter(); let mut matches = matcher.clone();
assert_eq!(matches.current_match_ix, 0); assert_eq!(matches.current_match_ix, 0);
assert_eq!(matches.next(), Some(18..20)); assert_eq!(matches.next(), Some(18..20));
assert_eq!(matches.next(), Some(23..25)); assert_eq!(matches.next(), Some(23..25));

View file

@ -143,7 +143,9 @@ impl Element for ContextMenu {
.anchor(anchor) .anchor(anchor)
.when_some(menu_view, |this, menu| { .when_some(menu_view, |this, menu| {
// Focus the menu, so that can be handle the action. // Focus the menu, so that can be handle the action.
menu.focus_handle(cx).focus(window); if !menu.focus_handle(cx).contains_focused(window, cx) {
menu.focus_handle(cx).focus(window);
}
this.child(div().occlude().child(menu.clone())) this.child(div().occlude().child(menu.clone()))
}), }),

View file

@ -1,6 +1,6 @@
use crate::{h_flex, ActiveTheme, Disableable, Selectable, StyledExt}; use crate::{h_flex, ActiveTheme, Disableable, Selectable, StyledExt};
use gpui::{ use gpui::{
div, prelude::FluentBuilder as _, AnyElement, App, ClickEvent, ElementId, InteractiveElement, prelude::FluentBuilder as _, AnyElement, App, ClickEvent, ElementId, InteractiveElement,
IntoElement, MouseButton, MouseMoveEvent, ParentElement, RenderOnce, IntoElement, MouseButton, MouseMoveEvent, ParentElement, RenderOnce,
StatefulInteractiveElement as _, StyleRefinement, Styled, Window, StatefulInteractiveElement as _, StyleRefinement, Styled, Window,
}; };
@ -12,6 +12,7 @@ pub struct MenuItem {
style: StyleRefinement, style: StyleRefinement,
disabled: bool, disabled: bool,
selected: bool, selected: bool,
hovered: bool,
on_click: Option<Box<dyn Fn(&ClickEvent, &mut Window, &mut App) + 'static>>, on_click: Option<Box<dyn Fn(&ClickEvent, &mut Window, &mut App) + 'static>>,
on_mouse_enter: Option<Box<dyn Fn(&MouseMoveEvent, &mut Window, &mut App) + 'static>>, on_mouse_enter: Option<Box<dyn Fn(&MouseMoveEvent, &mut Window, &mut App) + 'static>>,
children: SmallVec<[AnyElement; 2]>, children: SmallVec<[AnyElement; 2]>,
@ -25,6 +26,7 @@ impl MenuItem {
style: StyleRefinement::default(), style: StyleRefinement::default(),
disabled: false, disabled: false,
selected: false, selected: false,
hovered: false,
on_click: None, on_click: None,
on_mouse_enter: None, on_mouse_enter: None,
children: SmallVec::new(), children: SmallVec::new(),
@ -42,6 +44,11 @@ impl MenuItem {
self self
} }
pub fn hovered(mut self, hovered: bool) -> Self {
self.hovered = hovered;
self
}
pub fn on_click( pub fn on_click(
mut self, mut self,
handler: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static, handler: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
@ -50,6 +57,8 @@ impl MenuItem {
self self
} }
/// Set a handler for when the mouse enters the MenuItem.
#[allow(unused)]
pub fn on_mouse_enter( pub fn on_mouse_enter(
mut self, mut self,
handler: impl Fn(&MouseMoveEvent, &mut Window, &mut App) + 'static, handler: impl Fn(&MouseMoveEvent, &mut Window, &mut App) + 'static,
@ -103,11 +112,13 @@ impl RenderOnce for MenuItem {
.justify_between() .justify_between()
.refine_style(&self.style) .refine_style(&self.style)
.when(!self.disabled, |this| { .when(!self.disabled, |this| {
this.when(!self.selected, |this| { this.when(self.hovered, |this| {
this.hover(|this| { this.bg(cx.theme().accent)
this.bg(cx.theme().accent) .text_color(cx.theme().accent_foreground)
.text_color(cx.theme().accent_foreground) })
}) .hover(|this| {
this.bg(cx.theme().accent)
.text_color(cx.theme().accent_foreground)
}) })
.when_some(self.on_mouse_enter, |this, on_mouse_enter| { .when_some(self.on_mouse_enter, |this, on_mouse_enter| {
this.on_mouse_move(move |ev, window, cx| (on_mouse_enter)(ev, window, cx)) this.on_mouse_move(move |ev, window, cx| (on_mouse_enter)(ev, window, cx))
@ -122,13 +133,6 @@ impl RenderOnce for MenuItem {
.when(self.disabled, |this| { .when(self.disabled, |this| {
this.text_color(cx.theme().muted_foreground) this.text_color(cx.theme().muted_foreground)
}) })
.child( .children(self.children)
h_flex()
.w_full()
.items_center()
.justify_between()
.gap_x_1()
.child(div().w_full().children(self.children)),
)
} }
} }

View file

@ -1,11 +1,12 @@
use crate::actions::{Cancel, Confirm, SelectNext, SelectPrev}; use crate::actions::{Cancel, Confirm, SelectNext, SelectPrev};
use crate::input::{SelectLeft, SelectRight};
use crate::menu::menu_item::MenuItem; use crate::menu::menu_item::MenuItem;
use crate::scroll::{Scrollbar, ScrollbarState}; use crate::scroll::{Scrollbar, ScrollbarState};
use crate::{ use crate::{
button::Button, h_flex, popover::Popover, v_flex, ActiveTheme, Icon, IconName, Selectable, button::Button, h_flex, popover::Popover, v_flex, ActiveTheme, Icon, IconName, Selectable,
Sizable as _, Sizable as _,
}; };
use crate::{Kbd, StyledExt}; use crate::{Kbd, Side, StyledExt};
use gpui::{ use gpui::{
anchored, canvas, div, prelude::FluentBuilder, px, rems, Action, AnyElement, App, AppContext, anchored, canvas, div, prelude::FluentBuilder, px, rems, Action, AnyElement, App, AppContext,
Bounds, Context, Corner, DismissEvent, Edges, Entity, EventEmitter, FocusHandle, Focusable, Bounds, Context, Corner, DismissEvent, Edges, Entity, EventEmitter, FocusHandle, Focusable,
@ -17,14 +18,16 @@ use std::ops::Deref;
use std::rc::Rc; use std::rc::Rc;
const ITEM_HEIGHT: Pixels = px(26.); const ITEM_HEIGHT: Pixels = px(26.);
const CONTEXT: &str = "PopupMenu";
pub fn init(cx: &mut App) { pub fn init(cx: &mut App) {
let context = Some("PopupMenu");
cx.bind_keys([ cx.bind_keys([
KeyBinding::new("enter", Confirm { secondary: false }, context), KeyBinding::new("enter", Confirm { secondary: false }, Some(CONTEXT)),
KeyBinding::new("escape", Cancel, context), KeyBinding::new("escape", Cancel, Some(CONTEXT)),
KeyBinding::new("up", SelectPrev, context), KeyBinding::new("up", SelectPrev, Some(CONTEXT)),
KeyBinding::new("down", SelectNext, context), KeyBinding::new("down", SelectNext, Some(CONTEXT)),
KeyBinding::new("left", SelectLeft, Some(CONTEXT)),
KeyBinding::new("right", SelectRight, Some(CONTEXT)),
]); ]);
} }
@ -86,6 +89,19 @@ enum PopupMenuItem {
impl PopupMenuItem { impl PopupMenuItem {
fn is_clickable(&self) -> bool { fn is_clickable(&self) -> bool {
!matches!(self, PopupMenuItem::Separator) !matches!(self, PopupMenuItem::Separator)
&& matches!(
self,
PopupMenuItem::Item {
disabled: false,
..
} | PopupMenuItem::ElementItem {
disabled: false,
..
} | PopupMenuItem::Submenu {
disabled: false,
..
}
)
} }
fn is_separator(&self) -> bool { fn is_separator(&self) -> bool {
@ -103,7 +119,6 @@ pub struct PopupMenu {
min_width: Option<Pixels>, min_width: Option<Pixels>,
max_width: Option<Pixels>, max_width: Option<Pixels>,
max_height: Option<Pixels>, max_height: Option<Pixels>,
hovered_menu_ix: Option<usize>,
bounds: Bounds<Pixels>, bounds: Bounds<Pixels>,
scrollable: bool, scrollable: bool,
@ -123,12 +138,7 @@ impl PopupMenu {
) -> Entity<Self> { ) -> Entity<Self> {
cx.new(|cx| { cx.new(|cx| {
let focus_handle = cx.focus_handle(); let focus_handle = cx.focus_handle();
let _subscriptions = let _subscriptions = vec![];
vec![
cx.on_blur(&focus_handle, window, |this: &mut PopupMenu, window, cx| {
this.dismiss(&Cancel, window, cx)
}),
];
let menu = Self { let menu = Self {
focus_handle, focus_handle,
@ -140,7 +150,6 @@ impl PopupMenu {
max_width: None, max_width: None,
max_height: None, max_height: None,
has_icon: false, has_icon: false,
hovered_menu_ix: None,
bounds: Bounds::default(), bounds: Bounds::default(),
scrollable: false, scrollable: false,
scroll_handle: ScrollHandle::default(), scroll_handle: ScrollHandle::default(),
@ -516,7 +525,7 @@ impl PopupMenu {
} }
pub(crate) fn active_submenu(&self) -> Option<Entity<PopupMenu>> { pub(crate) fn active_submenu(&self) -> Option<Entity<PopupMenu>> {
if let Some(ix) = self.hovered_menu_ix { if let Some(ix) = self.selected_index {
if let Some(item) = self.menu_items.get(ix) { if let Some(item) = self.menu_items.get(ix) {
return match item { return match item {
PopupMenuItem::Submenu { menu, .. } => Some(menu.clone()), PopupMenuItem::Submenu { menu, .. } => Some(menu.clone()),
@ -566,40 +575,128 @@ impl PopupMenu {
} }
} }
fn select_next(&mut self, _: &SelectNext, _: &mut Window, cx: &mut Context<Self>) { fn set_selected_index(&mut self, ix: usize, cx: &mut Context<Self>) {
let count = self.clickable_menu_items().count(); if self.selected_index != Some(ix) {
if count > 0 {
let last_ix = count.saturating_sub(1);
let ix = self
.selected_index
.map(|index| if index == last_ix { 0 } else { index + 1 })
.unwrap_or(0);
self.selected_index = Some(ix); self.selected_index = Some(ix);
self.scroll_handle.scroll_to_item(ix);
cx.notify(); cx.notify();
} }
} }
fn select_prev(&mut self, _: &SelectPrev, _: &mut Window, cx: &mut Context<Self>) { fn select_next(&mut self, _: &SelectNext, _: &mut Window, cx: &mut Context<Self>) {
let count = self.clickable_menu_items().count(); cx.stop_propagation();
if count > 0 { let Some(ix) = self.selected_index else {
let last_ix = count.saturating_sub(1); self.set_selected_index(0, cx);
return;
};
let ix = self if let Some((next_ix, _)) = self
.selected_index .menu_items
.map(|index| { .iter()
if index == last_ix { .enumerate()
0 .find(|(i, item)| *i > ix && item.is_clickable())
} else { {
index.saturating_sub(1) self.set_selected_index(next_ix, cx);
} return;
}) }
.unwrap_or(last_ix);
self.selected_index = Some(ix); self.set_selected_index(0, cx);
}
fn select_prev(&mut self, _: &SelectPrev, _: &mut Window, cx: &mut Context<Self>) {
cx.stop_propagation();
let ix = self.selected_index.unwrap_or(0);
if let Some((prev_ix, _)) = self
.menu_items
.iter()
.enumerate()
.rev()
.find(|(i, item)| *i < ix && item.is_clickable())
{
self.set_selected_index(prev_ix, cx);
return;
}
let last_clickable_ix = self.clickable_menu_items().last().map(|(ix, _)| ix);
self.set_selected_index(last_clickable_ix.unwrap_or(0), cx);
}
fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
let (anchor, _) = self.child_menu_anchor(window);
if matches!(anchor, Corner::TopLeft | Corner::BottomLeft) {
self._unselect_submenu(window, cx);
} else {
self._select_submenu(window, cx);
}
if self.parent_side(cx).is_left() {
self._focus_parent_menu(window, cx);
}
}
fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
let (anchor, _) = self.child_menu_anchor(window);
if matches!(anchor, Corner::TopLeft | Corner::BottomLeft) {
self._select_submenu(window, cx);
} else {
self._unselect_submenu(window, cx);
}
if self.parent_side(cx).is_right() {
self._focus_parent_menu(window, cx);
}
}
fn _select_submenu(&mut self, window: &mut Window, cx: &mut Context<Self>) {
if let Some(active_submenu) = self.active_submenu() {
// Focus the submenu, so that can be handle the action.
active_submenu.update(cx, |view, cx| {
view.focus_handle(cx).focus(window);
view.set_selected_index(0, cx);
});
cx.notify(); cx.notify();
} }
} }
fn _unselect_submenu(&mut self, _: &mut Window, cx: &mut Context<Self>) {
if let Some(active_submenu) = self.active_submenu() {
active_submenu.update(cx, |view, cx| {
view.selected_index = None;
cx.notify();
});
}
}
fn _focus_parent_menu(&mut self, window: &mut Window, cx: &mut Context<Self>) {
if let Some(parent) = self.parent_menu.as_ref() {
self.selected_index = None;
if let Some(parent) = parent.upgrade() {
parent.update(cx, |view, cx| {
view.focus_handle.focus(window);
cx.notify();
});
}
}
}
fn parent_side(&self, cx: &App) -> Side {
let Some(parent) = self.parent_menu.as_ref() else {
return Side::Left;
};
let Some(parent) = parent.upgrade() else {
return Side::Left;
};
let parent_x = parent.read(cx).bounds.origin.x;
if parent_x < self.bounds.origin.x {
Side::Left
} else {
Side::Right
}
}
fn dismiss(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) { fn dismiss(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
if self.active_submenu().is_some() { if self.active_submenu().is_some() {
return; return;
@ -618,7 +715,7 @@ impl PopupMenu {
// Dismiss parent menu, when this menu is dismissed // Dismiss parent menu, when this menu is dismissed
_ = parent_menu.update(cx, |view, cx| { _ = parent_menu.update(cx, |view, cx| {
view.hovered_menu_ix = None; view.selected_index = None;
view.dismiss(&Cancel, window, cx); view.dismiss(&Cancel, window, cx);
}); });
} }
@ -672,6 +769,29 @@ impl PopupMenu {
Some(icon) Some(icon)
} }
#[inline]
fn max_width(&self) -> Pixels {
self.max_width.unwrap_or(px(500.))
}
/// Calculate the anchor corner and left offset for child submenu
fn child_menu_anchor(&self, window: &Window) -> (Corner, Pixels) {
let bounds = self.bounds;
let max_width = self.max_width();
let (anchor, left) = if max_width + bounds.origin.x > window.bounds().size.width {
(Corner::TopRight, -px(14.))
} else {
(Corner::TopLeft, bounds.size.width)
};
let is_bottom_pos = bounds.origin.y + bounds.size.height > window.bounds().size.height;
if is_bottom_pos {
(anchor.other_side_corner_along(gpui::Axis::Vertical), left)
} else {
(anchor, left)
}
}
fn render_item( fn render_item(
&self, &self,
ix: usize, ix: usize,
@ -680,10 +800,8 @@ impl PopupMenu {
window: &mut Window, window: &mut Window,
cx: &mut Context<Self>, cx: &mut Context<Self>,
) -> impl IntoElement { ) -> impl IntoElement {
let bounds = self.bounds;
let max_width = state.max_width;
let has_icon = self.has_icon; let has_icon = self.has_icon;
let hovered = self.hovered_menu_ix == Some(ix); let selected = self.selected_index == Some(ix);
const EDGE_PADDING: Pixels = px(8.); const EDGE_PADDING: Pixels = px(8.);
const INNER_PADDING: Pixels = px(4.); const INNER_PADDING: Pixels = px(4.);
@ -694,20 +812,25 @@ impl PopupMenu {
.px(INNER_PADDING) .px(INNER_PADDING)
.rounded(state.radius) .rounded(state.radius)
.items_center() .items_center()
.hovered(selected)
.on_mouse_enter(cx.listener(move |this, _, _, cx| { .on_mouse_enter(cx.listener(move |this, _, _, cx| {
this.hovered_menu_ix = Some(ix); if this.selected_index == Some(ix) {
return;
}
this.selected_index = Some(ix);
cx.notify(); cx.notify();
})); }));
match item { match item {
PopupMenuItem::Separator => this.h_auto().p_0().disabled(true).child( PopupMenuItem::Separator => this
div() .h_auto()
.rounded_none() .p_0()
.h(px(1.)) .my_0p5()
.mx_neg_1() .mx_neg_1()
.my_0p5() .h(px(1.))
.bg(cx.theme().border), .bg(cx.theme().border)
), .disabled(true),
PopupMenuItem::Label(label) => this.disabled(true).cursor_default().child( PopupMenuItem::Label(label) => this.disabled(true).cursor_default().child(
h_flex() h_flex()
.cursor_default() .cursor_default()
@ -754,9 +877,45 @@ impl PopupMenu {
) )
}) })
.disabled(*disabled) .disabled(*disabled)
.h(ITEM_HEIGHT)
.children(Self::render_icon(has_icon, icon.clone(), window, cx))
.child( .child(
h_flex() h_flex()
.h(ITEM_HEIGHT) .w_full()
.gap_2()
.items_center()
.justify_between()
.when(!show_link_icon, |this| this.child(label.clone()))
.when(show_link_icon, |this| {
this.child(
h_flex()
.w_full()
.justify_between()
.gap_1p5()
.child(label.clone())
.child(
Icon::new(IconName::ExternalLink)
.xsmall()
.text_color(cx.theme().muted_foreground),
),
)
})
.children(key),
)
}
PopupMenuItem::Submenu {
icon,
label,
menu,
disabled,
} => this
.selected(selected)
.disabled(*disabled)
.items_start()
.child(
h_flex()
.min_h(ITEM_HEIGHT)
.size_full()
.items_center() .items_center()
.gap_x_1() .gap_x_1()
.children(Self::render_icon(has_icon, icon.clone(), window, cx)) .children(Self::render_icon(has_icon, icon.clone(), window, cx))
@ -766,78 +925,28 @@ impl PopupMenu {
.gap_2() .gap_2()
.items_center() .items_center()
.justify_between() .justify_between()
.when(!show_link_icon, |this| this.child(label.clone())) .child(label.clone())
.when(show_link_icon, |this| { .child(IconName::ChevronRight),
this.child(
h_flex().gap_1p5().child(label.clone()).child(
Icon::new(IconName::ExternalLink)
.xsmall()
.text_color(cx.theme().muted_foreground),
),
)
})
.children(key),
), ),
) )
} .when(selected, |this| {
PopupMenuItem::Submenu { let (anchor, left) = self.child_menu_anchor(window);
icon, let is_bottom_pos = matches!(anchor, Corner::BottomLeft | Corner::BottomRight);
label,
menu, this.child(
disabled, anchored()
} => this.selected(hovered).disabled(*disabled).child( .anchor(anchor)
h_flex()
.items_start()
.when(hovered, |this| {
this.rounded(cx.theme().radius)
.mx(-INNER_PADDING)
.px(INNER_PADDING)
.bg(cx.theme().accent)
.text_color(cx.theme().accent_foreground)
})
.child(
h_flex()
.min_h(ITEM_HEIGHT)
.size_full()
.items_center()
.gap_x_1()
.children(Self::render_icon(has_icon, icon.clone(), window, cx))
.child( .child(
h_flex() div()
.flex_1() .occlude()
.gap_2() .when(is_bottom_pos, |this| this.bottom_0())
.items_center() .when(!is_bottom_pos, |this| this.top_neg_1())
.justify_between() .left(left)
.child(label.clone()) .child(menu.clone()),
.child(IconName::ChevronRight), )
), .snap_to_window_with_margin(Edges::all(EDGE_PADDING)),
) )
.when(hovered, |this| { }),
let (anchor, left) =
if max_width + bounds.origin.x > window.bounds().size.width {
(Corner::TopRight, -px(14.))
} else {
(Corner::TopLeft, bounds.size.width)
};
let is_bottom_pos =
bounds.origin.y + bounds.size.height > window.bounds().size.height;
this.child(
anchored()
.anchor(anchor)
.child(
div()
.occlude()
.when(is_bottom_pos, |this| this.bottom_0())
.when(!is_bottom_pos, |this| this.top_neg_1())
.left(left)
.child(menu.clone()),
)
.snap_to_window_with_margin(Edges::all(EDGE_PADDING)),
)
}),
),
} }
} }
} }
@ -852,7 +961,6 @@ impl Focusable for PopupMenu {
#[derive(Clone, Copy)] #[derive(Clone, Copy)]
struct ItemState { struct ItemState {
max_width: Pixels,
radius: Pixels, radius: Pixels,
} }
@ -868,19 +976,20 @@ impl Render for PopupMenu {
}, },
|height| height, |height| height,
); );
let max_width = self.max_width.unwrap_or(px(500.));
let max_width = self.max_width();
let item_state = ItemState { let item_state = ItemState {
max_width,
radius: cx.theme().radius.min(px(8.)), radius: cx.theme().radius.min(px(8.)),
}; };
v_flex() v_flex()
.id("popup-menu") .id("popup-menu")
.key_context("PopupMenu") .key_context(CONTEXT)
.track_focus(&self.focus_handle) .track_focus(&self.focus_handle)
.on_action(cx.listener(Self::select_next)) .on_action(cx.listener(Self::select_next))
.on_action(cx.listener(Self::select_prev)) .on_action(cx.listener(Self::select_prev))
.on_action(cx.listener(Self::select_left))
.on_action(cx.listener(Self::select_right))
.on_action(cx.listener(Self::confirm)) .on_action(cx.listener(Self::confirm))
.on_action(cx.listener(Self::dismiss)) .on_action(cx.listener(Self::dismiss))
.on_mouse_down_out(cx.listener(|this, ev: &MouseDownEvent, window, cx| { .on_mouse_down_out(cx.listener(|this, ev: &MouseDownEvent, window, cx| {
@ -899,41 +1008,34 @@ impl Render for PopupMenu {
.text_color(cx.theme().popover_foreground) .text_color(cx.theme().popover_foreground)
.relative() .relative()
.child( .child(
div() v_flex()
.id("items") .id("items")
.p_1()
.gap_y_0p5()
.min_w(rems(8.))
.when_some(self.min_width, |this, min_width| this.min_w(min_width))
.max_w(max_width)
.when(self.scrollable, |this| { .when(self.scrollable, |this| {
this.max_h(max_height) this.max_h(max_height)
.overflow_y_scroll() .overflow_y_scroll()
.track_scroll(&self.scroll_handle) .track_scroll(&self.scroll_handle)
}) })
.child( .children(
v_flex() self.menu_items
.p_1() .iter()
.gap_y_0p5() .enumerate()
.min_w(rems(8.)) // Ignore last separator
.when_some(self.min_width, |this, min_width| this.min_w(min_width)) .filter(|(ix, item)| !(*ix + 1 == items_count && item.is_separator()))
.max_w(max_width) .map(|(ix, item)| self.render_item(ix, item, item_state, window, cx)),
.child({ )
canvas( .child({
move |bounds, _, cx| view.update(cx, |r, _| r.bounds = bounds), canvas(
|_, _, _, _| {}, move |bounds, _, cx| view.update(cx, |r, _| r.bounds = bounds),
) |_, _, _, _| {},
.absolute() )
.size_full() .absolute()
}) .size_full()
.children( }),
self.menu_items
.iter()
.enumerate()
// Ignore last separator
.filter(|(ix, item)| {
!(*ix + 1 == items_count && item.is_separator())
})
.map(|(ix, item)| {
self.render_item(ix, item, item_state, window, cx)
}),
),
),
) )
.when(self.scrollable, |this| { .when(self.scrollable, |this| {
// TODO: When the menu is limited by `overflow_y_scroll`, the sub-menu will cannot be displayed. // TODO: When the menu is limited by `overflow_y_scroll`, the sub-menu will cannot be displayed.