Add a context menu to the project panel (#3393)

This PR adds a context menu to the project panel in Zed2.

* [x] Allow the context menu to extend outside of the project panel's
bounds
* [x] Add keyboard shortcuts to the context menu
* [x] Dismiss the context menu
    * [x] when running an action
    * [x] when changing selection in the project panel

Release Notes:

NA
This commit is contained in:
Max Brunsfeld
2023-11-29 10:04:41 -08:00
committed by GitHub
17 changed files with 272 additions and 170 deletions
+134 -53
View File
@@ -1,23 +1,28 @@
use std::cell::RefCell;
use std::rc::Rc;
use crate::{prelude::*, v_stack, Label, List};
use crate::{ListItem, ListSeparator, ListSubHeader};
use gpui::{
overlay, px, Action, AnchorCorner, AnyElement, AppContext, Bounds, ClickEvent, DismissEvent,
DispatchPhase, Div, EventEmitter, FocusHandle, FocusableView, IntoElement, LayoutId,
ManagedView, MouseButton, MouseDownEvent, Pixels, Point, Render, View, VisualContext,
use crate::{
h_stack, prelude::*, v_stack, KeyBinding, Label, List, ListItem, ListSeparator, ListSubHeader,
};
use gpui::{
overlay, px, Action, AnchorCorner, AnyElement, AppContext, Bounds, DismissEvent, DispatchPhase,
Div, EventEmitter, FocusHandle, FocusableView, IntoElement, LayoutId, ManagedView, MouseButton,
MouseDownEvent, Pixels, Point, Render, View, VisualContext,
};
use menu::{SelectFirst, SelectLast, SelectNext, SelectPrev};
use std::{cell::RefCell, rc::Rc};
pub enum ContextMenuItem {
Separator,
Header(SharedString),
Entry(SharedString, Rc<dyn Fn(&ClickEvent, &mut WindowContext)>),
Entry {
label: SharedString,
handler: Rc<dyn Fn(&mut WindowContext)>,
key_binding: Option<KeyBinding>,
},
}
pub struct ContextMenu {
items: Vec<ContextMenuItem>,
focus_handle: FocusHandle,
selected_index: Option<usize>,
}
impl FocusableView for ContextMenu {
@@ -39,6 +44,7 @@ impl ContextMenu {
Self {
items: Default::default(),
focus_handle: cx.focus_handle(),
selected_index: None,
},
cx,
)
@@ -58,27 +64,90 @@ impl ContextMenu {
pub fn entry(
mut self,
label: impl Into<SharedString>,
on_click: impl Fn(&ClickEvent, &mut WindowContext) + 'static,
on_click: impl Fn(&mut WindowContext) + 'static,
) -> Self {
self.items
.push(ContextMenuItem::Entry(label.into(), Rc::new(on_click)));
self.items.push(ContextMenuItem::Entry {
label: label.into(),
handler: Rc::new(on_click),
key_binding: None,
});
self
}
pub fn action(self, label: impl Into<SharedString>, action: Box<dyn Action>) -> Self {
// todo: add the keybindings to the list entry
self.entry(label.into(), move |_, cx| {
cx.dispatch_action(action.boxed_clone())
})
pub fn action(
mut self,
label: impl Into<SharedString>,
action: Box<dyn Action>,
cx: &mut WindowContext,
) -> Self {
self.items.push(ContextMenuItem::Entry {
label: label.into(),
key_binding: KeyBinding::for_action(&*action, cx),
handler: Rc::new(move |cx| cx.dispatch_action(action.boxed_clone())),
});
self
}
pub fn confirm(&mut self, _: &menu::Confirm, cx: &mut ViewContext<Self>) {
// todo!()
cx.emit(DismissEvent::Dismiss);
if let Some(ContextMenuItem::Entry { handler, .. }) =
self.selected_index.and_then(|ix| self.items.get(ix))
{
(handler)(cx)
}
cx.emit(DismissEvent);
}
pub fn cancel(&mut self, _: &menu::Cancel, cx: &mut ViewContext<Self>) {
cx.emit(DismissEvent::Dismiss);
cx.emit(DismissEvent);
}
fn select_first(&mut self, _: &SelectFirst, cx: &mut ViewContext<Self>) {
self.selected_index = self.items.iter().position(|item| item.is_selectable());
cx.notify();
}
fn select_last(&mut self, _: &SelectLast, cx: &mut ViewContext<Self>) {
for (ix, item) in self.items.iter().enumerate().rev() {
if item.is_selectable() {
self.selected_index = Some(ix);
cx.notify();
break;
}
}
}
fn select_next(&mut self, _: &SelectNext, cx: &mut ViewContext<Self>) {
if let Some(ix) = self.selected_index {
for (ix, item) in self.items.iter().enumerate().skip(ix + 1) {
if item.is_selectable() {
self.selected_index = Some(ix);
cx.notify();
break;
}
}
} else {
self.select_first(&Default::default(), cx);
}
}
pub fn select_prev(&mut self, _: &SelectPrev, cx: &mut ViewContext<Self>) {
if let Some(ix) = self.selected_index {
for (ix, item) in self.items.iter().enumerate().take(ix).rev() {
if item.is_selectable() {
self.selected_index = Some(ix);
cx.notify();
break;
}
}
} else {
self.select_last(&Default::default(), cx);
}
}
}
impl ContextMenuItem {
fn is_selectable(&self) -> bool {
matches!(self, Self::Entry { .. })
}
}
@@ -90,38 +159,51 @@ impl Render for ContextMenu {
v_stack()
.min_w(px(200.))
.track_focus(&self.focus_handle)
.on_mouse_down_out(
cx.listener(|this: &mut Self, _, cx| this.cancel(&Default::default(), cx)),
)
// .on_action(ContextMenu::select_first)
// .on_action(ContextMenu::select_last)
// .on_action(ContextMenu::select_next)
// .on_action(ContextMenu::select_prev)
.on_mouse_down_out(cx.listener(|this, _, cx| this.cancel(&Default::default(), cx)))
.key_context("menu")
.on_action(cx.listener(ContextMenu::select_first))
.on_action(cx.listener(ContextMenu::select_last))
.on_action(cx.listener(ContextMenu::select_next))
.on_action(cx.listener(ContextMenu::select_prev))
.on_action(cx.listener(ContextMenu::confirm))
.on_action(cx.listener(ContextMenu::cancel))
.flex_none()
// .bg(cx.theme().colors().elevated_surface_background)
// .border()
// .border_color(cx.theme().colors().border)
.child(
List::new().children(self.items.iter().map(|item| match item {
ContextMenuItem::Separator => ListSeparator::new().into_any_element(),
ContextMenuItem::Header(header) => {
ListSubHeader::new(header.clone()).into_any_element()
}
ContextMenuItem::Entry(entry, callback) => {
let callback = callback.clone();
let dismiss = cx.listener(|_, _, cx| cx.emit(DismissEvent::Dismiss));
List::new().children(self.items.iter().enumerate().map(
|(ix, item)| match item {
ContextMenuItem::Separator => ListSeparator::new().into_any_element(),
ContextMenuItem::Header(header) => {
ListSubHeader::new(header.clone()).into_any_element()
}
ContextMenuItem::Entry {
label: entry,
handler: callback,
key_binding,
} => {
let callback = callback.clone();
let dismiss = cx.listener(|_, _, cx| cx.emit(DismissEvent));
ListItem::new(entry.clone())
.child(Label::new(entry.clone()))
.on_click(move |event, cx| {
callback(event, cx);
dismiss(event, cx)
})
.into_any_element()
}
})),
ListItem::new(entry.clone())
.child(
h_stack()
.w_full()
.justify_between()
.child(Label::new(entry.clone()))
.children(
key_binding
.clone()
.map(|binding| div().ml_1().child(binding)),
),
)
.selected(Some(ix) == self.selected_index)
.on_click(move |event, cx| {
callback(cx);
dismiss(event, cx)
})
.into_any_element()
}
},
)),
),
)
}
@@ -177,6 +259,7 @@ pub struct MenuHandleState<M> {
child_element: Option<AnyElement>,
menu_element: Option<AnyElement>,
}
impl<M: ManagedView> Element for MenuHandle<M> {
type State = MenuHandleState<M>;
@@ -264,11 +347,9 @@ impl<M: ManagedView> Element for MenuHandle<M> {
let new_menu = (builder)(cx);
let menu2 = menu.clone();
cx.subscribe(&new_menu, move |_modal, e, cx| match e {
&DismissEvent::Dismiss => {
*menu2.borrow_mut() = None;
cx.notify();
}
cx.subscribe(&new_menu, move |_modal, _: &DismissEvent, cx| {
*menu2.borrow_mut() = None;
cx.notify();
})
.detach();
cx.focus_view(&new_menu);
+5 -7
View File
@@ -374,17 +374,15 @@ impl RenderOnce for List {
type Rendered = Div;
fn render(self, _cx: &mut WindowContext) -> Self::Rendered {
let list_content = match (self.children.is_empty(), self.toggle) {
(false, _) => div().children(self.children),
(true, Toggle::Toggled(false)) => div(),
(true, _) => div().child(Label::new(self.empty_message.clone()).color(Color::Muted)),
};
v_stack()
.w_full()
.py_1()
.children(self.header.map(|header| header))
.child(list_content)
.map(|this| match (self.children.is_empty(), self.toggle) {
(false, _) => this.children(self.children),
(true, Toggle::Toggled(false)) => this,
(true, _) => this.child(Label::new(self.empty_message.clone()).color(Color::Muted)),
})
}
}
@@ -10,11 +10,11 @@ fn build_menu(cx: &mut WindowContext, header: impl Into<SharedString>) -> View<C
ContextMenu::build(cx, |menu, _| {
menu.header(header)
.separator()
.entry("Print current time", |_event, cx| {
.entry("Print current time", |cx| {
println!("dispatching PrintCurrentTime action");
cx.dispatch_action(PrintCurrentDate.boxed_clone())
})
.entry("Print best foot", |_event, cx| {
.entry("Print best foot", |cx| {
cx.dispatch_action(PrintBestFood.boxed_clone())
})
})