context_menu: Fix ContextMenu to cover parent element area. (#1566)

Close #1541
This commit is contained in:
Jason Lee 2025-11-12 14:19:52 +08:00 committed by GitHub
parent 838fd6411a
commit b3c0188940
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
4 changed files with 164 additions and 92 deletions

View file

@ -117,7 +117,7 @@ use gpui_component::{
dock::{Panel, PanelControl, PanelEvent, PanelInfo, PanelState, TitleStyle, register_panel}, dock::{Panel, PanelControl, PanelEvent, PanelInfo, PanelState, TitleStyle, register_panel},
group_box::GroupBox, group_box::GroupBox,
h_flex, h_flex,
menu::{ContextMenuExt, PopupMenu}, menu::PopupMenu,
notification::Notification, notification::Notification,
scroll::ScrollbarShow, scroll::ScrollbarShow,
v_flex, v_flex,
@ -436,8 +436,6 @@ impl RenderOnce for StorySection {
} }
} }
impl ContextMenuExt for StorySection {}
pub(crate) fn section(title: impl Into<SharedString>) -> StorySection { pub(crate) fn section(title: impl Into<SharedString>) -> StorySection {
StorySection { StorySection {
title: title.into(), title: title.into(),

View file

@ -3,7 +3,7 @@ use gpui::{
ParentElement as _, Render, SharedString, Styled as _, Window, actions, div, px, ParentElement as _, Render, SharedString, Styled as _, Window, actions, div, px,
}; };
use gpui_component::{ use gpui_component::{
ActiveTheme as _, IconName, ActiveTheme as _, IconName, StyledExt,
button::Button, button::Button,
h_flex, h_flex,
menu::{ContextMenuExt, DropdownMenu as _, PopupMenuItem}, menu::{ContextMenuExt, DropdownMenu as _, PopupMenuItem},
@ -206,31 +206,85 @@ impl Render for MenuStory {
) )
.child( .child(
section("Context Menu") section("Context Menu")
.child("Right click to open ContextMenu") .v_flex()
.min_h_20() .gap_4()
.context_menu({ .child(
move |this, window, cx| { v_flex()
this.external_link_icon(false) .w_full()
.link("About", "https://github.com/longbridge/gpui-component") .p_4()
.separator() .items_center()
.menu("Cut", Box::new(Cut)) .justify_center()
.menu("Copy", Box::new(Copy)) .min_h_20()
.menu("Paste", Box::new(Paste)) .rounded_lg()
.separator() .border_2()
.label("This is a label") .border_dashed()
.menu_with_check("Toggle Check", checked, Box::new(ToggleCheck)) .border_color(cx.theme().border)
.separator() .child("Right click to open ContextMenu")
.submenu("Settings", window, cx, move |menu, _, _| { .context_menu({
menu.menu("Info 0", Box::new(Info(0))) move |this, window, cx| {
this.external_link_icon(false)
.link(
"About",
"https://github.com/longbridge/gpui-component",
)
.separator() .separator()
.menu("Item 1", Box::new(Info(1))) .menu("Cut", Box::new(Cut))
.menu("Item 2", Box::new(Info(2))) .menu("Copy", Box::new(Copy))
}) .menu("Paste", Box::new(Paste))
.separator() .separator()
.menu("Search All", Box::new(SearchAll)) .label("This is a label")
.separator() .menu_with_check(
} "Toggle Check",
}), checked,
Box::new(ToggleCheck),
)
.separator()
.submenu("Settings", window, cx, move |menu, _, _| {
menu.menu("Info 0", Box::new(Info(0)))
.separator()
.menu("Item 1", Box::new(Info(1)))
.menu("Item 2", Box::new(Info(2)))
})
.separator()
.menu("Search All", Box::new(SearchAll))
.separator()
}
})
.child(
div()
.text_sm()
.text_color(cx.theme().muted_foreground)
.child(
"You can right click anywhere in \
this area to open the context menu.",
),
),
)
.child(
div()
.id("other")
.flex()
.w_full()
.p_4()
.items_center()
.justify_center()
.min_h_20()
.rounded_lg()
.border_2()
.border_dashed()
.border_color(cx.theme().border)
.child("Here is another area with context menu.")
.context_menu({
move |this, _, _| {
this.link(
"About",
"https://github.com/longbridge/gpui-component",
)
.separator()
.menu("Item 1", Box::new(Info(1)))
}
}),
),
) )
.child( .child(
section("Menu with scrollbar") section("Menu with scrollbar")

View file

@ -1,48 +1,55 @@
use std::{cell::RefCell, rc::Rc}; use std::{cell::RefCell, rc::Rc};
use gpui::{ use gpui::{
anchored, deferred, div, prelude::FluentBuilder, px, relative, AnyElement, App, Context, anchored, deferred, div, prelude::FluentBuilder, px, AnyElement, App, Context, Corner,
Corner, DismissEvent, Element, ElementId, Entity, Focusable, GlobalElementId, DismissEvent, Element, ElementId, Entity, Focusable, GlobalElementId, InspectorElementId,
InspectorElementId, InteractiveElement, IntoElement, MouseButton, MouseDownEvent, InteractiveElement, IntoElement, MouseButton, MouseDownEvent, ParentElement, Pixels, Point,
ParentElement, Pixels, Point, Position, Stateful, Style, Subscription, Window, StyleRefinement, Styled, Subscription, Window,
}; };
use crate::menu::PopupMenu; use crate::menu::PopupMenu;
/// A extension trait for adding a context menu to an element. /// A extension trait for adding a context menu to an element.
pub trait ContextMenuExt: ParentElement + Sized { pub trait ContextMenuExt: ParentElement + Styled {
/// Add a context menu to the element. /// Add a context menu to the element.
///
/// This will changed the element to be `relative` positioned, and add a child `ContextMenu` element.
/// Because the `ContextMenu` element is positioned `absolute`, it will not affect the layout of the parent element.
fn context_menu( fn context_menu(
self, self,
f: impl Fn(PopupMenu, &mut Window, &mut Context<PopupMenu>) -> PopupMenu + 'static, f: impl Fn(PopupMenu, &mut Window, &mut Context<PopupMenu>) -> PopupMenu + 'static,
) -> Self { ) -> ContextMenu<Self> {
self.child(ContextMenu::new("context-menu").menu(f)) ContextMenu::new("context-menu", self).menu(f)
} }
} }
impl<E> ContextMenuExt for Stateful<E> where E: ParentElement {} impl<E: ParentElement + Styled> ContextMenuExt for E {}
/// A context menu that can be shown on right-click. /// A context menu that can be shown on right-click.
pub struct ContextMenu { pub struct ContextMenu<E: ParentElement + Styled + Sized> {
id: ElementId, id: ElementId,
menu: element: Option<E>,
Option<Box<dyn Fn(PopupMenu, &mut Window, &mut Context<PopupMenu>) -> PopupMenu + 'static>>, menu: Option<Box<dyn Fn(PopupMenu, &mut Window, &mut Context<PopupMenu>) -> PopupMenu>>,
// This is not in use, just for style refinement forwarding.
_ignore_style: StyleRefinement,
anchor: Corner, anchor: Corner,
} }
impl ContextMenu { impl<E: ParentElement + Styled> ContextMenu<E> {
/// Create a new context menu with the given ID. /// Create a new context menu with the given ID.
pub fn new(id: impl Into<ElementId>) -> Self { pub fn new(id: impl Into<ElementId>, element: E) -> Self {
Self { Self {
id: id.into(), id: id.into(),
element: Some(element),
menu: None, menu: None,
anchor: Corner::TopLeft, anchor: Corner::TopLeft,
_ignore_style: StyleRefinement::default(),
} }
} }
/// Build the context menu using the given builder function. /// Build the context menu using the given builder function.
#[must_use] #[must_use]
pub fn menu<F>(mut self, builder: F) -> Self fn menu<F>(mut self, builder: F) -> Self
where where
F: Fn(PopupMenu, &mut Window, &mut Context<PopupMenu>) -> PopupMenu + 'static, F: Fn(PopupMenu, &mut Window, &mut Context<PopupMenu>) -> PopupMenu + 'static,
{ {
@ -68,7 +75,25 @@ impl ContextMenu {
} }
} }
impl IntoElement for ContextMenu { impl<E: ParentElement + Styled> ParentElement for ContextMenu<E> {
fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
if let Some(element) = &mut self.element {
element.extend(elements);
}
}
}
impl<E: ParentElement + Styled> Styled for ContextMenu<E> {
fn style(&mut self) -> &mut StyleRefinement {
if let Some(element) = &mut self.element {
element.style()
} else {
&mut self._ignore_style
}
}
}
impl<E: ParentElement + Styled + IntoElement + 'static> IntoElement for ContextMenu<E> {
type Element = Self; type Element = Self;
fn into_element(self) -> Self::Element { fn into_element(self) -> Self::Element {
@ -84,14 +109,14 @@ struct ContextMenuSharedState {
} }
pub struct ContextMenuState { pub struct ContextMenuState {
menu_element: Option<AnyElement>, element: Option<AnyElement>,
shared_state: Rc<RefCell<ContextMenuSharedState>>, shared_state: Rc<RefCell<ContextMenuSharedState>>,
} }
impl Default for ContextMenuState { impl Default for ContextMenuState {
fn default() -> Self { fn default() -> Self {
Self { Self {
menu_element: None, element: None,
shared_state: Rc::new(RefCell::new(ContextMenuSharedState { shared_state: Rc::new(RefCell::new(ContextMenuSharedState {
menu_view: None, menu_view: None,
open: false, open: false,
@ -102,7 +127,7 @@ impl Default for ContextMenuState {
} }
} }
impl Element for ContextMenu { impl<E: ParentElement + Styled + IntoElement + 'static> Element for ContextMenu<E> {
type RequestLayoutState = ContextMenuState; type RequestLayoutState = ContextMenuState;
type PrepaintState = (); type PrepaintState = ();
@ -121,71 +146,60 @@ impl Element for ContextMenu {
window: &mut Window, window: &mut Window,
cx: &mut App, cx: &mut App,
) -> (gpui::LayoutId, Self::RequestLayoutState) { ) -> (gpui::LayoutId, Self::RequestLayoutState) {
let mut style = Style::default();
// Set the layout style relative to the table view to get same size.
style.position = Position::Absolute;
style.flex_grow = 1.0;
style.flex_shrink = 1.0;
style.size.width = relative(1.).into();
style.size.height = relative(1.).into();
let anchor = self.anchor; let anchor = self.anchor;
self.with_element_state( self.with_element_state(
id.unwrap(), id.unwrap(),
window, window,
cx, cx,
|_, state: &mut ContextMenuState, window, cx| { |this, state: &mut ContextMenuState, window, cx| {
let (position, open) = { let (position, open) = {
let shared_state = state.shared_state.borrow(); let shared_state = state.shared_state.borrow();
(shared_state.position, shared_state.open) (shared_state.position, shared_state.open)
}; };
let menu_view = state.shared_state.borrow().menu_view.clone(); let menu_view = state.shared_state.borrow().menu_view.clone();
let (menu_element, menu_layout_id) = if open { let mut menu_element = None;
if open {
let has_menu_item = menu_view let has_menu_item = menu_view
.as_ref() .as_ref()
.map(|menu| !menu.read(cx).is_empty()) .map(|menu| !menu.read(cx).is_empty())
.unwrap_or(false); .unwrap_or(false);
if has_menu_item { if has_menu_item {
let mut menu_element = deferred( menu_element = Some(
anchored() deferred(
.position(position) anchored()
.snap_to_window_with_margin(px(8.)) .position(position)
.anchor(anchor) .snap_to_window_with_margin(px(8.))
.when_some(menu_view, |this, menu| { .anchor(anchor)
// Focus the menu, so that can be handle the action. .when_some(menu_view, |this, menu| {
if !menu.focus_handle(cx).contains_focused(window, cx) { // Focus the menu, so that can be handle the action.
menu.focus_handle(cx).focus(window); if !menu.focus_handle(cx).contains_focused(window, cx) {
} menu.focus_handle(cx).focus(window);
}
this.child(div().occlude().child(menu.clone())) this.child(div().occlude().child(menu.clone()))
}), }),
) )
.with_priority(1) .with_priority(1)
.into_any(); .into_any(),
);
let menu_layout_id = menu_element.request_layout(window, cx);
(Some(menu_element), Some(menu_layout_id))
} else {
(None, None)
} }
} else {
(None, None)
};
let mut layout_ids = vec![];
if let Some(menu_layout_id) = menu_layout_id {
layout_ids.push(menu_layout_id);
} }
let layout_id = window.request_layout(style, layout_ids, cx); let mut element = this
.element
.take()
.expect("Element should exists.")
.children(menu_element)
.into_any_element();
let layout_id = element.request_layout(window, cx);
( (
layout_id, layout_id,
ContextMenuState { ContextMenuState {
menu_element, element: Some(element),
..Default::default() ..Default::default()
}, },
) )
@ -202,8 +216,8 @@ impl Element for ContextMenu {
window: &mut Window, window: &mut Window,
cx: &mut App, cx: &mut App,
) -> Self::PrepaintState { ) -> Self::PrepaintState {
if let Some(menu_element) = &mut request_layout.menu_element { if let Some(element) = &mut request_layout.element {
menu_element.prepaint(window, cx); element.prepaint(window, cx);
} }
} }
@ -217,8 +231,8 @@ impl Element for ContextMenu {
window: &mut Window, window: &mut Window,
cx: &mut App, cx: &mut App,
) { ) {
if let Some(menu_element) = &mut request_layout.menu_element { if let Some(element) = &mut request_layout.element {
menu_element.paint(window, cx); element.paint(window, cx);
} }
let Some(builder) = self.menu.take() else { let Some(builder) = self.menu.take() else {

View file

@ -1170,7 +1170,12 @@ where
} }
/// Calculate the extra rows needed to fill the table empty space when `stripe` is true. /// Calculate the extra rows needed to fill the table empty space when `stripe` is true.
fn calculate_extra_rows_needed(&self, total_height: Pixels, actual_height: Pixels, row_height: Pixels) -> usize { fn calculate_extra_rows_needed(
&self,
total_height: Pixels,
actual_height: Pixels,
row_height: Pixels,
) -> usize {
let mut extra_rows_needed = 0; let mut extra_rows_needed = 0;
let remaining_height = total_height - actual_height; let remaining_height = total_height - actual_height;
@ -1303,7 +1308,8 @@ where
.size .size
.height; .height;
let actual_height = row_height * rows_count as f32; let actual_height = row_height * rows_count as f32;
let extra_rows_count = self.calculate_extra_rows_needed(total_height, actual_height, row_height); let extra_rows_count =
self.calculate_extra_rows_needed(total_height, actual_height, row_height);
let render_rows_count = if self.options.stripe { let render_rows_count = if self.options.stripe {
rows_count + extra_rows_count rows_count + extra_rows_count
} else { } else {