context_menu.rs

   1use crate::{
   2    Icon, IconButtonShape, IconName, IconSize, KeyBinding, Label, List, ListItem, ListSeparator,
   3    ListSubHeader, h_flex, prelude::*, utils::WithRemSize, v_flex,
   4};
   5use gpui::{
   6    Action, AnyElement, App, AppContext as _, DismissEvent, Entity, EventEmitter, FocusHandle,
   7    Focusable, IntoElement, Render, Subscription, px,
   8};
   9use menu::{SelectFirst, SelectLast, SelectNext, SelectPrevious};
  10use settings::Settings;
  11use std::{rc::Rc, time::Duration};
  12use theme::ThemeSettings;
  13
  14use super::Tooltip;
  15
  16pub enum ContextMenuItem {
  17    Separator,
  18    Header(SharedString),
  19    /// title, link_label, link_url
  20    HeaderWithLink(SharedString, SharedString, SharedString), // This could be folded into header
  21    Label(SharedString),
  22    Entry(ContextMenuEntry),
  23    CustomEntry {
  24        entry_render: Box<dyn Fn(&mut Window, &mut App) -> AnyElement>,
  25        handler: Rc<dyn Fn(Option<&FocusHandle>, &mut Window, &mut App)>,
  26        selectable: bool,
  27        documentation_aside: Option<DocumentationAside>,
  28    },
  29}
  30
  31impl ContextMenuItem {
  32    pub fn custom_entry(
  33        entry_render: impl Fn(&mut Window, &mut App) -> AnyElement + 'static,
  34        handler: impl Fn(&mut Window, &mut App) + 'static,
  35        documentation_aside: Option<DocumentationAside>,
  36    ) -> Self {
  37        Self::CustomEntry {
  38            entry_render: Box::new(entry_render),
  39            handler: Rc::new(move |_, window, cx| handler(window, cx)),
  40            selectable: true,
  41            documentation_aside,
  42        }
  43    }
  44}
  45
  46pub struct ContextMenuEntry {
  47    toggle: Option<(IconPosition, bool)>,
  48    label: SharedString,
  49    icon: Option<IconName>,
  50    custom_icon_path: Option<SharedString>,
  51    custom_icon_svg: Option<SharedString>,
  52    icon_position: IconPosition,
  53    icon_size: IconSize,
  54    icon_color: Option<Color>,
  55    handler: Rc<dyn Fn(Option<&FocusHandle>, &mut Window, &mut App)>,
  56    action: Option<Box<dyn Action>>,
  57    disabled: bool,
  58    documentation_aside: Option<DocumentationAside>,
  59    end_slot_icon: Option<IconName>,
  60    end_slot_title: Option<SharedString>,
  61    end_slot_handler: Option<Rc<dyn Fn(Option<&FocusHandle>, &mut Window, &mut App)>>,
  62    show_end_slot_on_hover: bool,
  63}
  64
  65impl ContextMenuEntry {
  66    pub fn new(label: impl Into<SharedString>) -> Self {
  67        ContextMenuEntry {
  68            toggle: None,
  69            label: label.into(),
  70            icon: None,
  71            custom_icon_path: None,
  72            custom_icon_svg: None,
  73            icon_position: IconPosition::Start,
  74            icon_size: IconSize::Small,
  75            icon_color: None,
  76            handler: Rc::new(|_, _, _| {}),
  77            action: None,
  78            disabled: false,
  79            documentation_aside: None,
  80            end_slot_icon: None,
  81            end_slot_title: None,
  82            end_slot_handler: None,
  83            show_end_slot_on_hover: false,
  84        }
  85    }
  86
  87    pub fn toggleable(mut self, toggle_position: IconPosition, toggled: bool) -> Self {
  88        self.toggle = Some((toggle_position, toggled));
  89        self
  90    }
  91
  92    pub fn icon(mut self, icon: IconName) -> Self {
  93        self.icon = Some(icon);
  94        self
  95    }
  96
  97    pub fn custom_icon_path(mut self, path: impl Into<SharedString>) -> Self {
  98        self.custom_icon_path = Some(path.into());
  99        self.custom_icon_svg = None; // Clear other icon sources if custom path is set
 100        self.icon = None;
 101        self
 102    }
 103
 104    pub fn custom_icon_svg(mut self, svg: impl Into<SharedString>) -> Self {
 105        self.custom_icon_svg = Some(svg.into());
 106        self.custom_icon_path = None; // Clear other icon sources if custom path is set
 107        self.icon = None;
 108        self
 109    }
 110
 111    pub fn icon_position(mut self, position: IconPosition) -> Self {
 112        self.icon_position = position;
 113        self
 114    }
 115
 116    pub fn icon_size(mut self, icon_size: IconSize) -> Self {
 117        self.icon_size = icon_size;
 118        self
 119    }
 120
 121    pub fn icon_color(mut self, icon_color: Color) -> Self {
 122        self.icon_color = Some(icon_color);
 123        self
 124    }
 125
 126    pub fn toggle(mut self, toggle_position: IconPosition, toggled: bool) -> Self {
 127        self.toggle = Some((toggle_position, toggled));
 128        self
 129    }
 130
 131    pub fn action(mut self, action: Box<dyn Action>) -> Self {
 132        self.action = Some(action);
 133        self
 134    }
 135
 136    pub fn handler(mut self, handler: impl Fn(&mut Window, &mut App) + 'static) -> Self {
 137        self.handler = Rc::new(move |_, window, cx| handler(window, cx));
 138        self
 139    }
 140
 141    pub fn disabled(mut self, disabled: bool) -> Self {
 142        self.disabled = disabled;
 143        self
 144    }
 145
 146    pub fn documentation_aside(
 147        mut self,
 148        side: DocumentationSide,
 149        edge: DocumentationEdge,
 150        render: impl Fn(&mut App) -> AnyElement + 'static,
 151    ) -> Self {
 152        self.documentation_aside = Some(DocumentationAside {
 153            side,
 154            edge,
 155            render: Rc::new(render),
 156        });
 157
 158        self
 159    }
 160}
 161
 162impl FluentBuilder for ContextMenuEntry {}
 163
 164impl From<ContextMenuEntry> for ContextMenuItem {
 165    fn from(entry: ContextMenuEntry) -> Self {
 166        ContextMenuItem::Entry(entry)
 167    }
 168}
 169
 170pub struct ContextMenu {
 171    builder: Option<Rc<dyn Fn(Self, &mut Window, &mut Context<Self>) -> Self>>,
 172    items: Vec<ContextMenuItem>,
 173    focus_handle: FocusHandle,
 174    action_context: Option<FocusHandle>,
 175    selected_index: Option<usize>,
 176    delayed: bool,
 177    clicked: bool,
 178    end_slot_action: Option<Box<dyn Action>>,
 179    key_context: SharedString,
 180    _on_blur_subscription: Subscription,
 181    keep_open_on_confirm: bool,
 182    documentation_aside: Option<(usize, DocumentationAside)>,
 183    fixed_width: Option<DefiniteLength>,
 184}
 185
 186#[derive(Copy, Clone, PartialEq, Eq)]
 187pub enum DocumentationSide {
 188    Left,
 189    Right,
 190}
 191
 192#[derive(Copy, Default, Clone, PartialEq, Eq)]
 193pub enum DocumentationEdge {
 194    #[default]
 195    Top,
 196    Bottom,
 197}
 198
 199#[derive(Clone)]
 200pub struct DocumentationAside {
 201    pub side: DocumentationSide,
 202    pub edge: DocumentationEdge,
 203    pub render: Rc<dyn Fn(&mut App) -> AnyElement>,
 204}
 205
 206impl DocumentationAside {
 207    pub fn new(
 208        side: DocumentationSide,
 209        edge: DocumentationEdge,
 210        render: Rc<dyn Fn(&mut App) -> AnyElement>,
 211    ) -> Self {
 212        Self { side, edge, render }
 213    }
 214}
 215
 216impl Focusable for ContextMenu {
 217    fn focus_handle(&self, _cx: &App) -> FocusHandle {
 218        self.focus_handle.clone()
 219    }
 220}
 221
 222impl EventEmitter<DismissEvent> for ContextMenu {}
 223
 224impl FluentBuilder for ContextMenu {}
 225
 226impl ContextMenu {
 227    pub fn new(
 228        window: &mut Window,
 229        cx: &mut Context<Self>,
 230        f: impl FnOnce(Self, &mut Window, &mut Context<Self>) -> Self,
 231    ) -> Self {
 232        let focus_handle = cx.focus_handle();
 233        let _on_blur_subscription = cx.on_blur(
 234            &focus_handle,
 235            window,
 236            |this: &mut ContextMenu, window, cx| this.cancel(&menu::Cancel, window, cx),
 237        );
 238        window.refresh();
 239
 240        f(
 241            Self {
 242                builder: None,
 243                items: Default::default(),
 244                focus_handle,
 245                action_context: None,
 246                selected_index: None,
 247                delayed: false,
 248                clicked: false,
 249                key_context: "menu".into(),
 250                _on_blur_subscription,
 251                keep_open_on_confirm: false,
 252                documentation_aside: None,
 253                fixed_width: None,
 254                end_slot_action: None,
 255            },
 256            window,
 257            cx,
 258        )
 259    }
 260
 261    pub fn build(
 262        window: &mut Window,
 263        cx: &mut App,
 264        f: impl FnOnce(Self, &mut Window, &mut Context<Self>) -> Self,
 265    ) -> Entity<Self> {
 266        cx.new(|cx| Self::new(window, cx, f))
 267    }
 268
 269    /// Builds a [`ContextMenu`] that will stay open when making changes instead of closing after each confirmation.
 270    ///
 271    /// The main difference from [`ContextMenu::build`] is the type of the `builder`, as we need to be able to hold onto
 272    /// it to call it again.
 273    pub fn build_persistent(
 274        window: &mut Window,
 275        cx: &mut App,
 276        builder: impl Fn(Self, &mut Window, &mut Context<Self>) -> Self + 'static,
 277    ) -> Entity<Self> {
 278        cx.new(|cx| {
 279            let builder = Rc::new(builder);
 280
 281            let focus_handle = cx.focus_handle();
 282            let _on_blur_subscription = cx.on_blur(
 283                &focus_handle,
 284                window,
 285                |this: &mut ContextMenu, window, cx| this.cancel(&menu::Cancel, window, cx),
 286            );
 287            window.refresh();
 288
 289            (builder.clone())(
 290                Self {
 291                    builder: Some(builder),
 292                    items: Default::default(),
 293                    focus_handle,
 294                    action_context: None,
 295                    selected_index: None,
 296                    delayed: false,
 297                    clicked: false,
 298                    key_context: "menu".into(),
 299                    _on_blur_subscription,
 300                    keep_open_on_confirm: true,
 301                    documentation_aside: None,
 302                    fixed_width: None,
 303                    end_slot_action: None,
 304                },
 305                window,
 306                cx,
 307            )
 308        })
 309    }
 310
 311    /// Rebuilds the menu.
 312    ///
 313    /// This is used to refresh the menu entries when entries are toggled when the menu is configured with
 314    /// `keep_open_on_confirm = true`.
 315    ///
 316    /// This only works if the [`ContextMenu`] was constructed using [`ContextMenu::build_persistent`]. Otherwise it is
 317    /// a no-op.
 318    pub fn rebuild(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 319        let Some(builder) = self.builder.clone() else {
 320            return;
 321        };
 322
 323        // The way we rebuild the menu is a bit of a hack.
 324        let focus_handle = cx.focus_handle();
 325        let new_menu = (builder.clone())(
 326            Self {
 327                builder: Some(builder),
 328                items: Default::default(),
 329                focus_handle: focus_handle.clone(),
 330                action_context: None,
 331                selected_index: None,
 332                delayed: false,
 333                clicked: false,
 334                key_context: "menu".into(),
 335                _on_blur_subscription: cx.on_blur(
 336                    &focus_handle,
 337                    window,
 338                    |this: &mut ContextMenu, window, cx| this.cancel(&menu::Cancel, window, cx),
 339                ),
 340                keep_open_on_confirm: false,
 341                documentation_aside: None,
 342                fixed_width: None,
 343                end_slot_action: None,
 344            },
 345            window,
 346            cx,
 347        );
 348
 349        self.items = new_menu.items;
 350
 351        cx.notify();
 352    }
 353
 354    pub fn context(mut self, focus: FocusHandle) -> Self {
 355        self.action_context = Some(focus);
 356        self
 357    }
 358
 359    pub fn header(mut self, title: impl Into<SharedString>) -> Self {
 360        self.items.push(ContextMenuItem::Header(title.into()));
 361        self
 362    }
 363
 364    pub fn header_with_link(
 365        mut self,
 366        title: impl Into<SharedString>,
 367        link_label: impl Into<SharedString>,
 368        link_url: impl Into<SharedString>,
 369    ) -> Self {
 370        self.items.push(ContextMenuItem::HeaderWithLink(
 371            title.into(),
 372            link_label.into(),
 373            link_url.into(),
 374        ));
 375        self
 376    }
 377
 378    pub fn separator(mut self) -> Self {
 379        self.items.push(ContextMenuItem::Separator);
 380        self
 381    }
 382
 383    pub fn extend<I: Into<ContextMenuItem>>(mut self, items: impl IntoIterator<Item = I>) -> Self {
 384        self.items.extend(items.into_iter().map(Into::into));
 385        self
 386    }
 387
 388    pub fn item(mut self, item: impl Into<ContextMenuItem>) -> Self {
 389        self.items.push(item.into());
 390        self
 391    }
 392
 393    pub fn push_item(&mut self, item: impl Into<ContextMenuItem>) {
 394        self.items.push(item.into());
 395    }
 396
 397    pub fn entry(
 398        mut self,
 399        label: impl Into<SharedString>,
 400        action: Option<Box<dyn Action>>,
 401        handler: impl Fn(&mut Window, &mut App) + 'static,
 402    ) -> Self {
 403        self.items.push(ContextMenuItem::Entry(ContextMenuEntry {
 404            toggle: None,
 405            label: label.into(),
 406            handler: Rc::new(move |_, window, cx| handler(window, cx)),
 407            icon: None,
 408            custom_icon_path: None,
 409            custom_icon_svg: None,
 410            icon_position: IconPosition::End,
 411            icon_size: IconSize::Small,
 412            icon_color: None,
 413            action,
 414            disabled: false,
 415            documentation_aside: None,
 416            end_slot_icon: None,
 417            end_slot_title: None,
 418            end_slot_handler: None,
 419            show_end_slot_on_hover: false,
 420        }));
 421        self
 422    }
 423
 424    pub fn entry_with_end_slot(
 425        mut self,
 426        label: impl Into<SharedString>,
 427        action: Option<Box<dyn Action>>,
 428        handler: impl Fn(&mut Window, &mut App) + 'static,
 429        end_slot_icon: IconName,
 430        end_slot_title: SharedString,
 431        end_slot_handler: impl Fn(&mut Window, &mut App) + 'static,
 432    ) -> Self {
 433        self.items.push(ContextMenuItem::Entry(ContextMenuEntry {
 434            toggle: None,
 435            label: label.into(),
 436            handler: Rc::new(move |_, window, cx| handler(window, cx)),
 437            icon: None,
 438            custom_icon_path: None,
 439            custom_icon_svg: None,
 440            icon_position: IconPosition::End,
 441            icon_size: IconSize::Small,
 442            icon_color: None,
 443            action,
 444            disabled: false,
 445            documentation_aside: None,
 446            end_slot_icon: Some(end_slot_icon),
 447            end_slot_title: Some(end_slot_title),
 448            end_slot_handler: Some(Rc::new(move |_, window, cx| end_slot_handler(window, cx))),
 449            show_end_slot_on_hover: false,
 450        }));
 451        self
 452    }
 453
 454    pub fn entry_with_end_slot_on_hover(
 455        mut self,
 456        label: impl Into<SharedString>,
 457        action: Option<Box<dyn Action>>,
 458        handler: impl Fn(&mut Window, &mut App) + 'static,
 459        end_slot_icon: IconName,
 460        end_slot_title: SharedString,
 461        end_slot_handler: impl Fn(&mut Window, &mut App) + 'static,
 462    ) -> Self {
 463        self.items.push(ContextMenuItem::Entry(ContextMenuEntry {
 464            toggle: None,
 465            label: label.into(),
 466            handler: Rc::new(move |_, window, cx| handler(window, cx)),
 467            icon: None,
 468            custom_icon_path: None,
 469            custom_icon_svg: None,
 470            icon_position: IconPosition::End,
 471            icon_size: IconSize::Small,
 472            icon_color: None,
 473            action,
 474            disabled: false,
 475            documentation_aside: None,
 476            end_slot_icon: Some(end_slot_icon),
 477            end_slot_title: Some(end_slot_title),
 478            end_slot_handler: Some(Rc::new(move |_, window, cx| end_slot_handler(window, cx))),
 479            show_end_slot_on_hover: true,
 480        }));
 481        self
 482    }
 483
 484    pub fn toggleable_entry(
 485        mut self,
 486        label: impl Into<SharedString>,
 487        toggled: bool,
 488        position: IconPosition,
 489        action: Option<Box<dyn Action>>,
 490        handler: impl Fn(&mut Window, &mut App) + 'static,
 491    ) -> Self {
 492        self.items.push(ContextMenuItem::Entry(ContextMenuEntry {
 493            toggle: Some((position, toggled)),
 494            label: label.into(),
 495            handler: Rc::new(move |_, window, cx| handler(window, cx)),
 496            icon: None,
 497            custom_icon_path: None,
 498            custom_icon_svg: None,
 499            icon_position: position,
 500            icon_size: IconSize::Small,
 501            icon_color: None,
 502            action,
 503            disabled: false,
 504            documentation_aside: None,
 505            end_slot_icon: None,
 506            end_slot_title: None,
 507            end_slot_handler: None,
 508            show_end_slot_on_hover: false,
 509        }));
 510        self
 511    }
 512
 513    pub fn custom_row(
 514        mut self,
 515        entry_render: impl Fn(&mut Window, &mut App) -> AnyElement + 'static,
 516    ) -> Self {
 517        self.items.push(ContextMenuItem::CustomEntry {
 518            entry_render: Box::new(entry_render),
 519            handler: Rc::new(|_, _, _| {}),
 520            selectable: false,
 521            documentation_aside: None,
 522        });
 523        self
 524    }
 525
 526    pub fn custom_entry(
 527        mut self,
 528        entry_render: impl Fn(&mut Window, &mut App) -> AnyElement + 'static,
 529        handler: impl Fn(&mut Window, &mut App) + 'static,
 530    ) -> Self {
 531        self.items.push(ContextMenuItem::CustomEntry {
 532            entry_render: Box::new(entry_render),
 533            handler: Rc::new(move |_, window, cx| handler(window, cx)),
 534            selectable: true,
 535            documentation_aside: None,
 536        });
 537        self
 538    }
 539
 540    pub fn label(mut self, label: impl Into<SharedString>) -> Self {
 541        self.items.push(ContextMenuItem::Label(label.into()));
 542        self
 543    }
 544
 545    pub fn action(self, label: impl Into<SharedString>, action: Box<dyn Action>) -> Self {
 546        self.action_checked(label, action, false)
 547    }
 548
 549    pub fn action_checked(
 550        mut self,
 551        label: impl Into<SharedString>,
 552        action: Box<dyn Action>,
 553        checked: bool,
 554    ) -> Self {
 555        self.items.push(ContextMenuItem::Entry(ContextMenuEntry {
 556            toggle: if checked {
 557                Some((IconPosition::Start, true))
 558            } else {
 559                None
 560            },
 561            label: label.into(),
 562            action: Some(action.boxed_clone()),
 563            handler: Rc::new(move |context, window, cx| {
 564                if let Some(context) = &context {
 565                    window.focus(context);
 566                }
 567                window.dispatch_action(action.boxed_clone(), cx);
 568            }),
 569            icon: None,
 570            custom_icon_path: None,
 571            custom_icon_svg: None,
 572            icon_position: IconPosition::End,
 573            icon_size: IconSize::Small,
 574            icon_color: None,
 575            disabled: false,
 576            documentation_aside: None,
 577            end_slot_icon: None,
 578            end_slot_title: None,
 579            end_slot_handler: None,
 580            show_end_slot_on_hover: false,
 581        }));
 582        self
 583    }
 584
 585    pub fn action_disabled_when(
 586        mut self,
 587        disabled: bool,
 588        label: impl Into<SharedString>,
 589        action: Box<dyn Action>,
 590    ) -> Self {
 591        self.items.push(ContextMenuItem::Entry(ContextMenuEntry {
 592            toggle: None,
 593            label: label.into(),
 594            action: Some(action.boxed_clone()),
 595            handler: Rc::new(move |context, window, cx| {
 596                if let Some(context) = &context {
 597                    window.focus(context);
 598                }
 599                window.dispatch_action(action.boxed_clone(), cx);
 600            }),
 601            icon: None,
 602            custom_icon_path: None,
 603            custom_icon_svg: None,
 604            icon_size: IconSize::Small,
 605            icon_position: IconPosition::End,
 606            icon_color: None,
 607            disabled,
 608            documentation_aside: None,
 609            end_slot_icon: None,
 610            end_slot_title: None,
 611            end_slot_handler: None,
 612            show_end_slot_on_hover: false,
 613        }));
 614        self
 615    }
 616
 617    pub fn link(mut self, label: impl Into<SharedString>, action: Box<dyn Action>) -> Self {
 618        self.items.push(ContextMenuItem::Entry(ContextMenuEntry {
 619            toggle: None,
 620            label: label.into(),
 621            action: Some(action.boxed_clone()),
 622            handler: Rc::new(move |_, window, cx| window.dispatch_action(action.boxed_clone(), cx)),
 623            icon: Some(IconName::ArrowUpRight),
 624            custom_icon_path: None,
 625            custom_icon_svg: None,
 626            icon_size: IconSize::XSmall,
 627            icon_position: IconPosition::End,
 628            icon_color: None,
 629            disabled: false,
 630            documentation_aside: None,
 631            end_slot_icon: None,
 632            end_slot_title: None,
 633            end_slot_handler: None,
 634            show_end_slot_on_hover: false,
 635        }));
 636        self
 637    }
 638
 639    pub fn keep_open_on_confirm(mut self, keep_open: bool) -> Self {
 640        self.keep_open_on_confirm = keep_open;
 641        self
 642    }
 643
 644    pub fn trigger_end_slot_handler(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 645        let Some(entry) = self.selected_index.and_then(|ix| self.items.get(ix)) else {
 646            return;
 647        };
 648        let ContextMenuItem::Entry(entry) = entry else {
 649            return;
 650        };
 651        let Some(handler) = entry.end_slot_handler.as_ref() else {
 652            return;
 653        };
 654        handler(None, window, cx);
 655    }
 656
 657    pub fn fixed_width(mut self, width: DefiniteLength) -> Self {
 658        self.fixed_width = Some(width);
 659        self
 660    }
 661
 662    pub fn end_slot_action(mut self, action: Box<dyn Action>) -> Self {
 663        self.end_slot_action = Some(action);
 664        self
 665    }
 666
 667    pub fn key_context(mut self, context: impl Into<SharedString>) -> Self {
 668        self.key_context = context.into();
 669        self
 670    }
 671
 672    pub fn confirm(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
 673        let context = self.action_context.as_ref();
 674        if let Some(
 675            ContextMenuItem::Entry(ContextMenuEntry {
 676                handler,
 677                disabled: false,
 678                ..
 679            })
 680            | ContextMenuItem::CustomEntry { handler, .. },
 681        ) = self.selected_index.and_then(|ix| self.items.get(ix))
 682        {
 683            (handler)(context, window, cx)
 684        }
 685
 686        if self.keep_open_on_confirm {
 687            self.rebuild(window, cx);
 688        } else {
 689            cx.emit(DismissEvent);
 690        }
 691    }
 692
 693    pub fn cancel(&mut self, _: &menu::Cancel, _: &mut Window, cx: &mut Context<Self>) {
 694        cx.emit(DismissEvent);
 695        cx.emit(DismissEvent);
 696    }
 697
 698    pub fn end_slot(&mut self, _: &dyn Action, window: &mut Window, cx: &mut Context<Self>) {
 699        let Some(item) = self.selected_index.and_then(|ix| self.items.get(ix)) else {
 700            return;
 701        };
 702        let ContextMenuItem::Entry(entry) = item else {
 703            return;
 704        };
 705        let Some(handler) = entry.end_slot_handler.as_ref() else {
 706            return;
 707        };
 708        handler(None, window, cx);
 709        self.rebuild(window, cx);
 710        cx.notify();
 711    }
 712
 713    pub fn clear_selected(&mut self) {
 714        self.selected_index = None;
 715    }
 716
 717    pub fn select_first(&mut self, _: &SelectFirst, window: &mut Window, cx: &mut Context<Self>) {
 718        if let Some(ix) = self.items.iter().position(|item| item.is_selectable()) {
 719            self.select_index(ix, window, cx);
 720        }
 721        cx.notify();
 722    }
 723
 724    pub fn select_last(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<usize> {
 725        for (ix, item) in self.items.iter().enumerate().rev() {
 726            if item.is_selectable() {
 727                return self.select_index(ix, window, cx);
 728            }
 729        }
 730        None
 731    }
 732
 733    fn handle_select_last(&mut self, _: &SelectLast, window: &mut Window, cx: &mut Context<Self>) {
 734        if self.select_last(window, cx).is_some() {
 735            cx.notify();
 736        }
 737    }
 738
 739    pub fn select_next(&mut self, _: &SelectNext, window: &mut Window, cx: &mut Context<Self>) {
 740        if let Some(ix) = self.selected_index {
 741            let next_index = ix + 1;
 742            if self.items.len() <= next_index {
 743                self.select_first(&SelectFirst, window, cx);
 744                return;
 745            } else {
 746                for (ix, item) in self.items.iter().enumerate().skip(next_index) {
 747                    if item.is_selectable() {
 748                        self.select_index(ix, window, cx);
 749                        cx.notify();
 750                        return;
 751                    }
 752                }
 753            }
 754        }
 755        self.select_first(&SelectFirst, window, cx);
 756    }
 757
 758    pub fn select_previous(
 759        &mut self,
 760        _: &SelectPrevious,
 761        window: &mut Window,
 762        cx: &mut Context<Self>,
 763    ) {
 764        if let Some(ix) = self.selected_index {
 765            for (ix, item) in self.items.iter().enumerate().take(ix).rev() {
 766                if item.is_selectable() {
 767                    self.select_index(ix, window, cx);
 768                    cx.notify();
 769                    return;
 770                }
 771            }
 772        }
 773        self.handle_select_last(&SelectLast, window, cx);
 774    }
 775
 776    fn select_index(
 777        &mut self,
 778        ix: usize,
 779        _window: &mut Window,
 780        _cx: &mut Context<Self>,
 781    ) -> Option<usize> {
 782        self.documentation_aside = None;
 783        let item = self.items.get(ix)?;
 784        if item.is_selectable() {
 785            self.selected_index = Some(ix);
 786            match item {
 787                ContextMenuItem::Entry(entry) => {
 788                    if let Some(callback) = &entry.documentation_aside {
 789                        self.documentation_aside = Some((ix, callback.clone()));
 790                    }
 791                }
 792                ContextMenuItem::CustomEntry {
 793                    documentation_aside: Some(callback),
 794                    ..
 795                } => {
 796                    self.documentation_aside = Some((ix, callback.clone()));
 797                }
 798                _ => (),
 799            }
 800        }
 801        Some(ix)
 802    }
 803
 804    pub fn on_action_dispatch(
 805        &mut self,
 806        dispatched: &dyn Action,
 807        window: &mut Window,
 808        cx: &mut Context<Self>,
 809    ) {
 810        if self.clicked {
 811            cx.propagate();
 812            return;
 813        }
 814
 815        if let Some(ix) = self.items.iter().position(|item| {
 816            if let ContextMenuItem::Entry(ContextMenuEntry {
 817                action: Some(action),
 818                disabled: false,
 819                ..
 820            }) = item
 821            {
 822                action.partial_eq(dispatched)
 823            } else {
 824                false
 825            }
 826        }) {
 827            self.select_index(ix, window, cx);
 828            self.delayed = true;
 829            cx.notify();
 830            let action = dispatched.boxed_clone();
 831            cx.spawn_in(window, async move |this, cx| {
 832                cx.background_executor()
 833                    .timer(Duration::from_millis(50))
 834                    .await;
 835                cx.update(|window, cx| {
 836                    this.update(cx, |this, cx| {
 837                        this.cancel(&menu::Cancel, window, cx);
 838                        window.dispatch_action(action, cx);
 839                    })
 840                })
 841            })
 842            .detach_and_log_err(cx);
 843        } else {
 844            cx.propagate()
 845        }
 846    }
 847
 848    pub fn on_blur_subscription(mut self, new_subscription: Subscription) -> Self {
 849        self._on_blur_subscription = new_subscription;
 850        self
 851    }
 852
 853    fn render_menu_item(
 854        &self,
 855        ix: usize,
 856        item: &ContextMenuItem,
 857        window: &mut Window,
 858        cx: &mut Context<Self>,
 859    ) -> impl IntoElement + use<> {
 860        match item {
 861            ContextMenuItem::Separator => ListSeparator.into_any_element(),
 862            ContextMenuItem::Header(header) => ListSubHeader::new(header.clone())
 863                .inset(true)
 864                .into_any_element(),
 865            ContextMenuItem::HeaderWithLink(header, label, url) => {
 866                let url = url.clone();
 867                let link_id = ElementId::Name(format!("link-{}", url).into());
 868                ListSubHeader::new(header.clone())
 869                    .inset(true)
 870                    .end_slot(
 871                        Button::new(link_id, label.clone())
 872                            .color(Color::Muted)
 873                            .label_size(LabelSize::Small)
 874                            .size(ButtonSize::None)
 875                            .style(ButtonStyle::Transparent)
 876                            .on_click(move |_, _, cx| {
 877                                let url = url.clone();
 878                                cx.open_url(&url);
 879                            })
 880                            .into_any_element(),
 881                    )
 882                    .into_any_element()
 883            }
 884            ContextMenuItem::Label(label) => ListItem::new(ix)
 885                .inset(true)
 886                .disabled(true)
 887                .child(Label::new(label.clone()))
 888                .into_any_element(),
 889            ContextMenuItem::Entry(entry) => {
 890                self.render_menu_entry(ix, entry, cx).into_any_element()
 891            }
 892            ContextMenuItem::CustomEntry {
 893                entry_render,
 894                handler,
 895                selectable,
 896                ..
 897            } => {
 898                let handler = handler.clone();
 899                let menu = cx.entity().downgrade();
 900                let selectable = *selectable;
 901                ListItem::new(ix)
 902                    .inset(true)
 903                    .toggle_state(if selectable {
 904                        Some(ix) == self.selected_index
 905                    } else {
 906                        false
 907                    })
 908                    .selectable(selectable)
 909                    .when(selectable, |item| {
 910                        item.on_click({
 911                            let context = self.action_context.clone();
 912                            let keep_open_on_confirm = self.keep_open_on_confirm;
 913                            move |_, window, cx| {
 914                                handler(context.as_ref(), window, cx);
 915                                menu.update(cx, |menu, cx| {
 916                                    menu.clicked = true;
 917
 918                                    if keep_open_on_confirm {
 919                                        menu.rebuild(window, cx);
 920                                    } else {
 921                                        cx.emit(DismissEvent);
 922                                    }
 923                                })
 924                                .ok();
 925                            }
 926                        })
 927                    })
 928                    .child(entry_render(window, cx))
 929                    .into_any_element()
 930            }
 931        }
 932    }
 933
 934    fn render_menu_entry(
 935        &self,
 936        ix: usize,
 937        entry: &ContextMenuEntry,
 938        cx: &mut Context<Self>,
 939    ) -> impl IntoElement {
 940        let ContextMenuEntry {
 941            toggle,
 942            label,
 943            handler,
 944            icon,
 945            custom_icon_path,
 946            custom_icon_svg,
 947            icon_position,
 948            icon_size,
 949            icon_color,
 950            action,
 951            disabled,
 952            documentation_aside,
 953            end_slot_icon,
 954            end_slot_title,
 955            end_slot_handler,
 956            show_end_slot_on_hover,
 957        } = entry;
 958        let this = cx.weak_entity();
 959
 960        let handler = handler.clone();
 961        let menu = cx.entity().downgrade();
 962
 963        let icon_color = if *disabled {
 964            Color::Muted
 965        } else if toggle.is_some() {
 966            icon_color.unwrap_or(Color::Accent)
 967        } else {
 968            icon_color.unwrap_or(Color::Default)
 969        };
 970
 971        let label_color = if *disabled {
 972            Color::Disabled
 973        } else {
 974            Color::Default
 975        };
 976
 977        let label_element = if let Some(custom_path) = custom_icon_path {
 978            h_flex()
 979                .gap_1p5()
 980                .when(
 981                    *icon_position == IconPosition::Start && toggle.is_none(),
 982                    |flex| {
 983                        flex.child(
 984                            Icon::from_path(custom_path.clone())
 985                                .size(*icon_size)
 986                                .color(icon_color),
 987                        )
 988                    },
 989                )
 990                .child(Label::new(label.clone()).color(label_color).truncate())
 991                .when(*icon_position == IconPosition::End, |flex| {
 992                    flex.child(
 993                        Icon::from_path(custom_path.clone())
 994                            .size(*icon_size)
 995                            .color(icon_color),
 996                    )
 997                })
 998                .into_any_element()
 999        } else if let Some(custom_icon_svg) = custom_icon_svg {
1000            h_flex()
1001                .gap_1p5()
1002                .when(
1003                    *icon_position == IconPosition::Start && toggle.is_none(),
1004                    |flex| {
1005                        flex.child(
1006                            Icon::from_external_svg(custom_icon_svg.clone())
1007                                .size(*icon_size)
1008                                .color(icon_color),
1009                        )
1010                    },
1011                )
1012                .child(Label::new(label.clone()).color(label_color).truncate())
1013                .when(*icon_position == IconPosition::End, |flex| {
1014                    flex.child(
1015                        Icon::from_external_svg(custom_icon_svg.clone())
1016                            .size(*icon_size)
1017                            .color(icon_color),
1018                    )
1019                })
1020                .into_any_element()
1021        } else if let Some(icon_name) = icon {
1022            h_flex()
1023                .gap_1p5()
1024                .when(
1025                    *icon_position == IconPosition::Start && toggle.is_none(),
1026                    |flex| flex.child(Icon::new(*icon_name).size(*icon_size).color(icon_color)),
1027                )
1028                .child(Label::new(label.clone()).color(label_color).truncate())
1029                .when(*icon_position == IconPosition::End, |flex| {
1030                    flex.child(Icon::new(*icon_name).size(*icon_size).color(icon_color))
1031                })
1032                .into_any_element()
1033        } else {
1034            Label::new(label.clone())
1035                .color(label_color)
1036                .truncate()
1037                .into_any_element()
1038        };
1039
1040        div()
1041            .id(("context-menu-child", ix))
1042            .when_some(documentation_aside.clone(), |this, documentation_aside| {
1043                this.occlude()
1044                    .on_hover(cx.listener(move |menu, hovered, _, cx| {
1045                        if *hovered {
1046                            menu.documentation_aside = Some((ix, documentation_aside.clone()));
1047                        } else if matches!(menu.documentation_aside, Some((id, _)) if id == ix) {
1048                            menu.documentation_aside = None;
1049                        }
1050                        cx.notify();
1051                    }))
1052            })
1053            .child(
1054                ListItem::new(ix)
1055                    .group_name("label_container")
1056                    .inset(true)
1057                    .disabled(*disabled)
1058                    .toggle_state(Some(ix) == self.selected_index)
1059                    .when_some(*toggle, |list_item, (position, toggled)| {
1060                        let contents = div()
1061                            .flex_none()
1062                            .child(
1063                                Icon::new(icon.unwrap_or(IconName::Check))
1064                                    .color(icon_color)
1065                                    .size(*icon_size),
1066                            )
1067                            .when(!toggled, |contents| contents.invisible());
1068
1069                        match position {
1070                            IconPosition::Start => list_item.start_slot(contents),
1071                            IconPosition::End => list_item.end_slot(contents),
1072                        }
1073                    })
1074                    .child(
1075                        h_flex()
1076                            .w_full()
1077                            .justify_between()
1078                            .child(label_element)
1079                            .debug_selector(|| format!("MENU_ITEM-{}", label))
1080                            .children(action.as_ref().map(|action| {
1081                                let binding = self
1082                                    .action_context
1083                                    .as_ref()
1084                                    .map(|focus| KeyBinding::for_action_in(&**action, focus, cx))
1085                                    .unwrap_or_else(|| KeyBinding::for_action(&**action, cx));
1086
1087                                div()
1088                                    .ml_4()
1089                                    .child(binding.disabled(*disabled))
1090                                    .when(*disabled && documentation_aside.is_some(), |parent| {
1091                                        parent.invisible()
1092                                    })
1093                            }))
1094                            .when(*disabled && documentation_aside.is_some(), |parent| {
1095                                parent.child(
1096                                    Icon::new(IconName::Info)
1097                                        .size(IconSize::XSmall)
1098                                        .color(Color::Muted),
1099                                )
1100                            }),
1101                    )
1102                    .when_some(
1103                        end_slot_icon
1104                            .as_ref()
1105                            .zip(self.end_slot_action.as_ref())
1106                            .zip(end_slot_title.as_ref())
1107                            .zip(end_slot_handler.as_ref()),
1108                        |el, (((icon, action), title), handler)| {
1109                            el.end_slot({
1110                                let icon_button = IconButton::new("end-slot-icon", *icon)
1111                                    .shape(IconButtonShape::Square)
1112                                    .tooltip({
1113                                        let action_context = self.action_context.clone();
1114                                        let title = title.clone();
1115                                        let action = action.boxed_clone();
1116                                        move |_window, cx| {
1117                                            action_context
1118                                                .as_ref()
1119                                                .map(|focus| {
1120                                                    Tooltip::for_action_in(
1121                                                        title.clone(),
1122                                                        &*action,
1123                                                        focus,
1124                                                        cx,
1125                                                    )
1126                                                })
1127                                                .unwrap_or_else(|| {
1128                                                    Tooltip::for_action(title.clone(), &*action, cx)
1129                                                })
1130                                        }
1131                                    })
1132                                    .on_click({
1133                                        let handler = handler.clone();
1134                                        move |_, window, cx| {
1135                                            handler(None, window, cx);
1136                                            this.update(cx, |this, cx| {
1137                                                this.rebuild(window, cx);
1138                                                cx.notify();
1139                                            })
1140                                            .ok();
1141                                        }
1142                                    });
1143
1144                                if *show_end_slot_on_hover {
1145                                    div()
1146                                        .visible_on_hover("label_container")
1147                                        .child(icon_button)
1148                                        .into_any_element()
1149                                } else {
1150                                    icon_button.into_any_element()
1151                                }
1152                            })
1153                        },
1154                    )
1155                    .on_click({
1156                        let context = self.action_context.clone();
1157                        let keep_open_on_confirm = self.keep_open_on_confirm;
1158                        move |_, window, cx| {
1159                            handler(context.as_ref(), window, cx);
1160                            menu.update(cx, |menu, cx| {
1161                                menu.clicked = true;
1162                                if keep_open_on_confirm {
1163                                    menu.rebuild(window, cx);
1164                                } else {
1165                                    cx.emit(DismissEvent);
1166                                }
1167                            })
1168                            .ok();
1169                        }
1170                    }),
1171            )
1172            .into_any_element()
1173    }
1174}
1175
1176impl ContextMenuItem {
1177    fn is_selectable(&self) -> bool {
1178        match self {
1179            ContextMenuItem::Header(_)
1180            | ContextMenuItem::HeaderWithLink(_, _, _)
1181            | ContextMenuItem::Separator
1182            | ContextMenuItem::Label { .. } => false,
1183            ContextMenuItem::Entry(ContextMenuEntry { disabled, .. }) => !disabled,
1184            ContextMenuItem::CustomEntry { selectable, .. } => *selectable,
1185        }
1186    }
1187}
1188
1189impl Render for ContextMenu {
1190    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1191        let ui_font_size = ThemeSettings::get_global(cx).ui_font_size(cx);
1192        let window_size = window.viewport_size();
1193        let rem_size = window.rem_size();
1194        let is_wide_window = window_size.width / rem_size > rems_from_px(800.).0;
1195
1196        let aside = self.documentation_aside.clone();
1197        let render_aside = |aside: DocumentationAside, cx: &mut Context<Self>| {
1198            WithRemSize::new(ui_font_size)
1199                .occlude()
1200                .elevation_2(cx)
1201                .w_full()
1202                .p_2()
1203                .overflow_hidden()
1204                .when(is_wide_window, |this| this.max_w_96())
1205                .when(!is_wide_window, |this| this.max_w_48())
1206                .child((aside.render)(cx))
1207        };
1208
1209        let render_menu =
1210            |cx: &mut Context<Self>, window: &mut Window| {
1211                WithRemSize::new(ui_font_size)
1212                    .occlude()
1213                    .elevation_2(cx)
1214                    .flex()
1215                    .flex_row()
1216                    .flex_shrink_0()
1217                    .child(
1218                        v_flex()
1219                            .id("context-menu")
1220                            .max_h(vh(0.75, window))
1221                            .flex_shrink_0()
1222                            .when_some(self.fixed_width, |this, width| {
1223                                this.w(width).overflow_x_hidden()
1224                            })
1225                            .when(self.fixed_width.is_none(), |this| {
1226                                this.min_w(px(200.)).flex_1()
1227                            })
1228                            .overflow_y_scroll()
1229                            .track_focus(&self.focus_handle(cx))
1230                            .on_mouse_down_out(cx.listener(|this, _, window, cx| {
1231                                this.cancel(&menu::Cancel, window, cx)
1232                            }))
1233                            .key_context(self.key_context.as_ref())
1234                            .on_action(cx.listener(ContextMenu::select_first))
1235                            .on_action(cx.listener(ContextMenu::handle_select_last))
1236                            .on_action(cx.listener(ContextMenu::select_next))
1237                            .on_action(cx.listener(ContextMenu::select_previous))
1238                            .on_action(cx.listener(ContextMenu::confirm))
1239                            .on_action(cx.listener(ContextMenu::cancel))
1240                            .when_some(self.end_slot_action.as_ref(), |el, action| {
1241                                el.on_boxed_action(&**action, cx.listener(ContextMenu::end_slot))
1242                            })
1243                            .when(!self.delayed, |mut el| {
1244                                for item in self.items.iter() {
1245                                    if let ContextMenuItem::Entry(ContextMenuEntry {
1246                                        action: Some(action),
1247                                        disabled: false,
1248                                        ..
1249                                    }) = item
1250                                    {
1251                                        el = el.on_boxed_action(
1252                                            &**action,
1253                                            cx.listener(ContextMenu::on_action_dispatch),
1254                                        );
1255                                    }
1256                                }
1257                                el
1258                            })
1259                            .child(
1260                                List::new().children(
1261                                    self.items.iter().enumerate().map(|(ix, item)| {
1262                                        self.render_menu_item(ix, item, window, cx)
1263                                    }),
1264                                ),
1265                            ),
1266                    )
1267            };
1268
1269        if is_wide_window {
1270            div()
1271                .relative()
1272                .child(render_menu(cx, window))
1273                .children(aside.map(|(_item_index, aside)| {
1274                    h_flex()
1275                        .absolute()
1276                        .when(aside.side == DocumentationSide::Left, |this| {
1277                            this.right_full().mr_1()
1278                        })
1279                        .when(aside.side == DocumentationSide::Right, |this| {
1280                            this.left_full().ml_1()
1281                        })
1282                        .when(aside.edge == DocumentationEdge::Top, |this| this.top_0())
1283                        .when(aside.edge == DocumentationEdge::Bottom, |this| {
1284                            this.bottom_0()
1285                        })
1286                        .child(render_aside(aside, cx))
1287                }))
1288        } else {
1289            v_flex()
1290                .w_full()
1291                .gap_1()
1292                .justify_end()
1293                .children(aside.map(|(_, aside)| render_aside(aside, cx)))
1294                .child(render_menu(cx, window))
1295        }
1296    }
1297}
1298
1299#[cfg(test)]
1300mod tests {
1301    use gpui::TestAppContext;
1302
1303    use super::*;
1304
1305    #[gpui::test]
1306    fn can_navigate_back_over_headers(cx: &mut TestAppContext) {
1307        let cx = cx.add_empty_window();
1308        let context_menu = cx.update(|window, cx| {
1309            ContextMenu::build(window, cx, |menu, _, _| {
1310                menu.header("First header")
1311                    .separator()
1312                    .entry("First entry", None, |_, _| {})
1313                    .separator()
1314                    .separator()
1315                    .entry("Last entry", None, |_, _| {})
1316                    .header("Last header")
1317            })
1318        });
1319
1320        context_menu.update_in(cx, |context_menu, window, cx| {
1321            assert_eq!(
1322                None, context_menu.selected_index,
1323                "No selection is in the menu initially"
1324            );
1325
1326            context_menu.select_first(&SelectFirst, window, cx);
1327            assert_eq!(
1328                Some(2),
1329                context_menu.selected_index,
1330                "Should select first selectable entry, skipping the header and the separator"
1331            );
1332
1333            context_menu.select_next(&SelectNext, window, cx);
1334            assert_eq!(
1335                Some(5),
1336                context_menu.selected_index,
1337                "Should select next selectable entry, skipping 2 separators along the way"
1338            );
1339
1340            context_menu.select_next(&SelectNext, window, cx);
1341            assert_eq!(
1342                Some(2),
1343                context_menu.selected_index,
1344                "Should wrap around to first selectable entry"
1345            );
1346        });
1347
1348        context_menu.update_in(cx, |context_menu, window, cx| {
1349            assert_eq!(
1350                Some(2),
1351                context_menu.selected_index,
1352                "Should start from the first selectable entry"
1353            );
1354
1355            context_menu.select_previous(&SelectPrevious, window, cx);
1356            assert_eq!(
1357                Some(5),
1358                context_menu.selected_index,
1359                "Should wrap around to previous selectable entry (last)"
1360            );
1361
1362            context_menu.select_previous(&SelectPrevious, window, cx);
1363            assert_eq!(
1364                Some(2),
1365                context_menu.selected_index,
1366                "Should go back to previous selectable entry (first)"
1367            );
1368        });
1369
1370        context_menu.update_in(cx, |context_menu, window, cx| {
1371            context_menu.select_first(&SelectFirst, window, cx);
1372            assert_eq!(
1373                Some(2),
1374                context_menu.selected_index,
1375                "Should start from the first selectable entry"
1376            );
1377
1378            context_menu.select_previous(&SelectPrevious, window, cx);
1379            assert_eq!(
1380                Some(5),
1381                context_menu.selected_index,
1382                "Should wrap around to last selectable entry"
1383            );
1384            context_menu.select_next(&SelectNext, window, cx);
1385            assert_eq!(
1386                Some(2),
1387                context_menu.selected_index,
1388                "Should wrap around to first selectable entry"
1389            );
1390        });
1391    }
1392}