| 1 | use std::rc::Rc; |
| 2 | |
| 3 | use gpui::{ |
| 4 | Anchor, AnyElement, App, Context, DismissEvent, Element, ElementId, Entity, FocusHandle, |
| 5 | Focusable, GlobalElementId, InspectorElementId, InteractiveElement, IntoElement, LayoutId, |
| 6 | RenderOnce, SharedString, Styled, Window, prelude::FluentBuilder, |
| 7 | }; |
| 8 | |
| 9 | use crate::{Selectable, button::Button, menu::PopupMenu, popover::Popover}; |
| 10 | |
| 11 | /// A dropdown menu trait for buttons and other interactive elements |
| 12 | pub trait DropdownMenu: Styled + Selectable + InteractiveElement + IntoElement + 'static { |
| 13 | /// Create a dropdown menu with the given items, anchored to the TopLeft corner |
| 14 | fn dropdown_menu( |
| 15 | self, |
| 16 | f: impl Fn(PopupMenu, &mut Window, &mut Context<PopupMenu>) -> PopupMenu + 'static, |
| 17 | ) -> DropdownMenuPopover<Self> { |
| 18 | self.dropdown_menu_with_anchor(Anchor::TopLeft, f) |
| 19 | } |
| 20 | |
| 21 | /// Create a dropdown menu with the given items, anchored to the given corner |
| 22 | fn dropdown_menu_with_anchor( |
| 23 | mut self, |
| 24 | anchor: impl Into<Anchor>, |
| 25 | f: impl Fn(PopupMenu, &mut Window, &mut Context<PopupMenu>) -> PopupMenu + 'static, |
| 26 | ) -> DropdownMenuPopover<Self> { |
| 27 | let id = self.interactivity().element_id.clone(); |
| 28 | |
| 29 | DropdownMenuPopover::new(id.unwrap_or(0.into()), anchor, self, f) |
| 30 | } |
| 31 | } |
| 32 | |
| 33 | impl DropdownMenu for Button {} |
| 34 | |
| 35 | #[derive(IntoElement)] |
| 36 | pub struct DropdownMenuPopover<T: Selectable + IntoElement + 'static> { |
| 37 | id: ElementId, |
| 38 | anchor: Anchor, |
| 39 | trigger: T, |
| 40 | builder: Rc<dyn Fn(PopupMenu, &mut Window, &mut Context<PopupMenu>) -> PopupMenu>, |
| 41 | on_open_change: Option<Rc<dyn Fn(&bool, &mut Window, &mut App)>>, |
| 42 | open: Option<bool>, |
| 43 | } |
| 44 | |
| 45 | impl<T> DropdownMenuPopover<T> |
| 46 | where |
| 47 | T: Selectable + IntoElement + 'static, |
| 48 | { |
| 49 | fn new( |
| 50 | id: ElementId, |
| 51 | anchor: impl Into<Anchor>, |
| 52 | trigger: T, |
| 53 | builder: impl Fn(PopupMenu, &mut Window, &mut Context<PopupMenu>) -> PopupMenu + 'static, |
| 54 | ) -> Self { |
| 55 | Self { |
| 56 | id: SharedString::from(format!("dropdown-menu:{:?}", id)).into(), |
| 57 | anchor: anchor.into(), |
| 58 | trigger, |
| 59 | builder: Rc::new(builder), |
| 60 | on_open_change: None, |
| 61 | open: None, |
| 62 | } |
| 63 | } |
| 64 | |
| 65 | /// Control the open state from outside; pair it with `on_open_change`. |
| 66 | pub fn open(mut self, open: bool) -> Self { |
| 67 | self.open = Some(open); |
| 68 | self |
| 69 | } |
| 70 | |
| 71 | /// Set the anchor corner for the dropdown menu popover. |
| 72 | pub fn anchor(mut self, anchor: impl Into<Anchor>) -> Self { |
| 73 | self.anchor = anchor.into(); |
| 74 | self |
| 75 | } |
| 76 | |
| 77 | /// Add a callback to be called when the menu opens or closes. |
| 78 | /// |
| 79 | /// The `&bool` parameter is the **new open state**. |
| 80 | pub fn on_open_change( |
| 81 | mut self, |
| 82 | callback: impl Fn(&bool, &mut Window, &mut App) + 'static, |
| 83 | ) -> Self { |
| 84 | self.on_open_change = Some(Rc::new(callback)); |
| 85 | self |
| 86 | } |
| 87 | } |
| 88 | |
| 89 | #[derive(Default)] |
| 90 | struct DropdownMenuState { |
| 91 | menu: Option<Entity<PopupMenu>>, |
| 92 | } |
| 93 | |
| 94 | impl<T> RenderOnce for DropdownMenuPopover<T> |
| 95 | where |
| 96 | T: Selectable + IntoElement + 'static, |
| 97 | { |
| 98 | fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement { |
| 99 | TriggerFocus::new(self.id.clone(), move |trigger_focus, window, cx| { |
| 100 | self.render_popover(trigger_focus, window, cx) |
| 101 | .into_any_element() |
| 102 | }) |
| 103 | } |
| 104 | } |
| 105 | |
| 106 | impl<T> DropdownMenuPopover<T> |
| 107 | where |
| 108 | T: Selectable + IntoElement + 'static, |
| 109 | { |
| 110 | fn render_popover( |
| 111 | self, |
| 112 | trigger_focus: FocusHandle, |
| 113 | window: &mut Window, |
| 114 | cx: &mut App, |
| 115 | ) -> Popover { |
| 116 | let builder = self.builder.clone(); |
| 117 | let menu_state = |
| 118 | window.use_keyed_state(self.id.clone(), cx, |_, _| DropdownMenuState::default()); |
| 119 | |
| 120 | Popover::new(SharedString::from(format!("popover:{}", self.id))) |
| 121 | .appearance(false) |
| 122 | .overlay_closable(false) |
| 123 | .trigger(self.trigger) |
| 124 | .anchor(self.anchor) |
| 125 | .when_some(self.open, |this, open| this.open(open)) |
| 126 | .when_some(self.on_open_change, |this, callback| { |
| 127 | this.on_open_change(move |open, window, cx| callback(open, window, cx)) |
| 128 | }) |
| 129 | .content(move |_, window, cx| { |
| 130 | // Here is special logic to only create the PopupMenu once and reuse it. |
| 131 | // Because this `content` will called in every time render, so we need to store the menu |
| 132 | // in state to avoid recreating at every render. |
| 133 | // |
| 134 | // And we also need to rebuild the menu when it is dismissed, to rebuild menu items |
| 135 | // dynamically for support `dropdown_menu` method, so we listen for DismissEvent below. |
| 136 | let menu = match menu_state.read(cx).menu.clone() { |
| 137 | Some(menu) => menu, |
| 138 | None => { |
| 139 | let builder = builder.clone(); |
| 140 | let menu = PopupMenu::build(window, cx, move |menu, window, cx| { |
| 141 | builder(menu, window, cx) |
| 142 | }); |
| 143 | menu.update(cx, |menu, cx| { |
| 144 | menu.set_trigger_focus(Some(trigger_focus.clone()), cx) |
| 145 | }); |
| 146 | menu_state.update(cx, |state, _| { |
| 147 | state.menu = Some(menu.clone()); |
| 148 | }); |
| 149 | menu.focus_handle(cx).focus(window, cx); |
| 150 | |
| 151 | // Listen for dismiss events from the PopupMenu to close the popover. |
| 152 | // |
| 153 | // Hold Weak handles here, not strong clones: the listener |
| 154 | // lives as long as `menu`, which `menu_state` owns, so a |
| 155 | // strong capture would close the cycle |
| 156 | // `menu_state -> menu -> listener -> menu_state` and leak |
| 157 | // the `PopupMenu` and `DropdownMenuState` when the trigger |
| 158 | // stops being rendered while the menu is open. |
| 159 | let popover_state = cx.entity().downgrade(); |
| 160 | window |
| 161 | .subscribe(&menu, cx, { |
| 162 | let menu_state = menu_state.downgrade(); |
| 163 | move |_, _: &DismissEvent, window, cx| { |
| 164 | if let Some(popover_state) = popover_state.upgrade() { |
| 165 | popover_state.update(cx, |state, cx| { |
| 166 | state.dismiss(window, cx); |
| 167 | }); |
| 168 | } |
| 169 | _ = menu_state.update(cx, |state, _| { |
| 170 | state.menu = None; |
| 171 | }); |
| 172 | } |
| 173 | }) |
| 174 | .detach(); |
| 175 | |
| 176 | menu.clone() |
| 177 | } |
| 178 | }; |
| 179 | |
| 180 | menu.clone() |
| 181 | }) |
| 182 | } |
| 183 | } |
| 184 | |
| 185 | type TriggerFocusBuild = Box<dyn FnOnce(FocusHandle, &mut Window, &mut App) -> AnyElement>; |
| 186 | |
| 187 | /// Registers a focus handle on the trigger's dispatch node without ever |
| 188 | /// focusing it, so the menu opened from the trigger can resolve its shortcut |
| 189 | /// hints against the trigger's key contexts on the frame it opens. GPUI looks |
| 190 | /// a handle up in the previously rendered frame; the trigger was in it when |
| 191 | /// the menu was not yet. |
| 192 | struct TriggerFocus { |
| 193 | id: ElementId, |
| 194 | build: Option<TriggerFocusBuild>, |
| 195 | } |
| 196 | |
| 197 | #[derive(Default)] |
| 198 | struct TriggerFocusState { |
| 199 | focus_handle: Option<FocusHandle>, |
| 200 | } |
| 201 | |
| 202 | struct TriggerFocusFrame { |
| 203 | focus_handle: FocusHandle, |
| 204 | child: AnyElement, |
| 205 | } |
| 206 | |
| 207 | impl TriggerFocus { |
| 208 | fn new( |
| 209 | id: ElementId, |
| 210 | build: impl FnOnce(FocusHandle, &mut Window, &mut App) -> AnyElement + 'static, |
| 211 | ) -> Self { |
| 212 | Self { |
| 213 | id, |
| 214 | build: Some(Box::new(build)), |
| 215 | } |
| 216 | } |
| 217 | } |
| 218 | |
| 219 | impl IntoElement for TriggerFocus { |
| 220 | type Element = Self; |
| 221 | |
| 222 | fn into_element(self) -> Self::Element { |
| 223 | self |
| 224 | } |
| 225 | } |
| 226 | |
| 227 | impl Element for TriggerFocus { |
| 228 | type RequestLayoutState = TriggerFocusFrame; |
| 229 | type PrepaintState = (); |
| 230 | |
| 231 | fn id(&self) -> Option<ElementId> { |
| 232 | Some(self.id.clone()) |
| 233 | } |
| 234 | |
| 235 | fn source_location(&self) -> Option<&'static std::panic::Location<'static>> { |
| 236 | None |
| 237 | } |
| 238 | |
| 239 | fn request_layout( |
| 240 | &mut self, |
| 241 | id: Option<&GlobalElementId>, |
| 242 | _: Option<&InspectorElementId>, |
| 243 | window: &mut Window, |
| 244 | cx: &mut App, |
| 245 | ) -> (LayoutId, Self::RequestLayoutState) { |
| 246 | let focus_handle = |
| 247 | window.with_optional_element_state::<TriggerFocusState, _>(id, |state, _| { |
| 248 | let mut state = state.flatten().unwrap_or_default(); |
| 249 | let focus_handle = state |
| 250 | .focus_handle |
| 251 | .get_or_insert_with(|| cx.focus_handle()) |
| 252 | .clone(); |
| 253 | (focus_handle, Some(state)) |
| 254 | }); |
| 255 | let build = self.build.take().expect("TriggerFocus is laid out once"); |
| 256 | let mut child = build(focus_handle.clone(), window, cx); |
| 257 | let layout_id = child.request_layout(window, cx); |
| 258 | |
| 259 | ( |
| 260 | layout_id, |
| 261 | TriggerFocusFrame { |
| 262 | focus_handle, |
| 263 | child, |
| 264 | }, |
| 265 | ) |
| 266 | } |
| 267 | |
| 268 | fn prepaint( |
| 269 | &mut self, |
| 270 | _: Option<&GlobalElementId>, |
| 271 | _: Option<&InspectorElementId>, |
| 272 | _: gpui::Bounds<gpui::Pixels>, |
| 273 | frame: &mut Self::RequestLayoutState, |
| 274 | window: &mut Window, |
| 275 | cx: &mut App, |
| 276 | ) { |
| 277 | window.set_focus_handle(&frame.focus_handle, cx); |
| 278 | frame.child.prepaint(window, cx); |
| 279 | } |
| 280 | |
| 281 | fn paint( |
| 282 | &mut self, |
| 283 | _: Option<&GlobalElementId>, |
| 284 | _: Option<&InspectorElementId>, |
| 285 | _: gpui::Bounds<gpui::Pixels>, |
| 286 | frame: &mut Self::RequestLayoutState, |
| 287 | _: &mut Self::PrepaintState, |
| 288 | window: &mut Window, |
| 289 | cx: &mut App, |
| 290 | ) { |
| 291 | frame.child.paint(window, cx); |
| 292 | } |
| 293 | } |
| 294 | |
| 295 | #[cfg(test)] |
| 296 | mod tests { |
| 297 | use super::*; |
| 298 | use gpui::{ |
| 299 | KeyBinding, MouseButton, ParentElement as _, Render, TestAppContext, WeakEntity, actions, |
| 300 | div, point, px, |
| 301 | }; |
| 302 | use std::cell::{Cell, RefCell}; |
| 303 | |
| 304 | actions!(dropdown_menu_test, [CopyText]); |
| 305 | |
| 306 | const CONTEXT: &str = "dropdown_menu_test"; |
| 307 | |
| 308 | /// The story shape: the key binding lives in the key context of the |
| 309 | /// trigger's ancestor, the menu names no `action_context`, and other |
| 310 | /// content outside that context paints after the trigger. |
| 311 | struct TestRoot { |
| 312 | frames: Rc<Cell<usize>>, |
| 313 | } |
| 314 | |
| 315 | impl Render for TestRoot { |
| 316 | fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement { |
| 317 | self.frames.set(self.frames.get() + 1); |
| 318 | div() |
| 319 | .size_full() |
| 320 | .child( |
| 321 | div() |
| 322 | .key_context(CONTEXT) |
| 323 | .on_action(|_: &CopyText, _, _| {}) |
| 324 | .child( |
| 325 | Button::new("trigger") |
| 326 | .label("Edit") |
| 327 | .w(px(100.)) |
| 328 | .h(px(30.)) |
| 329 | .dropdown_menu(|menu, _, _| menu.menu("Copy", Box::new(CopyText))), |
| 330 | ), |
| 331 | ) |
| 332 | .child(div().child("Status")) |
| 333 | } |
| 334 | } |
| 335 | |
| 336 | /// Records the `PopupMenu` the dropdown builds, so a test can observe |
| 337 | /// its release through a weak handle. |
| 338 | struct MenuProbeRoot { |
| 339 | menu: Rc<RefCell<Option<WeakEntity<PopupMenu>>>>, |
| 340 | } |
| 341 | |
| 342 | impl Render for MenuProbeRoot { |
| 343 | fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement { |
| 344 | let slot = self.menu.clone(); |
| 345 | div().size_full().child( |
| 346 | Button::new("trigger") |
| 347 | .label("Edit") |
| 348 | .w(px(100.)) |
| 349 | .h(px(30.)) |
| 350 | .dropdown_menu(move |menu, _, cx| { |
| 351 | *slot.borrow_mut() = Some(cx.weak_entity()); |
| 352 | menu.menu("Copy", Box::new(CopyText)) |
| 353 | }), |
| 354 | ) |
| 355 | } |
| 356 | } |
| 357 | |
| 358 | /// Opening the menu and closing the window without dismissing it must |
| 359 | /// release the `PopupMenu`: the dismiss subscription lives as long as the |
| 360 | /// menu, which `DropdownMenuState` owns, so strong captures in it formed |
| 361 | /// a cycle that no element-state collection could break. The state still |
| 362 | /// holds the menu while it is open, so the menu's release also proves the |
| 363 | /// `DropdownMenuState` was released. |
| 364 | /// |
| 365 | /// The popover must go too: it holds the deferred-popover registration |
| 366 | /// while open, and a leaked one keeps every later right-click menu |
| 367 | /// stepping aside as if a popup were still showing. |
| 368 | #[gpui::test] |
| 369 | fn open_without_dismiss_releases_the_menu(cx: &mut TestAppContext) { |
| 370 | cx.update(|cx| crate::init(cx)); |
| 371 | let menu = Rc::new(RefCell::new(None::<WeakEntity<PopupMenu>>)); |
| 372 | |
| 373 | { |
| 374 | let (_, cx) = cx.add_window_view(|_, _| MenuProbeRoot { menu: menu.clone() }); |
| 375 | cx.update(|window, cx| window.draw(cx).clear(cx)); |
| 376 | |
| 377 | // Click the trigger; the menu opens and is left open. |
| 378 | cx.simulate_mouse_down( |
| 379 | point(px(10.), px(10.)), |
| 380 | MouseButton::Left, |
| 381 | Default::default(), |
| 382 | ); |
| 383 | cx.run_until_parked(); |
| 384 | assert!( |
| 385 | menu.borrow() |
| 386 | .as_ref() |
| 387 | .and_then(|menu| menu.upgrade()) |
| 388 | .is_some(), |
| 389 | "the menu must be open before the window closes" |
| 390 | ); |
| 391 | |
| 392 | // Close the window without dismissing the menu. |
| 393 | cx.update(|window, _| window.remove_window()); |
| 394 | cx.run_until_parked(); |
| 395 | } |
| 396 | |
| 397 | assert!( |
| 398 | menu.borrow() |
| 399 | .as_ref() |
| 400 | .and_then(|menu| menu.upgrade()) |
| 401 | .is_none(), |
| 402 | "the PopupMenu must be released with the window" |
| 403 | ); |
| 404 | cx.update(|cx| { |
| 405 | assert!( |
| 406 | !gpui_base::GlobalState::is_in_deferred_context(cx), |
| 407 | "the popover's deferred registration must be released with the window" |
| 408 | ) |
| 409 | }); |
| 410 | } |
| 411 | |
| 412 | #[gpui::test] |
| 413 | fn shortcut_hint_is_painted_on_the_frame_the_menu_opens(cx: &mut TestAppContext) { |
| 414 | cx.update(|cx| { |
| 415 | crate::init(cx); |
| 416 | cx.bind_keys([KeyBinding::new("ctrl-c", CopyText, Some(CONTEXT))]); |
| 417 | }); |
| 418 | let frames = Rc::new(Cell::new(0)); |
| 419 | let (_, cx) = cx.add_window_view({ |
| 420 | let frames = frames.clone(); |
| 421 | move |_, _| TestRoot { frames } |
| 422 | }); |
| 423 | // The popup host captures its trigger bounds on the first frame. |
| 424 | cx.update(|window, cx| window.draw(cx).clear(cx)); |
| 425 | let frames_before_open = frames.get(); |
| 426 | |
| 427 | cx.simulate_mouse_down( |
| 428 | point(px(10.), px(10.)), |
| 429 | MouseButton::Left, |
| 430 | Default::default(), |
| 431 | ); |
| 432 | |
| 433 | assert_eq!( |
| 434 | frames.get(), |
| 435 | frames_before_open + 1, |
| 436 | "the press must be followed by exactly one frame for this to test the first one" |
| 437 | ); |
| 438 | assert!( |
| 439 | cx.debug_bounds("kbd:ctrl-c").is_some(), |
| 440 | "the shortcut hint must be painted on the same frame as its item" |
| 441 | ); |
| 442 | } |
| 443 | } |