1use crate::{
2 h_flex, prelude::*, v_flex, Icon, IconName, KeyBinding, Label, List, ListItem, ListSeparator,
3 ListSubHeader, WithRemSize,
4};
5use gpui::{
6 px, Action, AnyElement, AppContext, DismissEvent, EventEmitter, FocusHandle, FocusableView,
7 IntoElement, Render, Subscription, View, VisualContext,
8};
9use menu::{SelectFirst, SelectLast, SelectNext, SelectPrev};
10use settings::Settings;
11use std::{rc::Rc, time::Duration};
12use theme::ThemeSettings;
13
14enum ContextMenuItem {
15 Separator,
16 Header(SharedString),
17 Label(SharedString),
18 Entry {
19 toggled: Option<bool>,
20 label: SharedString,
21 icon: Option<IconName>,
22 handler: Rc<dyn Fn(Option<&FocusHandle>, &mut WindowContext)>,
23 action: Option<Box<dyn Action>>,
24 },
25 CustomEntry {
26 entry_render: Box<dyn Fn(&mut WindowContext) -> AnyElement>,
27 handler: Rc<dyn Fn(Option<&FocusHandle>, &mut WindowContext)>,
28 selectable: bool,
29 },
30}
31
32pub struct ContextMenu {
33 items: Vec<ContextMenuItem>,
34 focus_handle: FocusHandle,
35 action_context: Option<FocusHandle>,
36 selected_index: Option<usize>,
37 delayed: bool,
38 clicked: bool,
39 _on_blur_subscription: Subscription,
40}
41
42impl FocusableView for ContextMenu {
43 fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
44 self.focus_handle.clone()
45 }
46}
47
48impl EventEmitter<DismissEvent> for ContextMenu {}
49
50impl FluentBuilder for ContextMenu {}
51
52impl ContextMenu {
53 pub fn build(
54 cx: &mut WindowContext,
55 f: impl FnOnce(Self, &mut WindowContext) -> Self,
56 ) -> View<Self> {
57 cx.new_view(|cx| {
58 let focus_handle = cx.focus_handle();
59 let _on_blur_subscription = cx.on_blur(&focus_handle, |this: &mut ContextMenu, cx| {
60 this.cancel(&menu::Cancel, cx)
61 });
62 cx.refresh();
63 f(
64 Self {
65 items: Default::default(),
66 focus_handle,
67 action_context: None,
68 selected_index: None,
69 delayed: false,
70 clicked: false,
71 _on_blur_subscription,
72 },
73 cx,
74 )
75 })
76 }
77
78 pub fn context(mut self, focus: FocusHandle) -> Self {
79 self.action_context = Some(focus);
80 self
81 }
82
83 pub fn header(mut self, title: impl Into<SharedString>) -> Self {
84 self.items.push(ContextMenuItem::Header(title.into()));
85 self
86 }
87
88 pub fn separator(mut self) -> Self {
89 self.items.push(ContextMenuItem::Separator);
90 self
91 }
92
93 pub fn entry(
94 mut self,
95 label: impl Into<SharedString>,
96 action: Option<Box<dyn Action>>,
97 handler: impl Fn(&mut WindowContext) + 'static,
98 ) -> Self {
99 self.items.push(ContextMenuItem::Entry {
100 toggled: None,
101 label: label.into(),
102 handler: Rc::new(move |_, cx| handler(cx)),
103 icon: None,
104 action,
105 });
106 self
107 }
108
109 pub fn toggleable_entry(
110 mut self,
111 label: impl Into<SharedString>,
112 toggled: bool,
113 action: Option<Box<dyn Action>>,
114 handler: impl Fn(&mut WindowContext) + 'static,
115 ) -> Self {
116 self.items.push(ContextMenuItem::Entry {
117 toggled: Some(toggled),
118 label: label.into(),
119 handler: Rc::new(move |_, cx| handler(cx)),
120 icon: None,
121 action,
122 });
123 self
124 }
125
126 pub fn custom_row(
127 mut self,
128 entry_render: impl Fn(&mut WindowContext) -> AnyElement + 'static,
129 ) -> Self {
130 self.items.push(ContextMenuItem::CustomEntry {
131 entry_render: Box::new(entry_render),
132 handler: Rc::new(|_, _| {}),
133 selectable: false,
134 });
135 self
136 }
137
138 pub fn custom_entry(
139 mut self,
140 entry_render: impl Fn(&mut WindowContext) -> AnyElement + 'static,
141 handler: impl Fn(&mut WindowContext) + 'static,
142 ) -> Self {
143 self.items.push(ContextMenuItem::CustomEntry {
144 entry_render: Box::new(entry_render),
145 handler: Rc::new(move |_, cx| handler(cx)),
146 selectable: true,
147 });
148 self
149 }
150
151 pub fn label(mut self, label: impl Into<SharedString>) -> Self {
152 let label = label.into();
153 self.items.push(ContextMenuItem::Label(label));
154 self
155 }
156
157 pub fn action(mut self, label: impl Into<SharedString>, action: Box<dyn Action>) -> Self {
158 self.items.push(ContextMenuItem::Entry {
159 toggled: None,
160 label: label.into(),
161 action: Some(action.boxed_clone()),
162
163 handler: Rc::new(move |context, cx| {
164 if let Some(context) = &context {
165 cx.focus(context);
166 }
167 cx.dispatch_action(action.boxed_clone());
168 }),
169 icon: None,
170 });
171 self
172 }
173
174 pub fn link(mut self, label: impl Into<SharedString>, action: Box<dyn Action>) -> Self {
175 self.items.push(ContextMenuItem::Entry {
176 toggled: None,
177 label: label.into(),
178
179 action: Some(action.boxed_clone()),
180 handler: Rc::new(move |_, cx| cx.dispatch_action(action.boxed_clone())),
181 icon: Some(IconName::ArrowUpRight),
182 });
183 self
184 }
185
186 pub fn confirm(&mut self, _: &menu::Confirm, cx: &mut ViewContext<Self>) {
187 let context = self.action_context.as_ref();
188 match self.selected_index.and_then(|ix| self.items.get(ix)) {
189 Some(
190 ContextMenuItem::Entry { handler, .. }
191 | ContextMenuItem::CustomEntry { handler, .. },
192 ) => (handler)(context, cx),
193 _ => {}
194 }
195
196 cx.emit(DismissEvent);
197 }
198
199 pub fn cancel(&mut self, _: &menu::Cancel, cx: &mut ViewContext<Self>) {
200 cx.emit(DismissEvent);
201 cx.emit(DismissEvent);
202 }
203
204 fn select_first(&mut self, _: &SelectFirst, cx: &mut ViewContext<Self>) {
205 self.selected_index = self.items.iter().position(|item| item.is_selectable());
206 cx.notify();
207 }
208
209 pub fn select_last(&mut self) -> Option<usize> {
210 for (ix, item) in self.items.iter().enumerate().rev() {
211 if item.is_selectable() {
212 self.selected_index = Some(ix);
213 return Some(ix);
214 }
215 }
216 None
217 }
218
219 fn handle_select_last(&mut self, _: &SelectLast, cx: &mut ViewContext<Self>) {
220 if self.select_last().is_some() {
221 cx.notify();
222 }
223 }
224
225 fn select_next(&mut self, _: &SelectNext, cx: &mut ViewContext<Self>) {
226 if let Some(ix) = self.selected_index {
227 for (ix, item) in self.items.iter().enumerate().skip(ix + 1) {
228 if item.is_selectable() {
229 self.selected_index = Some(ix);
230 cx.notify();
231 break;
232 }
233 }
234 } else {
235 self.select_first(&Default::default(), cx);
236 }
237 }
238
239 pub fn select_prev(&mut self, _: &SelectPrev, cx: &mut ViewContext<Self>) {
240 if let Some(ix) = self.selected_index {
241 for (ix, item) in self.items.iter().enumerate().take(ix).rev() {
242 if item.is_selectable() {
243 self.selected_index = Some(ix);
244 cx.notify();
245 break;
246 }
247 }
248 } else {
249 self.handle_select_last(&Default::default(), cx);
250 }
251 }
252
253 pub fn on_action_dispatch(&mut self, dispatched: &Box<dyn Action>, cx: &mut ViewContext<Self>) {
254 if self.clicked {
255 cx.propagate();
256 return;
257 }
258
259 if let Some(ix) = self.items.iter().position(|item| {
260 if let ContextMenuItem::Entry {
261 action: Some(action),
262 ..
263 } = item
264 {
265 action.partial_eq(&**dispatched)
266 } else {
267 false
268 }
269 }) {
270 self.selected_index = Some(ix);
271 self.delayed = true;
272 cx.notify();
273 let action = dispatched.boxed_clone();
274 cx.spawn(|this, mut cx| async move {
275 cx.background_executor()
276 .timer(Duration::from_millis(50))
277 .await;
278 this.update(&mut cx, |this, cx| {
279 this.cancel(&menu::Cancel, cx);
280 cx.dispatch_action(action);
281 })
282 })
283 .detach_and_log_err(cx);
284 } else {
285 cx.propagate()
286 }
287 }
288
289 pub fn on_blur_subscription(mut self, new_subscription: Subscription) -> Self {
290 self._on_blur_subscription = new_subscription;
291 self
292 }
293}
294
295impl ContextMenuItem {
296 fn is_selectable(&self) -> bool {
297 match self {
298 ContextMenuItem::Separator => false,
299 ContextMenuItem::Label { .. } => false,
300 ContextMenuItem::Header(_) => false,
301 ContextMenuItem::Entry { .. } => true,
302 ContextMenuItem::CustomEntry { selectable, .. } => *selectable,
303 }
304 }
305}
306
307impl Render for ContextMenu {
308 fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
309 let ui_font_size = ThemeSettings::get_global(cx).ui_font_size;
310
311 div().occlude().elevation_2(cx).flex().flex_row().child(
312 WithRemSize::new(ui_font_size).flex().child(
313 v_flex()
314 .min_w(px(200.))
315 .track_focus(&self.focus_handle)
316 .on_mouse_down_out(cx.listener(|this, _, cx| this.cancel(&menu::Cancel, cx)))
317 .key_context("menu")
318 .on_action(cx.listener(ContextMenu::select_first))
319 .on_action(cx.listener(ContextMenu::handle_select_last))
320 .on_action(cx.listener(ContextMenu::select_next))
321 .on_action(cx.listener(ContextMenu::select_prev))
322 .on_action(cx.listener(ContextMenu::confirm))
323 .on_action(cx.listener(ContextMenu::cancel))
324 .when(!self.delayed, |mut el| {
325 for item in self.items.iter() {
326 if let ContextMenuItem::Entry {
327 action: Some(action),
328 ..
329 } = item
330 {
331 el = el.on_boxed_action(
332 &**action,
333 cx.listener(ContextMenu::on_action_dispatch),
334 );
335 }
336 }
337 el
338 })
339 .flex_none()
340 .child(List::new().children(self.items.iter_mut().enumerate().map(
341 |(ix, item)| {
342 match item {
343 ContextMenuItem::Separator => ListSeparator.into_any_element(),
344 ContextMenuItem::Header(header) => {
345 ListSubHeader::new(header.clone())
346 .inset(true)
347 .into_any_element()
348 }
349 ContextMenuItem::Label(label) => ListItem::new(ix)
350 .inset(true)
351 .disabled(true)
352 .child(Label::new(label.clone()))
353 .into_any_element(),
354 ContextMenuItem::Entry {
355 toggled,
356 label,
357 handler,
358 icon,
359 action,
360 } => {
361 let handler = handler.clone();
362 let menu = cx.view().downgrade();
363
364 let label_element = if let Some(icon) = icon {
365 h_flex()
366 .gap_1()
367 .child(Label::new(label.clone()))
368 .child(Icon::new(*icon).size(IconSize::Small))
369 .into_any_element()
370 } else {
371 Label::new(label.clone()).into_any_element()
372 };
373
374 ListItem::new(ix)
375 .inset(true)
376 .selected(Some(ix) == self.selected_index)
377 .when_some(*toggled, |list_item, toggled| {
378 list_item.start_slot(if toggled {
379 v_flex().flex_none().child(
380 Icon::new(IconName::Check).color(Color::Accent),
381 )
382 } else {
383 v_flex()
384 .flex_none()
385 .size(IconSize::default().rems())
386 })
387 })
388 .child(
389 h_flex()
390 .w_full()
391 .justify_between()
392 .child(label_element)
393 .debug_selector(|| format!("MENU_ITEM-{}", label))
394 .children(action.as_ref().and_then(|action| {
395 self.action_context
396 .as_ref()
397 .map(|focus| {
398 KeyBinding::for_action_in(
399 &**action, focus, cx,
400 )
401 })
402 .unwrap_or_else(|| {
403 KeyBinding::for_action(&**action, cx)
404 })
405 .map(|binding| div().ml_4().child(binding))
406 })),
407 )
408 .on_click({
409 let context = self.action_context.clone();
410 move |_, cx| {
411 handler(context.as_ref(), cx);
412 menu.update(cx, |menu, cx| {
413 menu.clicked = true;
414 cx.emit(DismissEvent);
415 })
416 .ok();
417 }
418 })
419 .into_any_element()
420 }
421 ContextMenuItem::CustomEntry {
422 entry_render,
423 handler,
424 selectable,
425 } => {
426 let handler = handler.clone();
427 let menu = cx.view().downgrade();
428 ListItem::new(ix)
429 .inset(true)
430 .selected(if *selectable {
431 Some(ix) == self.selected_index
432 } else {
433 false
434 })
435 .selectable(*selectable)
436 .on_click({
437 let context = self.action_context.clone();
438 let selectable = *selectable;
439 move |_, cx| {
440 if selectable {
441 handler(context.as_ref(), cx);
442 menu.update(cx, |menu, cx| {
443 menu.clicked = true;
444 cx.emit(DismissEvent);
445 })
446 .ok();
447 }
448 }
449 })
450 .child(entry_render(cx))
451 .into_any_element()
452 }
453 }
454 },
455 ))),
456 ),
457 )
458 }
459}