ui: Open submenus and popovers on the side that has room (#66496)

Follow up of https://github.com/zed-industries/zed/pull/66482

Wide submenus could open on top of their own menu, and popovers near the
window bottom got pushed up over their button. The side was picked while
rendering, before the menu's real size was known, so submenus guessed
200px wide and popovers never switched sides at all.

This adds `Anchored::attach(target, corner)` to GPUI, which picks the
side during layout using the real size and moves the element to the
other side of the target when it doesn't fit. Submenus and `PopoverMenu`
use it.

`DropdownMenu` now opens left-aligned under its button, and settings row
dropdowns opt into right alignment.

Left out on purpose:
- Pickers can switch between above and below as the list shrinks while
you type. Using the side that fits seems better than a stale one.

Before:
<img width="300"
src="https://github.com/user-attachments/assets/9a45aba2-6149-4835-8aa5-c2e8ae49c9b2"
/>


After:

<img width="300"
src="https://github.com/user-attachments/assets/148e205d-dd6b-4c59-9ed4-5ad37054725e"
/>

<img width="300"
src="https://github.com/user-attachments/assets/88a24ac6-e1c5-4e92-b9be-26f813b1b576"
/>


Release Notes:

- Fixed wide submenus and popovers covering the menu or button they open
from.
- [GPUI] Added `Anchored::attach` to place an element next to a target
and flip it to the other side when it doesn't fit.
This commit is contained in:
Smit Barmase
2026-11-03 20:28:13 +00:00
committed by GitHub
parent b61f33f8b6
commit ce6c5413f1
6 changed files with 465 additions and 46 deletions
+190 -9
View File
@@ -1,3 +1,5 @@
use std::cmp::Ordering;
use smallvec::SmallVec;
use crate::{
@@ -17,11 +19,21 @@ pub struct Anchored {
children: SmallVec<[AnyElement; 2]>,
anchor: Anchor,
fit_mode: AnchoredFitMode,
anchor_position: Option<Point<Pixels>>,
placement: Placement,
position_mode: AnchoredPositionMode,
offset: Option<Point<Pixels>>,
}
#[derive(Clone, Copy)]
enum Placement {
InPlace,
At(Point<Pixels>),
Attached {
target: Bounds<Pixels>,
corner: Anchor,
},
}
/// anchored gives you an element that will avoid overflowing the window bounds.
/// Its children should have no margin to avoid measurement issues.
pub fn anchored() -> Anchored {
@@ -29,7 +41,7 @@ pub fn anchored() -> Anchored {
children: SmallVec::new(),
anchor: Anchor::TopLeft,
fit_mode: AnchoredFitMode::SwitchAnchor,
anchor_position: None,
placement: Placement::InPlace,
position_mode: AnchoredPositionMode::Window,
offset: None,
}
@@ -45,7 +57,20 @@ impl Anchored {
/// Sets the position in window coordinates
/// (otherwise the location the anchored element is rendered is used)
pub fn position(mut self, anchor: Point<Pixels>) -> Self {
self.anchor_position = Some(anchor);
self.placement = Placement::At(anchor);
self
}
/// Places the element next to `target`, with the element's [`Anchored::anchor`] corner
/// on `corner` of `target`. For example, a submenu puts its top-left corner on its row's
/// top-right corner. Use this instead of [`Anchored::position`].
///
/// If the element doesn't fit in the window, it moves to the other side of `target`, as
/// long as that side fits better. A submenu moves from the right of its row to the left,
/// and a dropdown moves from below its button to above. The offset flips with it.
/// [`AnchoredFitMode::SwitchAnchor`] has no effect here.
pub fn attach(mut self, target: Bounds<Pixels>, corner: Anchor) -> Self {
self.placement = Placement::Attached { target, corner };
self
}
@@ -57,8 +82,9 @@ impl Anchored {
}
/// Sets the position mode for this anchored element. Local will have this
/// interpret its [`Anchored::position`] as relative to the parent element.
/// While Window will have it interpret the position as relative to the window.
/// interpret its [`Anchored::position`] or [`Anchored::attach`] target as
/// relative to the parent element. While Window will have it interpret the
/// position as relative to the window.
pub fn position_mode(mut self, mode: AnchoredPositionMode) -> Self {
self.position_mode = mode;
self
@@ -139,8 +165,13 @@ impl Element for Anchored {
.reduce(|acc, bounds| acc.union(&bounds))
.unwrap();
let anchor_position = match self.placement {
Placement::InPlace => None,
Placement::At(position) => Some(position),
Placement::Attached { target, corner } => Some(target.corner(corner)),
};
let (origin, mut desired) = self.position_mode.get_position_and_bounds(
self.anchor_position,
anchor_position,
self.anchor,
children_bounds.size,
bounds,
@@ -152,7 +183,53 @@ impl Element for Anchored {
size: window.viewport_size(),
};
if self.fit_mode == AnchoredFitMode::SwitchAnchor {
if let Placement::Attached { target, mut corner } = self.placement {
// Compare against the window edges, not the snap margin, so an element that
// already fits doesn't move. The client inset doesn't count as room either,
// since on Linux it's the window's transparent shadow.
let visible = limits.inset(window.client_inset.unwrap_or(px(0.)));
let overflow_along = |bounds: Bounds<Pixels>, axis: Axis| match axis {
Axis::Horizontal => {
(visible.left() - bounds.left()).max(px(0.))
+ (bounds.right() - visible.right()).max(px(0.))
}
Axis::Vertical => {
(visible.top() - bounds.top()).max(px(0.))
+ (bounds.bottom() - visible.bottom()).max(px(0.))
}
};
let mut anchor = self.anchor;
let mut offset = self.offset.unwrap_or_default();
for axis in [Axis::Horizontal, Axis::Vertical] {
let corner_side = side_along(corner, axis);
let is_outside_target = corner_side != Ordering::Equal
&& side_along(anchor, axis) == corner_side.reverse();
let overflow = overflow_along(desired, axis);
if !is_outside_target || overflow == px(0.) {
continue;
}
let flipped_corner = corner.other_side_along(axis);
let flipped_anchor = anchor.other_side_along(axis);
let flipped_offset = match axis {
Axis::Horizontal => point(-offset.x, offset.y),
Axis::Vertical => point(offset.x, -offset.y),
};
let (_, flipped) = self.position_mode.get_position_and_bounds(
Some(target.corner(flipped_corner)),
flipped_anchor,
children_bounds.size,
bounds,
Some(flipped_offset),
);
if overflow_along(flipped, axis) < overflow {
corner = flipped_corner;
anchor = flipped_anchor;
offset = flipped_offset;
desired = flipped;
}
}
} else if self.fit_mode == AnchoredFitMode::SwitchAnchor {
let mut anchor = self.anchor;
if desired.left() < limits.left() || desired.right() > limits.right() {
@@ -238,6 +315,23 @@ impl IntoElement for Anchored {
}
}
/// Which side of a box `anchor` is on along `axis`. `Less` is left or top, `Equal` is the
/// center, and `Greater` is right or bottom.
fn side_along(anchor: Anchor, axis: Axis) -> Ordering {
match axis {
Axis::Horizontal => match anchor {
Anchor::TopLeft | Anchor::BottomLeft | Anchor::LeftCenter => Ordering::Less,
Anchor::TopCenter | Anchor::BottomCenter => Ordering::Equal,
Anchor::TopRight | Anchor::BottomRight | Anchor::RightCenter => Ordering::Greater,
},
Axis::Vertical => match anchor {
Anchor::TopLeft | Anchor::TopRight | Anchor::TopCenter => Ordering::Less,
Anchor::LeftCenter | Anchor::RightCenter => Ordering::Equal,
Anchor::BottomLeft | Anchor::BottomRight | Anchor::BottomCenter => Ordering::Greater,
},
}
}
/// Which algorithm to use when fitting the anchored element to be inside the window.
#[derive(Copy, Clone, PartialEq)]
pub enum AnchoredFitMode {
@@ -291,8 +385,8 @@ impl AnchoredPositionMode {
#[cfg(test)]
mod tests {
use crate::{
Context, Pixels, PlatformInput, Point, TestAppContext, Window, deferred, div, point,
prelude::*, px, size,
Anchor, Bounds, Context, Pixels, PlatformInput, Point, TestAppContext, Window, deferred,
div, point, prelude::*, px, size,
};
struct AnchoredTestView {
@@ -395,4 +489,91 @@ mod tests {
assert_eq!(menu_bounds.origin, point(px(100.), px(300.)));
assert_eq!(menu_bounds.size, size(px(200.), px(300.)));
}
struct AttachedTestView {
target: Bounds<Pixels>,
corner: Anchor,
anchor: Anchor,
}
impl Render for AttachedTestView {
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
div().size_full().child(
deferred(
super::anchored()
.attach(self.target, self.corner)
.anchor(self.anchor)
.offset(point(px(-2.), px(4.)))
.snap_to_window_with_margin(px(8.))
.child(
div()
.debug_selector(|| "MENU".into())
.w(px(200.))
.h(px(300.)),
),
)
.with_priority(1),
)
}
}
#[gpui::test]
fn test_anchored_attach_moves_to_the_side_with_room(cx: &mut TestAppContext) {
let trigger = |x: f32, y: f32| Bounds::new(point(px(x), px(y)), size(px(100.), px(20.)));
// A submenu sits to the right of its trigger, with their top edges lined up.
let submenu = (Anchor::TopRight, Anchor::TopLeft);
// A dropdown sits below its button, with their left edges lined up.
let dropdown = (Anchor::BottomLeft, Anchor::TopLeft);
for (target, (corner, anchor), expected_origin) in [
(trigger(100., 100.), submenu, point(px(198.), px(104.))),
(trigger(550., 100.), submenu, point(px(352.), px(104.))),
(trigger(100., 400.), dropdown, point(px(98.), px(96.))),
// Ends 4px from the window edge. That's inside the snap margin but still fits,
// so it stays.
(trigger(498., 100.), submenu, point(px(596.), px(104.))),
// Doesn't fit on either side. The left sticks out less, so it goes left and
// slides back into the window.
(
Bounds::new(point(px(180.), px(100.)), size(px(500.), px(20.))),
submenu,
point(px(8.), px(104.)),
),
// Doesn't fit on either side, but the right sticks out less, so it stays right
// and slides back into the window.
(
Bounds::new(point(px(50.), px(100.)), size(px(650.), px(20.))),
submenu,
point(px(592.), px(104.)),
),
// A dropdown that runs off the right edge slides left. It never moves beside its
// button.
(trigger(700., 100.), dropdown, point(px(592.), px(124.))),
// Centered under its button, so it can move above it but never sideways.
(
trigger(100., 400.),
(Anchor::BottomCenter, Anchor::TopCenter),
point(px(48.), px(96.)),
),
] {
let window = cx.open_window(size(px(800.), px(600.)), |_, _| AttachedTestView {
target,
corner,
anchor,
});
cx.run_until_parked();
let menu_bounds = window
.update(cx, |_, window, _| {
window.rendered_frame.debug_bounds.get("MENU").copied()
})
.unwrap()
.expect("MENU debug bounds not found");
assert_eq!(
menu_bounds.origin, expected_origin,
"target: {target:?}, corner: {corner:?}, anchor: {anchor:?}"
);
}
}
}
@@ -132,6 +132,7 @@ impl RenderOnce for EnumVariantDropdown {
.when_some(self.tab_index, |elem, tab_index| elem.tab_index(tab_index))
.trigger_size(ButtonSize::Medium)
.style(DropdownStyle::Outlined)
.attach(gpui::Anchor::BottomRight)
.offset(gpui::Point {
x: px(0.0),
y: px(2.0),
@@ -177,7 +177,8 @@ fn render_provider_dropdown(window: &mut Window, cx: &mut App) -> AnyElement {
.child(
DropdownMenu::new("provider-dropdown", current_provider_name, menu)
.tab_index(0)
.style(DropdownStyle::Outlined),
.style(DropdownStyle::Outlined)
.attach(gpui::Anchor::BottomRight),
),
)
.into_any_element()
+62 -22
View File
@@ -1667,7 +1667,6 @@ impl ContextMenu {
ix,
submenu,
is_active_descendant(!submenu.disabled),
window,
cx,
)
.into_any_element(),
@@ -1679,7 +1678,6 @@ impl ContextMenu {
ix: usize,
submenu: &ContextMenuSubmenu,
is_active_descendant: bool,
window: &Window,
cx: &mut Context<Self>,
) -> impl IntoElement {
let ContextMenuSubmenu {
@@ -1848,7 +1846,7 @@ impl ContextMenu {
),
)
.when_some(submenu, |this, (submenu, trigger_bounds)| {
this.child(self.render_submenu_container(ix, submenu, trigger_bounds, window, cx))
this.child(self.render_submenu_container(ix, submenu, trigger_bounds.size, cx))
})
}
@@ -1870,21 +1868,9 @@ impl ContextMenu {
&self,
ix: usize,
submenu: Entity<ContextMenu>,
trigger_bounds: Bounds<Pixels>,
window: &Window,
trigger_size: Size<Pixels>,
cx: &mut Context<Self>,
) -> impl IntoElement {
let space_on_right = window.viewport_size().width - trigger_bounds.right();
let space_on_left = trigger_bounds.left();
let flip_left = space_on_right < CONTEXT_MENU_MIN_WIDTH && space_on_left > space_on_right;
let anchor_position = point(
if flip_left {
px(2.)
} else {
trigger_bounds.size.width - px(2.)
},
px(0.),
);
let bounds_cell = self.submenu_bounds.clone();
let canvas = canvas(
{
@@ -1904,13 +1890,13 @@ impl ContextMenu {
div().absolute().top_0().left_0().w(px(0.)).h(px(0.)).child(
deferred(
anchored()
.position(anchor_position)
.position_mode(AnchoredPositionMode::Local)
.anchor(if flip_left {
Anchor::TopRight
} else {
Anchor::TopLeft
})
.attach(
Bounds::new(Point::default(), trigger_size),
Anchor::TopRight,
)
.anchor(Anchor::TopLeft)
.offset(point(px(-2.), px(0.)))
.snap_to_window_with_margin(px(8.0))
.child(
div()
@@ -3102,6 +3088,60 @@ mod tests {
}
}
#[gpui::test]
fn wide_submenu_opens_on_the_side_it_fits(cx: &mut TestAppContext) {
cx.update(|cx| {
let settings_store = settings::SettingsStore::test(cx);
cx.set_global(settings_store);
theme_settings::init(theme::LoadThemes::JustBase, cx);
});
let window = cx.open_window(size(px(900.), px(400.)), |window, cx| {
let menu = ContextMenu::build(window, cx, |menu, _, _| {
menu.submenu("Wide", |menu, _, _| {
menu.custom_row(|_, _| div().w(px(320.)).child("wide").into_any_element())
})
});
SubmenuTestView {
menu,
left: px(400.),
}
});
cx.run_until_parked();
let menu = window
.update(cx, |view, _, _| view.menu.clone())
.expect("submenu window");
let mut visual = VisualTestContext::from_window(window.into(), cx);
draw_frames(&mut visual);
menu.update_in(&mut visual, |menu, window, cx| {
menu.select_first(&SelectFirst, window, cx);
menu.select_submenu_child(&SelectChild, window, cx);
});
draw_frames(&mut visual);
menu.read_with(&visual, |menu, _| {
let trigger = menu
.submenu_trigger_bounds
.borrow()
.get(&0)
.copied()
.expect("trigger bounds");
let submenu = menu.submenu_bounds.get().expect("submenu bounds");
let space_on_right = px(900.) - trigger.right();
assert!(
space_on_right > CONTEXT_MENU_MIN_WIDTH && space_on_right < submenu.size.width,
"trigger: {trigger:?}, submenu: {submenu:?}"
);
assert_eq!(
submenu.right(),
trigger.left() + px(2.),
"trigger: {trigger:?}, submenu: {submenu:?}"
);
assert_eq!(submenu.top(), trigger.top());
});
}
#[gpui::test]
fn submenu_content_keeps_focus(cx: &mut TestAppContext) {
let content_focus = cx.update(|cx| cx.focus_handle());
+104 -6
View File
@@ -1,4 +1,4 @@
use gpui::{Anchor, AnyView, Entity, Pixels, Point, Role};
use gpui::{Anchor, AnyView, Axis, Entity, Pixels, Point, Role};
use crate::{ButtonLike, ContextMenu, PopoverMenu, prelude::*};
@@ -125,7 +125,10 @@ impl DropdownMenu {
self
}
/// Defines which corner of the handle to attach the menu's anchor to.
/// Defines which corner of the trigger the menu lines up with. The default,
/// [`Anchor::BottomLeft`], opens the menu below the trigger with their left edges lined
/// up. Use [`Anchor::BottomRight`] to line up the right edges instead, for a trigger at
/// the right end of a row.
pub fn attach(mut self, attach: Anchor) -> Self {
self.attach = Some(attach);
self
@@ -304,11 +307,10 @@ impl RenderOnce for DropdownMenu {
_ => popover,
};
let attach = self.attach.unwrap_or(Anchor::BottomLeft);
popover
.attach(match self.attach {
Some(attach) => attach,
None => Anchor::BottomRight,
})
.attach(attach)
.anchor(attach.other_side_along(Axis::Vertical))
.when_some(self.offset, |this, offset| this.offset(offset))
}
}
@@ -417,3 +419,99 @@ impl Component for DropdownMenu {
.into_any_element()
}
}
#[cfg(test)]
mod tests {
use gpui::{Bounds, TestAppContext, VisualTestContext, size};
use super::*;
struct DropdownTestView {
handle: PopoverMenuHandle<ContextMenu>,
menu: Entity<ContextMenu>,
attach: Option<Anchor>,
at_right_edge: bool,
}
impl Render for DropdownTestView {
fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
let trigger = div()
.absolute()
.top(px(40.))
.map(|this| {
if self.at_right_edge {
this.right(px(40.))
} else {
this.left(px(40.))
}
})
.debug_selector(|| "TRIGGER".into())
.child(
DropdownMenu::new("dropdown", "Pick", self.menu.clone())
.handle(self.handle.clone())
.when_some(self.attach, |this, attach| this.attach(attach)),
);
div().size_full().child(trigger)
}
}
fn open_dropdown(
attach: Option<Anchor>,
at_right_edge: bool,
cx: &mut TestAppContext,
) -> (Bounds<Pixels>, Bounds<Pixels>) {
cx.update(|cx| {
let settings_store = settings::SettingsStore::test(cx);
cx.set_global(settings_store);
theme_settings::init(theme::LoadThemes::JustBase, cx);
});
let handle = PopoverMenuHandle::default();
let window = cx.open_window(size(px(800.), px(600.)), |window, cx| {
let menu = ContextMenu::build(window, cx, |menu, _, _| {
menu.custom_row(|_, _| {
div()
.debug_selector(|| "MENU_ROW".into())
.w(px(300.))
.h(px(20.))
.into_any_element()
})
});
DropdownTestView {
handle: handle.clone(),
menu,
attach,
at_right_edge,
}
});
cx.run_until_parked();
let mut cx = VisualTestContext::from_window(window.into(), cx);
cx.update(|window, cx| window.draw(cx).clear(cx));
cx.update(|window, cx| handle.show(window, cx));
for _ in 0..3 {
cx.update(|window, cx| window.draw(cx).clear(cx));
}
let trigger = cx.debug_bounds("TRIGGER").expect("trigger bounds");
let menu_row = cx.debug_bounds("MENU_ROW").expect("menu row bounds");
(trigger, menu_row)
}
#[gpui::test]
fn dropdown_lines_up_with_its_attached_edge(cx: &mut TestAppContext) {
for (attach, at_right_edge) in [(None, false), (Some(Anchor::BottomRight), true)] {
let (trigger, menu_row) = open_dropdown(attach, at_right_edge, cx);
let (menu_edge, trigger_edge) = if at_right_edge {
(menu_row.right(), trigger.right())
} else {
(menu_row.left(), trigger.left())
};
assert!(
menu_row.top() >= trigger.bottom(),
"attach: {attach:?}, trigger: {trigger:?}, menu row: {menu_row:?}"
);
assert!(
(menu_edge - trigger_edge).abs() < px(12.),
"attach: {attach:?}, trigger: {trigger:?}, menu row: {menu_row:?}"
);
}
}
}
+106 -8
View File
@@ -224,7 +224,8 @@ impl<M: ManagedView> PopoverMenu<M> {
self
}
/// Defines which corner of the handle to attach the menu's anchor to.
/// Defines which corner of the handle to attach the menu's anchor to. If the menu doesn't
/// fit on that side of the handle, it opens on the other side.
pub fn attach(mut self, attach: Anchor) -> Self {
self.attach = Some(attach);
self
@@ -373,14 +374,17 @@ impl<M: ManagedView> Element for PopoverMenu<M> {
let menu_element = element_state.menu.borrow_mut().as_mut().map(|menu| {
let offset = self.resolved_offset(window);
let mut anchored = anchored()
let anchored = anchored()
.snap_to_window_with_margin(px(8.))
.anchor(self.anchor)
.offset(offset);
if let Some(child_bounds) = element_state.child_bounds {
anchored =
anchored.position(child_bounds.corner(self.resolved_attach()) + offset);
}
.anchor(self.anchor);
let anchored = match element_state.child_bounds {
// The offset is doubled on purpose. This used to add it twice, and
// callers picked their offsets with that in mind.
Some(child_bounds) => anchored
.attach(child_bounds, self.resolved_attach())
.offset(offset + offset),
None => anchored.offset(offset),
};
let mut element = deferred(anchored.child(div().occlude().child(menu.clone())))
.with_priority(1)
.into_any();
@@ -506,3 +510,97 @@ impl<M: ManagedView> IntoElement for PopoverMenu<M> {
self
}
}
#[cfg(test)]
mod tests {
use gpui::{EventEmitter, FocusHandle, Focusable, TestAppContext, VisualTestContext};
use super::*;
use crate::Button;
struct TestMenu {
focus_handle: FocusHandle,
}
impl EventEmitter<DismissEvent> for TestMenu {}
impl Focusable for TestMenu {
fn focus_handle(&self, _: &App) -> FocusHandle {
self.focus_handle.clone()
}
}
impl Render for TestMenu {
fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
div()
.track_focus(&self.focus_handle)
.debug_selector(|| "MENU".into())
.w(px(200.))
.h(px(100.))
}
}
struct PopoverTestView {
handle: PopoverMenuHandle<TestMenu>,
top: Pixels,
}
impl Render for PopoverTestView {
fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
div().size_full().child(
div()
.absolute()
.left(px(100.))
.top(self.top)
.debug_selector(|| "TRIGGER".into())
.child(
PopoverMenu::new("popover")
.trigger(Button::new("trigger", "Open"))
.menu(|_, cx| {
Some(cx.new(|cx| TestMenu {
focus_handle: cx.focus_handle(),
}))
})
.with_handle(self.handle.clone()),
),
)
}
}
#[gpui::test]
fn popover_opens_below_its_trigger_or_above_when_it_does_not_fit(cx: &mut TestAppContext) {
cx.update(|cx| {
let settings_store = settings::SettingsStore::test(cx);
cx.set_global(settings_store);
theme_settings::init(theme::LoadThemes::JustBase, cx);
});
for (top, opens_above) in [(px(40.), false), (px(560.), true)] {
let handle = PopoverMenuHandle::default();
let window = cx.open_window(size(px(800.), px(600.)), |_, _| PopoverTestView {
handle: handle.clone(),
top,
});
cx.run_until_parked();
let mut cx = VisualTestContext::from_window(window.into(), cx);
cx.update(|window, cx| window.draw(cx).clear(cx));
cx.update(|window, cx| handle.show(window, cx));
for _ in 0..3 {
cx.update(|window, cx| window.draw(cx).clear(cx));
}
let trigger = cx.debug_bounds("TRIGGER").expect("trigger bounds");
let menu = cx.debug_bounds("MENU").expect("menu bounds");
let offset = cx.update(|window, _| rems_from_px(5_f32) * window.rem_size());
let top = if opens_above {
trigger.top() - menu.size.height
} else {
trigger.bottom()
};
assert_eq!(
menu.origin,
point(trigger.left() - offset - offset, top),
"trigger: {trigger:?}, menu: {menu:?}"
);
}
}
}