use super::overlay::{DropSide, cross_origin};
use gpui_kit::{
Anchor, AnyElement, App, AvailableSpace, Bounds, DispatchPhase, Element, Entity,
GlobalElementId, Hsla, InspectorElementId, IntoElement, LayoutId, MouseExitEvent,
MouseMoveEvent, ParentElement as _, PathBuilder, Pixels, Point, Styled, Task, Window, canvas,
point, px,
};
use std::{cell::Cell, rc::Rc, time::Duration};
pub const CARET_WIDTH: f32 = 12.;
pub const CARET_HEIGHT: f32 = 6.;
pub const POPOVER_OFFSET: f32 = 10.;
pub const TOOLTIP_OFFSET: f32 = 12.;
pub const NO_CARET_GAP: f32 = 4.;
pub const NO_CARET_SHIFT: f32 = 16.;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum Align {
Top,
TopLeft,
TopRight,
#[default]
Bottom,
BottomLeft,
BottomRight,
Left,
LeftTop,
LeftBottom,
Right,
RightTop,
RightBottom,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Side {
Top,
Bottom,
Left,
Right,
}
impl Align {
pub const ALL: [Align; 12] = [
Self::Top,
Self::TopLeft,
Self::TopRight,
Self::Bottom,
Self::BottomLeft,
Self::BottomRight,
Self::Left,
Self::LeftTop,
Self::LeftBottom,
Self::Right,
Self::RightTop,
Self::RightBottom,
];
pub const fn name(self) -> &'static str {
match self {
Self::Top => "top",
Self::TopLeft => "top-left",
Self::TopRight => "top-right",
Self::Bottom => "bottom",
Self::BottomLeft => "bottom-left",
Self::BottomRight => "bottom-right",
Self::Left => "left",
Self::LeftTop => "left-top",
Self::LeftBottom => "left-bottom",
Self::Right => "right",
Self::RightTop => "right-top",
Self::RightBottom => "right-bottom",
}
}
pub const fn side(self) -> Side {
match self {
Self::Top | Self::TopLeft | Self::TopRight => Side::Top,
Self::Bottom | Self::BottomLeft | Self::BottomRight => Side::Bottom,
Self::Left | Self::LeftTop | Self::LeftBottom => Side::Left,
Self::Right | Self::RightTop | Self::RightBottom => Side::Right,
}
}
pub const fn cross(self) -> i8 {
match self {
Self::TopLeft | Self::BottomLeft | Self::LeftTop | Self::RightTop => -1,
Self::TopRight | Self::BottomRight | Self::LeftBottom | Self::RightBottom => 1,
_ => 0,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Placement {
pub anchor: Anchor,
pub gap: f32,
pub cross_fraction: f32,
pub cross_px: f32,
pub caret_at: Option<(f32, f32)>,
}
impl Placement {
pub fn of(align: Align, caret: bool, offset: f32) -> Self {
let anchor = align.side().anchor();
let shift = if caret { 2. * offset } else { NO_CARET_SHIFT };
let (cross_fraction, cross_px) = match align.cross() {
-1 => (0.5, -shift),
1 => (-0.5, shift),
_ => (0., 0.),
};
let caret_at = caret.then(|| match align.cross() {
-1 => (0., shift),
1 => (1., -shift),
_ => (0.5, 0.),
});
Self {
anchor,
gap: if caret { offset } else { NO_CARET_GAP },
cross_fraction,
cross_px,
caret_at,
}
}
}
impl Side {
pub const fn opposite(self) -> Self {
match self {
Self::Top => Self::Bottom,
Self::Bottom => Self::Top,
Self::Left => Self::Right,
Self::Right => Self::Left,
}
}
pub const fn vertical(self) -> bool {
matches!(self, Self::Top | Self::Bottom)
}
pub const fn anchor(self) -> Anchor {
match self {
Self::Top => Anchor::BottomCenter,
Self::Bottom => Anchor::TopCenter,
Self::Left => Anchor::RightCenter,
Self::Right => Anchor::LeftCenter,
}
}
pub fn choose(
self,
trigger: Bounds<Pixels>,
extent: f32,
viewport: gpui_kit::Size<Pixels>,
) -> Self {
let (top, bottom) = (f32::from(trigger.top()), f32::from(trigger.bottom()));
let (left, right) = (f32::from(trigger.left()), f32::from(trigger.right()));
let (vw, vh) = (f32::from(viewport.width), f32::from(viewport.height));
let flipped = match self {
Self::Bottom => DropSide::choose(top, bottom, extent, vh),
Self::Top => DropSide::choose(vh - bottom, vh - top, extent, vh),
Self::Right => DropSide::choose(left, right, extent, vw),
Self::Left => DropSide::choose(vw - right, vw - left, extent, vw),
} == DropSide::Above;
if flipped { self.opposite() } else { self }
}
pub fn main_origin(self, trigger: Bounds<Pixels>, depth: f32, gap: f32) -> f32 {
match self {
Self::Bottom => f32::from(trigger.bottom()) + gap,
Self::Top => f32::from(trigger.top()) - gap - depth,
Self::Right => f32::from(trigger.right()) + gap,
Self::Left => f32::from(trigger.left()) - gap - depth,
}
}
fn logical(self, rtl: bool) -> Self {
match self {
Self::Left | Self::Right if rtl => self.opposite(),
_ => self,
}
}
}
pub fn caret_points(side: Side, surface: Bounds<Pixels>, at: (f32, f32)) -> [Point<Pixels>; 3] {
let (o, s) = (surface.origin, surface.size);
let (fraction, shift) = at;
let (half, h) = (px(CARET_WIDTH / 2.), px(CARET_HEIGHT));
match side {
Side::Bottom | Side::Top => {
let x = o.x + s.width * fraction + px(shift);
let (edge, tip) = if side == Side::Bottom {
(o.y, o.y - h)
} else {
(o.y + s.height, o.y + s.height + h)
};
[point(x - half, edge), point(x, tip), point(x + half, edge)]
}
Side::Right | Side::Left => {
let y = o.y + s.height * fraction + px(shift);
let (edge, tip) = if side == Side::Right {
(o.x, o.x - h)
} else {
(o.x + s.width, o.x + s.width + h)
};
[point(edge, y - half), point(tip, y), point(edge, y + half)]
}
}
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn anchored(
id: impl Into<gpui_kit::ElementId>,
trigger: AnyElement,
surface: Option<gpui_kit::Stateful<gpui_kit::Div>>,
align: Align,
caret_color: Option<Hsla>,
offset: f32,
window: &mut Window,
cx: &mut App,
) -> AnyElement {
let id: gpui_kit::ElementId = id.into();
let placement = Placement::of(align, caret_color.is_some(), offset);
let rtl = gpui_kit::base::LayoutDirection::global(cx).is_rtl();
let preferred = align.side().logical(rtl);
let chosen = window
.use_keyed_state((id.clone(), "side"), cx, move |_, _| {
Rc::new(Cell::new(preferred))
})
.read(cx)
.clone();
if surface.is_none() {
chosen.set(preferred);
}
let measured = window
.use_keyed_state((id.clone(), "measured"), cx, |_, _| {
Rc::new(Cell::new(gpui_kit::Size::<Pixels>::default()))
})
.read(cx)
.clone();
let trigger_bounds = Rc::new(Cell::new(None));
let popup = gpui_kit::base::Popup::new(id, trigger)
.anchor(chosen.get().logical(rtl).anchor())
.offset(px(placement.gap))
.on_position({
let trigger_bounds = trigger_bounds.clone();
move |_, trigger| trigger_bounds.set(Some(trigger))
});
let Some(surface) = surface else {
return popup.into_any_element();
};
let surface_layout = Rc::new(Cell::new(None));
let viewport = window.viewport_size();
popup
.content(Placed {
child: gpui_kit::div()
.relative()
.w(viewport.width)
.h(viewport.height)
.child(gpui_kit::div().absolute().top_0().left_0().child(Measure {
child: surface.into_any_element(),
layout: surface_layout.clone(),
}))
.into_any_element(),
surface_layout,
preferred,
placement,
caret_color,
trigger: trigger_bounds,
chosen,
measured,
})
.into_any_element()
}
struct Placed {
child: AnyElement,
preferred: Side,
placement: Placement,
caret_color: Option<Hsla>,
trigger: Rc<Cell<Option<Bounds<Pixels>>>>,
chosen: Rc<Cell<Side>>,
measured: Rc<Cell<gpui_kit::Size<Pixels>>>,
surface_layout: Rc<Cell<Option<LayoutId>>>,
}
struct Measure {
child: AnyElement,
layout: Rc<Cell<Option<LayoutId>>>,
}
impl Element for Measure {
type RequestLayoutState = ();
type PrepaintState = ();
fn id(&self) -> Option<gpui_kit::ElementId> {
None
}
fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
None
}
fn request_layout(
&mut self,
_: Option<&GlobalElementId>,
_: Option<&InspectorElementId>,
window: &mut Window,
cx: &mut App,
) -> (LayoutId, ()) {
let id = self.child.request_layout(window, cx);
self.layout.set(Some(id));
(id, ())
}
fn prepaint(
&mut self,
_: Option<&GlobalElementId>,
_: Option<&InspectorElementId>,
_: Bounds<Pixels>,
_: &mut (),
window: &mut Window,
cx: &mut App,
) {
self.child.prepaint(window, cx);
}
fn paint(
&mut self,
_: Option<&GlobalElementId>,
_: Option<&InspectorElementId>,
_: Bounds<Pixels>,
_: &mut (),
_: &mut (),
window: &mut Window,
cx: &mut App,
) {
self.child.paint(window, cx);
}
}
impl Element for Placed {
type RequestLayoutState = ();
type PrepaintState = Option<(Side, Bounds<Pixels>)>;
fn id(&self) -> Option<gpui_kit::ElementId> {
None
}
fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
None
}
fn request_layout(
&mut self,
_: Option<&GlobalElementId>,
_: Option<&InspectorElementId>,
window: &mut Window,
cx: &mut App,
) -> (LayoutId, ()) {
let size = self.measured.get();
let mut style = gpui_kit::Style::default();
style.size.width = size.width.into();
style.size.height = size.height.into();
(window.request_layout(style, [], cx), ())
}
fn prepaint(
&mut self,
_: Option<&GlobalElementId>,
_: Option<&InspectorElementId>,
bounds: Bounds<Pixels>,
_: &mut (),
window: &mut Window,
cx: &mut App,
) -> Self::PrepaintState {
let viewport = window.viewport_size();
self.child.layout_as_root(
gpui_kit::Size {
width: AvailableSpace::Definite(viewport.width),
height: AvailableSpace::Definite(viewport.height),
},
window,
cx,
);
let size = self
.surface_layout
.get()
.map_or(gpui_kit::Size::default(), |id| {
window.layout_bounds(id).size
});
if size != self.measured.get() {
self.measured.set(size);
window.request_animation_frame();
}
let Some(trigger) = self.trigger.get() else {
self.child.prepaint_at(bounds.origin, window, cx);
return None;
};
let placed = place(
self.preferred,
self.placement,
trigger,
size,
window.viewport_size(),
);
let side = placed.0;
if side != self.chosen.get() {
self.chosen.set(side);
window.request_animation_frame();
}
self.child.prepaint_at(placed.1.origin, window, cx);
Some(placed)
}
fn paint(
&mut self,
_: Option<&GlobalElementId>,
_: Option<&InspectorElementId>,
_: Bounds<Pixels>,
_: &mut (),
placed: &mut Self::PrepaintState,
window: &mut Window,
cx: &mut App,
) {
self.child.paint(window, cx);
let (Some((side, surface)), Some(at), Some(color)) =
(*placed, self.placement.caret_at, self.caret_color)
else {
return;
};
let pts = caret_points(side, surface, at);
let mut path = PathBuilder::fill();
path.move_to(pts[0]);
path.line_to(pts[1]);
path.line_to(pts[2]);
path.close();
if let Ok(path) = path.build() {
window.paint_path(path, color);
}
}
}
pub fn place(
preferred: Side,
placement: Placement,
trigger: Bounds<Pixels>,
size: gpui_kit::Size<Pixels>,
viewport: gpui_kit::Size<Pixels>,
) -> (Side, Bounds<Pixels>) {
let (depth, along, center, room) = if preferred.vertical() {
(size.height, size.width, trigger.center().x, viewport.width)
} else {
(size.width, size.height, trigger.center().y, viewport.height)
};
let (depth, along) = (f32::from(depth), f32::from(along));
let side = preferred.choose(trigger, depth + placement.gap, viewport);
let main = side.main_origin(trigger, depth, placement.gap);
let cross = cross_origin(
f32::from(center),
along,
placement.cross_fraction,
placement.cross_px,
f32::from(room),
);
let origin = if side.vertical() {
point(px(cross), px(main))
} else {
point(px(main), px(cross))
};
(side, Bounds::new(origin, size))
}
pub(crate) struct HoverIntent {
pub open: bool,
outside: bool,
pointer_in: bool,
rest: bool,
generation: u64,
_task: Option<Task<()>>,
}
pub(crate) fn hover_intent(
id: impl Into<gpui_kit::ElementId>,
open: bool,
rest: bool,
window: &mut Window,
cx: &mut App,
) -> Entity<HoverIntent> {
window.use_keyed_state(id, cx, move |_, _| HoverIntent {
open,
outside: false,
pointer_in: false,
rest,
generation: 0,
_task: None,
})
}
pub(crate) fn schedule(intent: &Entity<HoverIntent>, open: bool, delay: Duration, cx: &mut App) {
intent.update(cx, |state, cx| {
if open && state.outside {
return;
}
state.generation += 1;
let generation = state.generation;
if delay.is_zero() || state.open == open {
state._task = None;
if state.open != open {
state.open = open;
cx.notify();
}
return;
}
state._task = Some(cx.spawn(async move |this, cx| {
cx.background_executor().timer(delay).await;
let _ = this.update(cx, |state, cx| {
if state.generation == generation {
state.open = open;
cx.notify();
}
});
}));
});
}
pub(crate) fn pointer(intent: &Entity<HoverIntent>, inside: bool, delay: Duration, cx: &mut App) {
let target = {
let state = intent.read(cx);
if inside { true } else { state.rest }
};
intent.update(cx, |state, _| state.pointer_in = inside);
schedule(intent, target, delay, cx);
}
pub(crate) fn window_exit_guard(intent: Entity<HoverIntent>, delay: Duration) -> impl IntoElement {
canvas(
|_, _, _| {},
move |_, _, window, _| {
let exit = intent.clone();
window.on_mouse_event(move |_: &MouseExitEvent, phase, _, cx| {
if phase == DispatchPhase::Bubble {
let was_in = exit.read(cx).pointer_in;
exit.update(cx, |state, _| state.outside = true);
if was_in {
pointer(&exit, false, delay, cx);
}
}
});
let moved = intent.clone();
window.on_mouse_event(move |_: &MouseMoveEvent, phase, _, cx| {
if phase == DispatchPhase::Capture && moved.read(cx).outside {
moved.update(cx, |state, _| state.outside = false);
}
});
},
)
.absolute()
.size_0()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn alignments_follow_popover_rules() {
assert_eq!(Align::ALL.len(), 12);
assert_eq!(Align::BottomLeft.name(), "bottom-left");
let bottom = Placement::of(Align::Bottom, true, POPOVER_OFFSET);
assert_eq!(bottom.anchor, Anchor::TopCenter);
assert_eq!((bottom.gap, bottom.cross_fraction), (10., 0.));
assert_eq!(bottom.caret_at, Some((0.5, 0.)));
let start = Placement::of(Align::BottomLeft, true, POPOVER_OFFSET);
assert_eq!((start.cross_fraction, start.cross_px), (0.5, -20.));
assert_eq!(start.caret_at, Some((0., 20.)));
let plain = Placement::of(Align::TopRight, false, 0.);
assert_eq!(plain.anchor, Anchor::BottomCenter);
assert_eq!((plain.gap, plain.cross_px, plain.caret_at), (4., 16., None));
assert_eq!(Placement::of(Align::Top, true, TOOLTIP_OFFSET).gap, 12.);
assert_eq!(
Placement::of(Align::RightTop, true, 10.).anchor,
Anchor::LeftCenter
);
}
fn rect(x: f32, y: f32, w: f32, h: f32) -> Bounds<Pixels> {
Bounds::new(point(px(x), px(y)), gpui_kit::size(px(w), px(h)))
}
#[test]
fn surfaces_flip_to_the_opposite_side_instead_of_covering_the_trigger() {
let viewport = gpui_kit::size(px(1440.), px(900.));
let trigger = rect(296., 768., 154., 32.);
let start = Placement::of(Align::BottomLeft, true, POPOVER_OFFSET);
let size = gpui_kit::size(px(192.), px(120.));
let (side, bounds) = place(Side::Bottom, start, trigger, size, viewport);
assert_eq!(side, Side::Top);
assert_eq!(bounds.bottom(), px(758.));
assert!(bounds.bottom() <= trigger.top());
assert_eq!(bounds.left(), px(296. + 77. - 20.));
let caret = caret_points(side, bounds, start.caret_at.unwrap());
assert_eq!(caret[1], point(px(373.), px(764.)));
assert_eq!((caret[0].y, caret[2].y), (px(758.), px(758.)));
assert_eq!(caret[2].x - caret[0].x, px(CARET_WIDTH));
let high = rect(296., 300., 154., 32.);
let (side, bounds) = place(Side::Bottom, start, high, size, viewport);
assert_eq!((side, bounds.top()), (Side::Bottom, px(342.)));
let caret = caret_points(side, bounds, start.caret_at.unwrap());
assert_eq!(caret[1], point(px(373.), px(336.)));
let tip = Placement::of(Align::Top, true, TOOLTIP_OFFSET);
let small = gpui_kit::size(px(100.), px(50.));
assert_eq!(
place(Side::Top, tip, rect(0., 60., 32., 32.), small, viewport).0,
Side::Bottom
);
assert_eq!(
place(Side::Top, tip, rect(0., 70., 32., 32.), small, viewport).0,
Side::Top
);
assert_eq!(
place(Side::Top, tip, rect(0., 69., 32., 32.), small, viewport).0,
Side::Bottom
);
let wide = gpui_kit::size(px(200.), px(40.));
let edge = rect(1380., 400., 32., 32.);
let (side, bounds) = place(Side::Right, tip, edge, wide, viewport);
assert_eq!((side, bounds.right()), (Side::Left, px(1368.)));
assert_eq!(
place(Side::Left, tip, rect(20., 400., 32., 32.), wide, viewport).0,
Side::Right
);
}
#[test]
fn a_surface_with_room_on_neither_side_overflows_instead_of_covering() {
let viewport = gpui_kit::size(px(1440.), px(900.));
let plain = Placement::of(Align::Bottom, false, 0.);
let size = gpui_kit::size(px(300.), px(600.));
let trigger = rect(600., 500., 100., 32.);
let (side, bounds) = place(Side::Bottom, plain, trigger, size, viewport);
assert_eq!(side, Side::Top);
assert_eq!(bounds.bottom(), px(496.));
assert_eq!(bounds.top(), px(-104.));
let middle = rect(600., 434., 100., 32.);
assert_eq!(
place(Side::Bottom, plain, middle, size, viewport).0,
Side::Bottom
);
assert_eq!(place(Side::Top, plain, middle, size, viewport).0, Side::Top);
let corner = rect(1420., 100., 20., 20.);
let (_, bounds) = place(Side::Bottom, plain, corner, size, viewport);
assert_eq!(bounds.right(), px(1432.));
}
#[test]
fn sides_flip_and_anchor() {
for side in [Side::Top, Side::Bottom, Side::Left, Side::Right] {
assert_eq!(side.opposite().opposite(), side);
assert_eq!(side.logical(false), side);
}
assert_eq!(Side::Left.logical(true), Side::Right);
assert_eq!(Side::Top.logical(true), Side::Top);
assert_eq!(Side::Top.anchor(), Anchor::BottomCenter);
assert_eq!(Side::Right.anchor(), Anchor::LeftCenter);
}
#[test]
fn caret_size_follows_popover_caret() {
assert_eq!((CARET_WIDTH, CARET_HEIGHT), (12., 6.));
}
}