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(mut self, label: impl Into<SharedString>, action: Box<dyn Action>) -> Self {
 546        self.items.push(ContextMenuItem::Entry(ContextMenuEntry {
 547            toggle: None,
 548            label: label.into(),
 549            action: Some(action.boxed_clone()),
 550            handler: Rc::new(move |context, window, cx| {
 551                if let Some(context) = &context {
 552                    window.focus(context);
 553                }
 554                window.dispatch_action(action.boxed_clone(), cx);
 555            }),
 556            icon: None,
 557            custom_icon_path: None,
 558            custom_icon_svg: None,
 559            icon_position: IconPosition::End,
 560            icon_size: IconSize::Small,
 561            icon_color: None,
 562            disabled: false,
 563            documentation_aside: None,
 564            end_slot_icon: None,
 565            end_slot_title: None,
 566            end_slot_handler: None,
 567            show_end_slot_on_hover: false,
 568        }));
 569        self
 570    }
 571
 572    pub fn action_disabled_when(
 573        mut self,
 574        disabled: bool,
 575        label: impl Into<SharedString>,
 576        action: Box<dyn Action>,
 577    ) -> Self {
 578        self.items.push(ContextMenuItem::Entry(ContextMenuEntry {
 579            toggle: None,
 580            label: label.into(),
 581            action: Some(action.boxed_clone()),
 582            handler: Rc::new(move |context, window, cx| {
 583                if let Some(context) = &context {
 584                    window.focus(context);
 585                }
 586                window.dispatch_action(action.boxed_clone(), cx);
 587            }),
 588            icon: None,
 589            custom_icon_path: None,
 590            custom_icon_svg: None,
 591            icon_size: IconSize::Small,
 592            icon_position: IconPosition::End,
 593            icon_color: None,
 594            disabled,
 595            documentation_aside: None,
 596            end_slot_icon: None,
 597            end_slot_title: None,
 598            end_slot_handler: None,
 599            show_end_slot_on_hover: false,
 600        }));
 601        self
 602    }
 603
 604    pub fn link(mut self, label: impl Into<SharedString>, action: Box<dyn Action>) -> Self {
 605        self.items.push(ContextMenuItem::Entry(ContextMenuEntry {
 606            toggle: None,
 607            label: label.into(),
 608            action: Some(action.boxed_clone()),
 609            handler: Rc::new(move |_, window, cx| window.dispatch_action(action.boxed_clone(), cx)),
 610            icon: Some(IconName::ArrowUpRight),
 611            custom_icon_path: None,
 612            custom_icon_svg: None,
 613            icon_size: IconSize::XSmall,
 614            icon_position: IconPosition::End,
 615            icon_color: None,
 616            disabled: false,
 617            documentation_aside: None,
 618            end_slot_icon: None,
 619            end_slot_title: None,
 620            end_slot_handler: None,
 621            show_end_slot_on_hover: false,
 622        }));
 623        self
 624    }
 625
 626    pub fn keep_open_on_confirm(mut self, keep_open: bool) -> Self {
 627        self.keep_open_on_confirm = keep_open;
 628        self
 629    }
 630
 631    pub fn trigger_end_slot_handler(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 632        let Some(entry) = self.selected_index.and_then(|ix| self.items.get(ix)) else {
 633            return;
 634        };
 635        let ContextMenuItem::Entry(entry) = entry else {
 636            return;
 637        };
 638        let Some(handler) = entry.end_slot_handler.as_ref() else {
 639            return;
 640        };
 641        handler(None, window, cx);
 642    }
 643
 644    pub fn fixed_width(mut self, width: DefiniteLength) -> Self {
 645        self.fixed_width = Some(width);
 646        self
 647    }
 648
 649    pub fn end_slot_action(mut self, action: Box<dyn Action>) -> Self {
 650        self.end_slot_action = Some(action);
 651        self
 652    }
 653
 654    pub fn key_context(mut self, context: impl Into<SharedString>) -> Self {
 655        self.key_context = context.into();
 656        self
 657    }
 658
 659    pub fn confirm(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
 660        let context = self.action_context.as_ref();
 661        if let Some(
 662            ContextMenuItem::Entry(ContextMenuEntry {
 663                handler,
 664                disabled: false,
 665                ..
 666            })
 667            | ContextMenuItem::CustomEntry { handler, .. },
 668        ) = self.selected_index.and_then(|ix| self.items.get(ix))
 669        {
 670            (handler)(context, window, cx)
 671        }
 672
 673        if self.keep_open_on_confirm {
 674            self.rebuild(window, cx);
 675        } else {
 676            cx.emit(DismissEvent);
 677        }
 678    }
 679
 680    pub fn cancel(&mut self, _: &menu::Cancel, _: &mut Window, cx: &mut Context<Self>) {
 681        cx.emit(DismissEvent);
 682        cx.emit(DismissEvent);
 683    }
 684
 685    pub fn end_slot(&mut self, _: &dyn Action, window: &mut Window, cx: &mut Context<Self>) {
 686        let Some(item) = self.selected_index.and_then(|ix| self.items.get(ix)) else {
 687            return;
 688        };
 689        let ContextMenuItem::Entry(entry) = item else {
 690            return;
 691        };
 692        let Some(handler) = entry.end_slot_handler.as_ref() else {
 693            return;
 694        };
 695        handler(None, window, cx);
 696        self.rebuild(window, cx);
 697        cx.notify();
 698    }
 699
 700    pub fn clear_selected(&mut self) {
 701        self.selected_index = None;
 702    }
 703
 704    pub fn select_first(&mut self, _: &SelectFirst, window: &mut Window, cx: &mut Context<Self>) {
 705        if let Some(ix) = self.items.iter().position(|item| item.is_selectable()) {
 706            self.select_index(ix, window, cx);
 707        }
 708        cx.notify();
 709    }
 710
 711    pub fn select_last(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<usize> {
 712        for (ix, item) in self.items.iter().enumerate().rev() {
 713            if item.is_selectable() {
 714                return self.select_index(ix, window, cx);
 715            }
 716        }
 717        None
 718    }
 719
 720    fn handle_select_last(&mut self, _: &SelectLast, window: &mut Window, cx: &mut Context<Self>) {
 721        if self.select_last(window, cx).is_some() {
 722            cx.notify();
 723        }
 724    }
 725
 726    pub fn select_next(&mut self, _: &SelectNext, window: &mut Window, cx: &mut Context<Self>) {
 727        if let Some(ix) = self.selected_index {
 728            let next_index = ix + 1;
 729            if self.items.len() <= next_index {
 730                self.select_first(&SelectFirst, window, cx);
 731                return;
 732            } else {
 733                for (ix, item) in self.items.iter().enumerate().skip(next_index) {
 734                    if item.is_selectable() {
 735                        self.select_index(ix, window, cx);
 736                        cx.notify();
 737                        return;
 738                    }
 739                }
 740            }
 741        }
 742        self.select_first(&SelectFirst, window, cx);
 743    }
 744
 745    pub fn select_previous(
 746        &mut self,
 747        _: &SelectPrevious,
 748        window: &mut Window,
 749        cx: &mut Context<Self>,
 750    ) {
 751        if let Some(ix) = self.selected_index {
 752            for (ix, item) in self.items.iter().enumerate().take(ix).rev() {
 753                if item.is_selectable() {
 754                    self.select_index(ix, window, cx);
 755                    cx.notify();
 756                    return;
 757                }
 758            }
 759        }
 760        self.handle_select_last(&SelectLast, window, cx);
 761    }
 762
 763    fn select_index(
 764        &mut self,
 765        ix: usize,
 766        _window: &mut Window,
 767        _cx: &mut Context<Self>,
 768    ) -> Option<usize> {
 769        self.documentation_aside = None;
 770        let item = self.items.get(ix)?;
 771        if item.is_selectable() {
 772            self.selected_index = Some(ix);
 773            match item {
 774                ContextMenuItem::Entry(entry) => {
 775                    if let Some(callback) = &entry.documentation_aside {
 776                        self.documentation_aside = Some((ix, callback.clone()));
 777                    }
 778                }
 779                ContextMenuItem::CustomEntry {
 780                    documentation_aside: Some(callback),
 781                    ..
 782                } => {
 783                    self.documentation_aside = Some((ix, callback.clone()));
 784                }
 785                _ => (),
 786            }
 787        }
 788        Some(ix)
 789    }
 790
 791    pub fn on_action_dispatch(
 792        &mut self,
 793        dispatched: &dyn Action,
 794        window: &mut Window,
 795        cx: &mut Context<Self>,
 796    ) {
 797        if self.clicked {
 798            cx.propagate();
 799            return;
 800        }
 801
 802        if let Some(ix) = self.items.iter().position(|item| {
 803            if let ContextMenuItem::Entry(ContextMenuEntry {
 804                action: Some(action),
 805                disabled: false,
 806                ..
 807            }) = item
 808            {
 809                action.partial_eq(dispatched)
 810            } else {
 811                false
 812            }
 813        }) {
 814            self.select_index(ix, window, cx);
 815            self.delayed = true;
 816            cx.notify();
 817            let action = dispatched.boxed_clone();
 818            cx.spawn_in(window, async move |this, cx| {
 819                cx.background_executor()
 820                    .timer(Duration::from_millis(50))
 821                    .await;
 822                cx.update(|window, cx| {
 823                    this.update(cx, |this, cx| {
 824                        this.cancel(&menu::Cancel, window, cx);
 825                        window.dispatch_action(action, cx);
 826                    })
 827                })
 828            })
 829            .detach_and_log_err(cx);
 830        } else {
 831            cx.propagate()
 832        }
 833    }
 834
 835    pub fn on_blur_subscription(mut self, new_subscription: Subscription) -> Self {
 836        self._on_blur_subscription = new_subscription;
 837        self
 838    }
 839
 840    fn render_menu_item(
 841        &self,
 842        ix: usize,
 843        item: &ContextMenuItem,
 844        window: &mut Window,
 845        cx: &mut Context<Self>,
 846    ) -> impl IntoElement + use<> {
 847        match item {
 848            ContextMenuItem::Separator => ListSeparator.into_any_element(),
 849            ContextMenuItem::Header(header) => ListSubHeader::new(header.clone())
 850                .inset(true)
 851                .into_any_element(),
 852            ContextMenuItem::HeaderWithLink(header, label, url) => {
 853                let url = url.clone();
 854                let link_id = ElementId::Name(format!("link-{}", url).into());
 855                ListSubHeader::new(header.clone())
 856                    .inset(true)
 857                    .end_slot(
 858                        Button::new(link_id, label.clone())
 859                            .color(Color::Muted)
 860                            .label_size(LabelSize::Small)
 861                            .size(ButtonSize::None)
 862                            .style(ButtonStyle::Transparent)
 863                            .on_click(move |_, _, cx| {
 864                                let url = url.clone();
 865                                cx.open_url(&url);
 866                            })
 867                            .into_any_element(),
 868                    )
 869                    .into_any_element()
 870            }
 871            ContextMenuItem::Label(label) => ListItem::new(ix)
 872                .inset(true)
 873                .disabled(true)
 874                .child(Label::new(label.clone()))
 875                .into_any_element(),
 876            ContextMenuItem::Entry(entry) => {
 877                self.render_menu_entry(ix, entry, cx).into_any_element()
 878            }
 879            ContextMenuItem::CustomEntry {
 880                entry_render,
 881                handler,
 882                selectable,
 883                ..
 884            } => {
 885                let handler = handler.clone();
 886                let menu = cx.entity().downgrade();
 887                let selectable = *selectable;
 888                ListItem::new(ix)
 889                    .inset(true)
 890                    .toggle_state(if selectable {
 891                        Some(ix) == self.selected_index
 892                    } else {
 893                        false
 894                    })
 895                    .selectable(selectable)
 896                    .when(selectable, |item| {
 897                        item.on_click({
 898                            let context = self.action_context.clone();
 899                            let keep_open_on_confirm = self.keep_open_on_confirm;
 900                            move |_, window, cx| {
 901                                handler(context.as_ref(), window, cx);
 902                                menu.update(cx, |menu, cx| {
 903                                    menu.clicked = true;
 904
 905                                    if keep_open_on_confirm {
 906                                        menu.rebuild(window, cx);
 907                                    } else {
 908                                        cx.emit(DismissEvent);
 909                                    }
 910                                })
 911                                .ok();
 912                            }
 913                        })
 914                    })
 915                    .child(entry_render(window, cx))
 916                    .into_any_element()
 917            }
 918        }
 919    }
 920
 921    fn render_menu_entry(
 922        &self,
 923        ix: usize,
 924        entry: &ContextMenuEntry,
 925        cx: &mut Context<Self>,
 926    ) -> impl IntoElement {
 927        let ContextMenuEntry {
 928            toggle,
 929            label,
 930            handler,
 931            icon,
 932            custom_icon_path,
 933            custom_icon_svg,
 934            icon_position,
 935            icon_size,
 936            icon_color,
 937            action,
 938            disabled,
 939            documentation_aside,
 940            end_slot_icon,
 941            end_slot_title,
 942            end_slot_handler,
 943            show_end_slot_on_hover,
 944        } = entry;
 945        let this = cx.weak_entity();
 946
 947        let handler = handler.clone();
 948        let menu = cx.entity().downgrade();
 949
 950        let icon_color = if *disabled {
 951            Color::Muted
 952        } else if toggle.is_some() {
 953            icon_color.unwrap_or(Color::Accent)
 954        } else {
 955            icon_color.unwrap_or(Color::Default)
 956        };
 957
 958        let label_color = if *disabled {
 959            Color::Disabled
 960        } else {
 961            Color::Default
 962        };
 963
 964        let label_element = if let Some(custom_path) = custom_icon_path {
 965            h_flex()
 966                .gap_1p5()
 967                .when(
 968                    *icon_position == IconPosition::Start && toggle.is_none(),
 969                    |flex| {
 970                        flex.child(
 971                            Icon::from_path(custom_path.clone())
 972                                .size(*icon_size)
 973                                .color(icon_color),
 974                        )
 975                    },
 976                )
 977                .child(Label::new(label.clone()).color(label_color).truncate())
 978                .when(*icon_position == IconPosition::End, |flex| {
 979                    flex.child(
 980                        Icon::from_path(custom_path.clone())
 981                            .size(*icon_size)
 982                            .color(icon_color),
 983                    )
 984                })
 985                .into_any_element()
 986        } else if let Some(custom_icon_svg) = custom_icon_svg {
 987            h_flex()
 988                .gap_1p5()
 989                .when(
 990                    *icon_position == IconPosition::Start && toggle.is_none(),
 991                    |flex| {
 992                        flex.child(
 993                            Icon::from_external_svg(custom_icon_svg.clone())
 994                                .size(*icon_size)
 995                                .color(icon_color),
 996                        )
 997                    },
 998                )
 999                .child(Label::new(label.clone()).color(label_color).truncate())
1000                .when(*icon_position == IconPosition::End, |flex| {
1001                    flex.child(
1002                        Icon::from_external_svg(custom_icon_svg.clone())
1003                            .size(*icon_size)
1004                            .color(icon_color),
1005                    )
1006                })
1007                .into_any_element()
1008        } else if let Some(icon_name) = icon {
1009            h_flex()
1010                .gap_1p5()
1011                .when(
1012                    *icon_position == IconPosition::Start && toggle.is_none(),
1013                    |flex| flex.child(Icon::new(*icon_name).size(*icon_size).color(icon_color)),
1014                )
1015                .child(Label::new(label.clone()).color(label_color).truncate())
1016                .when(*icon_position == IconPosition::End, |flex| {
1017                    flex.child(Icon::new(*icon_name).size(*icon_size).color(icon_color))
1018                })
1019                .into_any_element()
1020        } else {
1021            Label::new(label.clone())
1022                .color(label_color)
1023                .truncate()
1024                .into_any_element()
1025        };
1026
1027        div()
1028            .id(("context-menu-child", ix))
1029            .when_some(documentation_aside.clone(), |this, documentation_aside| {
1030                this.occlude()
1031                    .on_hover(cx.listener(move |menu, hovered, _, cx| {
1032                        if *hovered {
1033                            menu.documentation_aside = Some((ix, documentation_aside.clone()));
1034                        } else if matches!(menu.documentation_aside, Some((id, _)) if id == ix) {
1035                            menu.documentation_aside = None;
1036                        }
1037                        cx.notify();
1038                    }))
1039            })
1040            .child(
1041                ListItem::new(ix)
1042                    .group_name("label_container")
1043                    .inset(true)
1044                    .disabled(*disabled)
1045                    .toggle_state(Some(ix) == self.selected_index)
1046                    .when_some(*toggle, |list_item, (position, toggled)| {
1047                        let contents = div()
1048                            .flex_none()
1049                            .child(
1050                                Icon::new(icon.unwrap_or(IconName::Check))
1051                                    .color(icon_color)
1052                                    .size(*icon_size),
1053                            )
1054                            .when(!toggled, |contents| contents.invisible());
1055
1056                        match position {
1057                            IconPosition::Start => list_item.start_slot(contents),
1058                            IconPosition::End => list_item.end_slot(contents),
1059                        }
1060                    })
1061                    .child(
1062                        h_flex()
1063                            .w_full()
1064                            .justify_between()
1065                            .child(label_element)
1066                            .debug_selector(|| format!("MENU_ITEM-{}", label))
1067                            .children(action.as_ref().map(|action| {
1068                                let binding = self
1069                                    .action_context
1070                                    .as_ref()
1071                                    .map(|focus| KeyBinding::for_action_in(&**action, focus, cx))
1072                                    .unwrap_or_else(|| KeyBinding::for_action(&**action, cx));
1073
1074                                div()
1075                                    .ml_4()
1076                                    .child(binding.disabled(*disabled))
1077                                    .when(*disabled && documentation_aside.is_some(), |parent| {
1078                                        parent.invisible()
1079                                    })
1080                            }))
1081                            .when(*disabled && documentation_aside.is_some(), |parent| {
1082                                parent.child(
1083                                    Icon::new(IconName::Info)
1084                                        .size(IconSize::XSmall)
1085                                        .color(Color::Muted),
1086                                )
1087                            }),
1088                    )
1089                    .when_some(
1090                        end_slot_icon
1091                            .as_ref()
1092                            .zip(self.end_slot_action.as_ref())
1093                            .zip(end_slot_title.as_ref())
1094                            .zip(end_slot_handler.as_ref()),
1095                        |el, (((icon, action), title), handler)| {
1096                            el.end_slot({
1097                                let icon_button = IconButton::new("end-slot-icon", *icon)
1098                                    .shape(IconButtonShape::Square)
1099                                    .tooltip({
1100                                        let action_context = self.action_context.clone();
1101                                        let title = title.clone();
1102                                        let action = action.boxed_clone();
1103                                        move |_window, cx| {
1104                                            action_context
1105                                                .as_ref()
1106                                                .map(|focus| {
1107                                                    Tooltip::for_action_in(
1108                                                        title.clone(),
1109                                                        &*action,
1110                                                        focus,
1111                                                        cx,
1112                                                    )
1113                                                })
1114                                                .unwrap_or_else(|| {
1115                                                    Tooltip::for_action(title.clone(), &*action, cx)
1116                                                })
1117                                        }
1118                                    })
1119                                    .on_click({
1120                                        let handler = handler.clone();
1121                                        move |_, window, cx| {
1122                                            handler(None, window, cx);
1123                                            this.update(cx, |this, cx| {
1124                                                this.rebuild(window, cx);
1125                                                cx.notify();
1126                                            })
1127                                            .ok();
1128                                        }
1129                                    });
1130
1131                                if *show_end_slot_on_hover {
1132                                    div()
1133                                        .visible_on_hover("label_container")
1134                                        .child(icon_button)
1135                                        .into_any_element()
1136                                } else {
1137                                    icon_button.into_any_element()
1138                                }
1139                            })
1140                        },
1141                    )
1142                    .on_click({
1143                        let context = self.action_context.clone();
1144                        let keep_open_on_confirm = self.keep_open_on_confirm;
1145                        move |_, window, cx| {
1146                            handler(context.as_ref(), window, cx);
1147                            menu.update(cx, |menu, cx| {
1148                                menu.clicked = true;
1149                                if keep_open_on_confirm {
1150                                    menu.rebuild(window, cx);
1151                                } else {
1152                                    cx.emit(DismissEvent);
1153                                }
1154                            })
1155                            .ok();
1156                        }
1157                    }),
1158            )
1159            .into_any_element()
1160    }
1161}
1162
1163impl ContextMenuItem {
1164    fn is_selectable(&self) -> bool {
1165        match self {
1166            ContextMenuItem::Header(_)
1167            | ContextMenuItem::HeaderWithLink(_, _, _)
1168            | ContextMenuItem::Separator
1169            | ContextMenuItem::Label { .. } => false,
1170            ContextMenuItem::Entry(ContextMenuEntry { disabled, .. }) => !disabled,
1171            ContextMenuItem::CustomEntry { selectable, .. } => *selectable,
1172        }
1173    }
1174}
1175
1176impl Render for ContextMenu {
1177    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1178        let ui_font_size = ThemeSettings::get_global(cx).ui_font_size(cx);
1179        let window_size = window.viewport_size();
1180        let rem_size = window.rem_size();
1181        let is_wide_window = window_size.width / rem_size > rems_from_px(800.).0;
1182
1183        let aside = self.documentation_aside.clone();
1184        let render_aside = |aside: DocumentationAside, cx: &mut Context<Self>| {
1185            WithRemSize::new(ui_font_size)
1186                .occlude()
1187                .elevation_2(cx)
1188                .w_full()
1189                .p_2()
1190                .overflow_hidden()
1191                .when(is_wide_window, |this| this.max_w_96())
1192                .when(!is_wide_window, |this| this.max_w_48())
1193                .child((aside.render)(cx))
1194        };
1195
1196        let render_menu =
1197            |cx: &mut Context<Self>, window: &mut Window| {
1198                WithRemSize::new(ui_font_size)
1199                    .occlude()
1200                    .elevation_2(cx)
1201                    .flex()
1202                    .flex_row()
1203                    .flex_shrink_0()
1204                    .child(
1205                        v_flex()
1206                            .id("context-menu")
1207                            .max_h(vh(0.75, window))
1208                            .flex_shrink_0()
1209                            .when_some(self.fixed_width, |this, width| {
1210                                this.w(width).overflow_x_hidden()
1211                            })
1212                            .when(self.fixed_width.is_none(), |this| {
1213                                this.min_w(px(200.)).flex_1()
1214                            })
1215                            .overflow_y_scroll()
1216                            .track_focus(&self.focus_handle(cx))
1217                            .on_mouse_down_out(cx.listener(|this, _, window, cx| {
1218                                this.cancel(&menu::Cancel, window, cx)
1219                            }))
1220                            .key_context(self.key_context.as_ref())
1221                            .on_action(cx.listener(ContextMenu::select_first))
1222                            .on_action(cx.listener(ContextMenu::handle_select_last))
1223                            .on_action(cx.listener(ContextMenu::select_next))
1224                            .on_action(cx.listener(ContextMenu::select_previous))
1225                            .on_action(cx.listener(ContextMenu::confirm))
1226                            .on_action(cx.listener(ContextMenu::cancel))
1227                            .when_some(self.end_slot_action.as_ref(), |el, action| {
1228                                el.on_boxed_action(&**action, cx.listener(ContextMenu::end_slot))
1229                            })
1230                            .when(!self.delayed, |mut el| {
1231                                for item in self.items.iter() {
1232                                    if let ContextMenuItem::Entry(ContextMenuEntry {
1233                                        action: Some(action),
1234                                        disabled: false,
1235                                        ..
1236                                    }) = item
1237                                    {
1238                                        el = el.on_boxed_action(
1239                                            &**action,
1240                                            cx.listener(ContextMenu::on_action_dispatch),
1241                                        );
1242                                    }
1243                                }
1244                                el
1245                            })
1246                            .child(
1247                                List::new().children(
1248                                    self.items.iter().enumerate().map(|(ix, item)| {
1249                                        self.render_menu_item(ix, item, window, cx)
1250                                    }),
1251                                ),
1252                            ),
1253                    )
1254            };
1255
1256        if is_wide_window {
1257            div()
1258                .relative()
1259                .child(render_menu(cx, window))
1260                .children(aside.map(|(_item_index, aside)| {
1261                    h_flex()
1262                        .absolute()
1263                        .when(aside.side == DocumentationSide::Left, |this| {
1264                            this.right_full().mr_1()
1265                        })
1266                        .when(aside.side == DocumentationSide::Right, |this| {
1267                            this.left_full().ml_1()
1268                        })
1269                        .when(aside.edge == DocumentationEdge::Top, |this| this.top_0())
1270                        .when(aside.edge == DocumentationEdge::Bottom, |this| {
1271                            this.bottom_0()
1272                        })
1273                        .child(render_aside(aside, cx))
1274                }))
1275        } else {
1276            v_flex()
1277                .w_full()
1278                .gap_1()
1279                .justify_end()
1280                .children(aside.map(|(_, aside)| render_aside(aside, cx)))
1281                .child(render_menu(cx, window))
1282        }
1283    }
1284}
1285
1286#[cfg(test)]
1287mod tests {
1288    use gpui::TestAppContext;
1289
1290    use super::*;
1291
1292    #[gpui::test]
1293    fn can_navigate_back_over_headers(cx: &mut TestAppContext) {
1294        let cx = cx.add_empty_window();
1295        let context_menu = cx.update(|window, cx| {
1296            ContextMenu::build(window, cx, |menu, _, _| {
1297                menu.header("First header")
1298                    .separator()
1299                    .entry("First entry", None, |_, _| {})
1300                    .separator()
1301                    .separator()
1302                    .entry("Last entry", None, |_, _| {})
1303                    .header("Last header")
1304            })
1305        });
1306
1307        context_menu.update_in(cx, |context_menu, window, cx| {
1308            assert_eq!(
1309                None, context_menu.selected_index,
1310                "No selection is in the menu initially"
1311            );
1312
1313            context_menu.select_first(&SelectFirst, window, cx);
1314            assert_eq!(
1315                Some(2),
1316                context_menu.selected_index,
1317                "Should select first selectable entry, skipping the header and the separator"
1318            );
1319
1320            context_menu.select_next(&SelectNext, window, cx);
1321            assert_eq!(
1322                Some(5),
1323                context_menu.selected_index,
1324                "Should select next selectable entry, skipping 2 separators along the way"
1325            );
1326
1327            context_menu.select_next(&SelectNext, window, cx);
1328            assert_eq!(
1329                Some(2),
1330                context_menu.selected_index,
1331                "Should wrap around to first selectable entry"
1332            );
1333        });
1334
1335        context_menu.update_in(cx, |context_menu, window, cx| {
1336            assert_eq!(
1337                Some(2),
1338                context_menu.selected_index,
1339                "Should start from the first selectable entry"
1340            );
1341
1342            context_menu.select_previous(&SelectPrevious, window, cx);
1343            assert_eq!(
1344                Some(5),
1345                context_menu.selected_index,
1346                "Should wrap around to previous selectable entry (last)"
1347            );
1348
1349            context_menu.select_previous(&SelectPrevious, window, cx);
1350            assert_eq!(
1351                Some(2),
1352                context_menu.selected_index,
1353                "Should go back to previous selectable entry (first)"
1354            );
1355        });
1356
1357        context_menu.update_in(cx, |context_menu, window, cx| {
1358            context_menu.select_first(&SelectFirst, window, cx);
1359            assert_eq!(
1360                Some(2),
1361                context_menu.selected_index,
1362                "Should start from the first selectable entry"
1363            );
1364
1365            context_menu.select_previous(&SelectPrevious, window, cx);
1366            assert_eq!(
1367                Some(5),
1368                context_menu.selected_index,
1369                "Should wrap around to last selectable entry"
1370            );
1371            context_menu.select_next(&SelectNext, window, cx);
1372            assert_eq!(
1373                Some(2),
1374                context_menu.selected_index,
1375                "Should wrap around to first selectable entry"
1376            );
1377        });
1378    }
1379}