context_menu.rs

  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
290impl ContextMenuItem {
291    fn is_selectable(&self) -> bool {
292        match self {
293            ContextMenuItem::Separator => false,
294            ContextMenuItem::Label { .. } => false,
295            ContextMenuItem::Header(_) => false,
296            ContextMenuItem::Entry { .. } => true,
297            ContextMenuItem::CustomEntry { selectable, .. } => *selectable,
298        }
299    }
300}
301
302impl Render for ContextMenu {
303    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
304        let ui_font_size = ThemeSettings::get_global(cx).ui_font_size;
305
306        div().occlude().elevation_2(cx).flex().flex_row().child(
307            WithRemSize::new(ui_font_size).flex().child(
308                v_flex()
309                    .min_w(px(200.))
310                    .track_focus(&self.focus_handle)
311                    .on_mouse_down_out(cx.listener(|this, _, cx| this.cancel(&menu::Cancel, cx)))
312                    .key_context("menu")
313                    .on_action(cx.listener(ContextMenu::select_first))
314                    .on_action(cx.listener(ContextMenu::handle_select_last))
315                    .on_action(cx.listener(ContextMenu::select_next))
316                    .on_action(cx.listener(ContextMenu::select_prev))
317                    .on_action(cx.listener(ContextMenu::confirm))
318                    .on_action(cx.listener(ContextMenu::cancel))
319                    .when(!self.delayed, |mut el| {
320                        for item in self.items.iter() {
321                            if let ContextMenuItem::Entry {
322                                action: Some(action),
323                                ..
324                            } = item
325                            {
326                                el = el.on_boxed_action(
327                                    &**action,
328                                    cx.listener(ContextMenu::on_action_dispatch),
329                                );
330                            }
331                        }
332                        el
333                    })
334                    .flex_none()
335                    .child(List::new().children(self.items.iter_mut().enumerate().map(
336                        |(ix, item)| {
337                            match item {
338                                ContextMenuItem::Separator => ListSeparator.into_any_element(),
339                                ContextMenuItem::Header(header) => {
340                                    ListSubHeader::new(header.clone())
341                                        .inset(true)
342                                        .into_any_element()
343                                }
344                                ContextMenuItem::Label(label) => ListItem::new(ix)
345                                    .inset(true)
346                                    .disabled(true)
347                                    .child(Label::new(label.clone()))
348                                    .into_any_element(),
349                                ContextMenuItem::Entry {
350                                    toggled,
351                                    label,
352                                    handler,
353                                    icon,
354                                    action,
355                                } => {
356                                    let handler = handler.clone();
357                                    let menu = cx.view().downgrade();
358
359                                    let label_element = if let Some(icon) = icon {
360                                        h_flex()
361                                            .gap_1()
362                                            .child(Label::new(label.clone()))
363                                            .child(Icon::new(*icon).size(IconSize::Small))
364                                            .into_any_element()
365                                    } else {
366                                        Label::new(label.clone()).into_any_element()
367                                    };
368
369                                    ListItem::new(ix)
370                                        .inset(true)
371                                        .selected(Some(ix) == self.selected_index)
372                                        .when_some(*toggled, |list_item, toggled| {
373                                            list_item.start_slot(if toggled {
374                                                v_flex().flex_none().child(
375                                                    Icon::new(IconName::Check).color(Color::Accent),
376                                                )
377                                            } else {
378                                                v_flex()
379                                                    .flex_none()
380                                                    .size(IconSize::default().rems())
381                                            })
382                                        })
383                                        .child(
384                                            h_flex()
385                                                .w_full()
386                                                .justify_between()
387                                                .child(label_element)
388                                                .debug_selector(|| format!("MENU_ITEM-{}", label))
389                                                .children(action.as_ref().and_then(|action| {
390                                                    self.action_context
391                                                        .as_ref()
392                                                        .map(|focus| {
393                                                            KeyBinding::for_action_in(
394                                                                &**action, focus, cx,
395                                                            )
396                                                        })
397                                                        .unwrap_or_else(|| {
398                                                            KeyBinding::for_action(&**action, cx)
399                                                        })
400                                                        .map(|binding| div().ml_4().child(binding))
401                                                })),
402                                        )
403                                        .on_click({
404                                            let context = self.action_context.clone();
405                                            move |_, cx| {
406                                                handler(context.as_ref(), cx);
407                                                menu.update(cx, |menu, cx| {
408                                                    menu.clicked = true;
409                                                    cx.emit(DismissEvent);
410                                                })
411                                                .ok();
412                                            }
413                                        })
414                                        .into_any_element()
415                                }
416                                ContextMenuItem::CustomEntry {
417                                    entry_render,
418                                    handler,
419                                    selectable,
420                                } => {
421                                    let handler = handler.clone();
422                                    let menu = cx.view().downgrade();
423                                    ListItem::new(ix)
424                                        .inset(true)
425                                        .selected(if *selectable {
426                                            Some(ix) == self.selected_index
427                                        } else {
428                                            false
429                                        })
430                                        .selectable(*selectable)
431                                        .on_click({
432                                            let context = self.action_context.clone();
433                                            let selectable = *selectable;
434                                            move |_, cx| {
435                                                if selectable {
436                                                    handler(context.as_ref(), cx);
437                                                    menu.update(cx, |menu, cx| {
438                                                        menu.clicked = true;
439                                                        cx.emit(DismissEvent);
440                                                    })
441                                                    .ok();
442                                                }
443                                            }
444                                        })
445                                        .child(entry_render(cx))
446                                        .into_any_element()
447                                }
448                            }
449                        },
450                    ))),
451            ),
452        )
453    }
454}