Skip to main content

gpui_base/
positioner.rs

1//! Shared popup positioning.
2//!
3//! Every anchored surface in Base resolves its position here so that flipping,
4//! alignment, and viewport clamping cannot drift apart between popups,
5//! tooltips, and menus.
6
7use gpui::{
8    Anchor, AnyElement, App, Bounds, Decorations, Display, Edges, Element, GlobalElementId,
9    Half as _, HitboxBehavior, InspectorElementId, LayoutId, ParentElement, Pixels, Point,
10    Position, Size, Style, Window, point, px,
11};
12
13use crate::{LayoutDirection, Placement};
14use std::{cell::Cell, rc::Rc};
15
16/// Alignment of a popup along the side it is placed on.
17#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
18pub enum Align {
19    /// Align with the trigger's leading edge.
20    Start,
21    /// Center on the trigger.
22    #[default]
23    Center,
24    /// Align with the trigger's trailing edge.
25    End,
26}
27
28/// How a popup derives its position.
29#[derive(Clone, Copy, Debug, PartialEq)]
30enum Strategy {
31    /// Place `anchor`'s corner of the popup at `position`, then clamp into the
32    /// viewport. This reproduces GPUI's `anchored` corner behavior and does not
33    /// flip to the opposite side.
34    Corner {
35        anchor: Anchor,
36        position: Point<Pixels>,
37    },
38    /// Place the popup on `placement`'s side of the trigger, flipping to the
39    /// opposite side when it does not fit, then clamp into the viewport.
40    Side {
41        trigger_bounds: Bounds<Pixels>,
42        placement: Option<Placement>,
43        align: Align,
44        offset: Pixels,
45    },
46}
47
48impl Align {
49    /// The physical alignment along the horizontal axis: `Start` is the
50    /// left edge in LTR and the right edge in RTL.
51    fn horizontal(self, direction: LayoutDirection) -> Self {
52        match (self, direction) {
53            (Align::Start, LayoutDirection::Rtl) => Align::End,
54            (Align::End, LayoutDirection::Rtl) => Align::Start,
55            (align, _) => align,
56        }
57    }
58}
59
60/// The bounds a popup resolved to, and the side it ended up on.
61#[derive(Clone, Copy, Debug, PartialEq)]
62pub struct ResolvedPosition {
63    /// Final popup bounds in window coordinates.
64    pub bounds: Bounds<Pixels>,
65    /// The side the popup was placed on. `None` for corner positioning, which
66    /// has no notion of a side.
67    pub placement: Option<Placement>,
68}
69
70/// An unstyled element that positions its children as an anchored popup.
71///
72/// This owns measurement, side selection, alignment, and viewport clamping. It
73/// installs no presentation of its own and adds no wrapper element around its
74/// children.
75pub struct Positioner {
76    strategy: Strategy,
77    corner_position: Option<Rc<Cell<Point<Pixels>>>>,
78    on_position: Option<Box<dyn Fn(ResolvedPosition)>>,
79    margin: Pixels,
80    occlude: bool,
81    children: Vec<AnyElement>,
82}
83
84#[doc(hidden)]
85pub struct PositionerState {
86    child_layout_ids: Vec<LayoutId>,
87}
88
89impl Positioner {
90    /// Places the popup on a side of `trigger_bounds`, flipping when needed.
91    pub fn side(trigger_bounds: Bounds<Pixels>) -> Self {
92        Self {
93            strategy: Strategy::Side {
94                trigger_bounds,
95                placement: None,
96                align: Align::Center,
97                offset: px(0.),
98            },
99            corner_position: None,
100            on_position: None,
101            margin: px(4.),
102            occlude: false,
103            children: Vec::new(),
104        }
105    }
106
107    /// Places `anchor`'s corner of the popup at `position`.
108    ///
109    /// This is the corner-anchoring path used by triggers that were written
110    /// against GPUI's `anchored` element. It clamps into the viewport without
111    /// changing the requested anchor.
112    pub fn corner(anchor: Anchor, position: Point<Pixels>) -> Self {
113        Self {
114            strategy: Strategy::Corner { anchor, position },
115            corner_position: None,
116            on_position: None,
117            margin: px(4.),
118            occlude: false,
119            children: Vec::new(),
120        }
121    }
122
123    /// Updates the requested corner position.
124    ///
125    /// This is useful when an animation moves an already-composed popup. It
126    /// has no effect on a side-positioned popup.
127    pub fn position(mut self, position: Point<Pixels>) -> Self {
128        if let Strategy::Corner {
129            position: current, ..
130        } = &mut self.strategy
131        {
132            *current = position;
133        }
134        self
135    }
136
137    /// Sets the preferred side. Only meaningful for [`Positioner::side`].
138    pub fn placement(mut self, placement: Placement) -> Self {
139        if let Strategy::Side {
140            placement: slot, ..
141        } = &mut self.strategy
142        {
143            *slot = Some(placement);
144        }
145        self
146    }
147
148    /// Sets the alignment along the chosen side. Only meaningful for
149    /// [`Positioner::side`].
150    pub fn align(mut self, align: Align) -> Self {
151        if let Strategy::Side { align: slot, .. } = &mut self.strategy {
152            *slot = align;
153        }
154        self
155    }
156
157    /// Sets the gap between the trigger and the popup. Only meaningful for
158    /// [`Positioner::side`].
159    pub fn offset(mut self, offset: Pixels) -> Self {
160        if let Strategy::Side { offset: slot, .. } = &mut self.strategy {
161            *slot = offset;
162        }
163        self
164    }
165
166    // Read after trigger prepaint so an open popup follows a moving trigger.
167    pub(crate) fn tracked_corner_position(mut self, position: Rc<Cell<Point<Pixels>>>) -> Self {
168        self.corner_position = Some(position);
169        self
170    }
171
172    /// Observe resolved geometry before children prepaint.
173    pub fn on_position(mut self, callback: impl Fn(ResolvedPosition) + 'static) -> Self {
174        self.on_position = Some(Box::new(callback));
175        self
176    }
177
178    /// Blocks the mouse over the positioned popup.
179    ///
180    /// Off by default, because a tooltip that swallowed the pointer would
181    /// un-hover the very trigger keeping it open. An interactive surface — a
182    /// popover, a menu, a dropdown — wants it on: what the surface covers is
183    /// the surface's, not the panel underneath.
184    pub fn occlude(mut self) -> Self {
185        self.occlude = true;
186        self
187    }
188
189    /// Sets the minimum distance kept between the popup and the viewport edge.
190    pub fn margin(mut self, margin: Pixels) -> Self {
191        self.margin = margin;
192        self
193    }
194}
195
196/// The part of the window's viewport that is frame rather than content, per
197/// side.
198///
199/// A window drawn with client-side decorations pads its content by the client
200/// inset to make room for a shadow, except along an edge that is tiled against
201/// the screen, where the frame draws no shadow and the content runs to the
202/// viewport edge. `Window::client_inset` is the one value on every side (the
203/// platform needs it stable across tiling changes to size the window), so the
204/// tiling is what says where it actually applies. A server-decorated window
205/// has no frame of its own.
206fn frame_insets(decorations: Decorations, client_inset: Pixels) -> Edges<Pixels> {
207    match decorations {
208        Decorations::Server => Edges::default(),
209        Decorations::Client { tiling } => Edges {
210            top: if tiling.top { px(0.) } else { client_inset },
211            right: if tiling.right { px(0.) } else { client_inset },
212            bottom: if tiling.bottom { px(0.) } else { client_inset },
213            left: if tiling.left { px(0.) } else { client_inset },
214        },
215    }
216}
217
218/// Resolves the bounds of a popup of `popup_size`.
219///
220/// Side placement picks the preferred side when the popup fits, otherwise the
221/// opposite side, otherwise whichever side has more room. The result is always
222/// clamped into the viewport, keeping `margin` from each edge.
223#[cfg(test)]
224fn resolve(
225    strategy: Strategy,
226    popup_size: Size<Pixels>,
227    viewport_size: Size<Pixels>,
228    margin: Edges<Pixels>,
229) -> ResolvedPosition {
230    resolve_in(
231        strategy,
232        popup_size,
233        viewport_size,
234        margin,
235        LayoutDirection::Ltr,
236    )
237}
238
239/// [`resolve`] for a layout direction: horizontal [`Align::Start`] and
240/// [`Align::End`] follow it, while [`Placement`] sides stay physical.
241fn resolve_in(
242    strategy: Strategy,
243    popup_size: Size<Pixels>,
244    viewport_size: Size<Pixels>,
245    margin: Edges<Pixels>,
246    direction: LayoutDirection,
247) -> ResolvedPosition {
248    match strategy {
249        Strategy::Corner { anchor, position } => ResolvedPosition {
250            bounds: clamp(
251                Bounds::from_anchor_and_size(anchor, position, popup_size),
252                viewport_size,
253                margin,
254            ),
255            placement: None,
256        },
257        Strategy::Side {
258            trigger_bounds,
259            placement,
260            align,
261            offset,
262        } => {
263            let placement =
264                resolve_placement(trigger_bounds, popup_size, viewport_size, margin, placement);
265            let origin = side_origin(
266                trigger_bounds,
267                popup_size,
268                placement,
269                align,
270                offset,
271                direction,
272            );
273            ResolvedPosition {
274                bounds: clamp(Bounds::new(origin, popup_size), viewport_size, margin),
275                placement: Some(placement),
276            }
277        }
278    }
279}
280
281fn resolve_placement(
282    trigger_bounds: Bounds<Pixels>,
283    popup_size: Size<Pixels>,
284    viewport_size: Size<Pixels>,
285    margin: Edges<Pixels>,
286    preferred: Option<Placement>,
287) -> Placement {
288    let right_limit = (viewport_size.width - margin.right).max(margin.left);
289    let bottom_limit = (viewport_size.height - margin.bottom).max(margin.top);
290    let available_left = (trigger_bounds.left() - margin.left).max(px(0.));
291    let available_right = (right_limit - trigger_bounds.right()).max(px(0.));
292    let available_above = (trigger_bounds.top() - margin.top).max(px(0.));
293    let available_below = (bottom_limit - trigger_bounds.bottom()).max(px(0.));
294
295    match preferred {
296        Some(Placement::Right) if popup_size.width <= available_right => Placement::Right,
297        Some(Placement::Right) if popup_size.width <= available_left => Placement::Left,
298        Some(Placement::Right) if available_right >= available_left => Placement::Right,
299        Some(Placement::Right) => Placement::Left,
300        Some(Placement::Left) if popup_size.width <= available_left => Placement::Left,
301        Some(Placement::Left) if popup_size.width <= available_right => Placement::Right,
302        Some(Placement::Left) if available_left >= available_right => Placement::Left,
303        Some(Placement::Left) => Placement::Right,
304        Some(Placement::Bottom) if popup_size.height <= available_below => Placement::Bottom,
305        Some(Placement::Bottom) if popup_size.height <= available_above => Placement::Top,
306        Some(Placement::Bottom) if available_below >= available_above => Placement::Bottom,
307        Some(Placement::Bottom) => Placement::Top,
308        Some(Placement::Top) | None if popup_size.height <= available_above => Placement::Top,
309        Some(Placement::Top) | None if popup_size.height <= available_below => Placement::Bottom,
310        Some(Placement::Top) | None if available_below >= available_above => Placement::Bottom,
311        Some(Placement::Top) | None => Placement::Top,
312    }
313}
314
315fn side_origin(
316    trigger_bounds: Bounds<Pixels>,
317    popup_size: Size<Pixels>,
318    placement: Placement,
319    align: Align,
320    offset: Pixels,
321    direction: LayoutDirection,
322) -> Point<Pixels> {
323    let aligned_x = match align.horizontal(direction) {
324        Align::Start => trigger_bounds.left(),
325        Align::Center => trigger_bounds.center().x - popup_size.width.half(),
326        Align::End => trigger_bounds.right() - popup_size.width,
327    };
328    let aligned_y = match align {
329        Align::Start => trigger_bounds.top(),
330        Align::Center => trigger_bounds.center().y - popup_size.height.half(),
331        Align::End => trigger_bounds.bottom() - popup_size.height,
332    };
333
334    match placement {
335        Placement::Top => point(aligned_x, trigger_bounds.top() - popup_size.height - offset),
336        Placement::Bottom => point(aligned_x, trigger_bounds.bottom() + offset),
337        Placement::Left => point(trigger_bounds.left() - popup_size.width - offset, aligned_y),
338        Placement::Right => point(trigger_bounds.right() + offset, aligned_y),
339    }
340}
341
342fn clamp(
343    mut bounds: Bounds<Pixels>,
344    viewport_size: Size<Pixels>,
345    margin: Edges<Pixels>,
346) -> Bounds<Pixels> {
347    let right_limit = (viewport_size.width - margin.right).max(margin.left);
348    let bottom_limit = (viewport_size.height - margin.bottom).max(margin.top);
349
350    if bounds.right() > right_limit {
351        bounds.origin.x -= bounds.right() - right_limit;
352    }
353    if bounds.left() < margin.left {
354        bounds.origin.x = margin.left;
355    }
356    if bounds.bottom() > bottom_limit {
357        bounds.origin.y -= bounds.bottom() - bottom_limit;
358    }
359    if bounds.top() < margin.top {
360        bounds.origin.y = margin.top;
361    }
362
363    bounds
364}
365
366impl ParentElement for Positioner {
367    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
368        self.children.extend(elements);
369    }
370}
371
372impl Element for Positioner {
373    type RequestLayoutState = PositionerState;
374    type PrepaintState = ();
375
376    fn id(&self) -> Option<gpui::ElementId> {
377        None
378    }
379
380    fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
381        None
382    }
383
384    fn request_layout(
385        &mut self,
386        _: Option<&GlobalElementId>,
387        _: Option<&InspectorElementId>,
388        window: &mut Window,
389        cx: &mut App,
390    ) -> (LayoutId, Self::RequestLayoutState) {
391        let child_layout_ids = self
392            .children
393            .iter_mut()
394            .map(|child| child.request_layout(window, cx))
395            .collect::<Vec<_>>();
396        let layout_id = window.request_layout(
397            Style {
398                position: Position::Absolute,
399                display: Display::Flex,
400                ..Style::default()
401            },
402            child_layout_ids.iter().copied(),
403            cx,
404        );
405
406        (layout_id, PositionerState { child_layout_ids })
407    }
408
409    fn prepaint(
410        &mut self,
411        _: Option<&GlobalElementId>,
412        _: Option<&InspectorElementId>,
413        bounds: Bounds<Pixels>,
414        request_layout: &mut Self::RequestLayoutState,
415        window: &mut Window,
416        cx: &mut App,
417    ) {
418        if request_layout.child_layout_ids.is_empty() {
419            return;
420        }
421
422        let mut child_min = point(Pixels::MAX, Pixels::MAX);
423        let mut child_max = Point::default();
424        for child_layout_id in &request_layout.child_layout_ids {
425            let child_bounds = window.layout_bounds(*child_layout_id);
426            child_min = child_min.min(&child_bounds.origin);
427            child_max = child_max.max(&child_bounds.bottom_right());
428        }
429
430        let popup_size = (child_max - child_min).into();
431        let frame = frame_insets(
432            window.window_decorations(),
433            window.client_inset().unwrap_or(px(0.)),
434        );
435        let mut strategy = self.strategy;
436        if let (Strategy::Corner { position, .. }, Some(tracked)) =
437            (&mut strategy, &self.corner_position)
438        {
439            *position = tracked.get();
440        }
441        let position = resolve_in(
442            strategy,
443            popup_size,
444            window.viewport_size(),
445            frame.map(|inset| *inset + self.margin),
446            LayoutDirection::global(cx),
447        );
448        if let Some(callback) = &self.on_position {
449            callback(position);
450        }
451        // Ahead of the children so it blocks what is behind the popup without
452        // blocking the popup's own content.
453        if self.occlude {
454            window.insert_hitbox(position.bounds, HitboxBehavior::BlockMouse);
455        }
456
457        let offset = position.bounds.origin - bounds.origin;
458        let offset = point(offset.x.round(), offset.y.round());
459
460        window.with_element_offset(offset, |window| {
461            for child in &mut self.children {
462                child.prepaint(window, cx);
463            }
464        });
465    }
466
467    fn paint(
468        &mut self,
469        _: Option<&GlobalElementId>,
470        _: Option<&InspectorElementId>,
471        _: Bounds<Pixels>,
472        _: &mut Self::RequestLayoutState,
473        _: &mut Self::PrepaintState,
474        window: &mut Window,
475        cx: &mut App,
476    ) {
477        for child in &mut self.children {
478            child.paint(window, cx);
479        }
480    }
481}
482
483#[cfg(test)]
484mod tests {
485    use super::*;
486    use gpui::Tiling;
487
488    const MARGIN: Pixels = px(4.);
489
490    fn trigger(x: f32, y: f32, w: f32, h: f32) -> Bounds<Pixels> {
491        Bounds::new(point(px(x), px(y)), Size::new(px(w), px(h)))
492    }
493
494    fn viewport() -> Size<Pixels> {
495        Size::new(px(500.), px(400.))
496    }
497
498    fn side(
499        trigger_bounds: Bounds<Pixels>,
500        placement: Option<Placement>,
501        align: Align,
502        popup: Size<Pixels>,
503    ) -> ResolvedPosition {
504        resolve(
505            Strategy::Side {
506                trigger_bounds,
507                placement,
508                align,
509                offset: px(0.),
510            },
511            popup,
512            viewport(),
513            Edges::all(MARGIN),
514        )
515    }
516
517    #[test]
518    fn prefers_the_requested_side_when_it_fits() {
519        let position = side(
520            trigger(200., 200., 40., 20.),
521            Some(Placement::Top),
522            Align::Center,
523            Size::new(px(80.), px(30.)),
524        );
525
526        assert_eq!(position.placement, Some(Placement::Top));
527        assert_eq!(position.bounds.bottom(), px(200.));
528    }
529
530    #[test]
531    fn flips_to_the_opposite_side_when_the_preferred_side_does_not_fit() {
532        let position = side(
533            trigger(200., 10., 40., 20.),
534            Some(Placement::Top),
535            Align::Center,
536            Size::new(px(80.), px(60.)),
537        );
538
539        assert_eq!(position.placement, Some(Placement::Bottom));
540        assert_eq!(position.bounds.top(), px(30.));
541    }
542
543    #[test]
544    fn clamps_into_the_viewport_while_keeping_the_flipped_side() {
545        let position = side(
546            trigger(480., 200., 40., 20.),
547            Some(Placement::Bottom),
548            Align::Center,
549            Size::new(px(120.), px(30.)),
550        );
551
552        assert_eq!(position.placement, Some(Placement::Bottom));
553        assert_eq!(position.bounds.right(), viewport().width - MARGIN);
554    }
555
556    #[test]
557    fn alignment_selects_the_leading_center_or_trailing_edge() {
558        let trigger_bounds = trigger(200., 200., 100., 20.);
559        let popup = Size::new(px(40.), px(30.));
560
561        let start = side(trigger_bounds, Some(Placement::Bottom), Align::Start, popup);
562        let center = side(
563            trigger_bounds,
564            Some(Placement::Bottom),
565            Align::Center,
566            popup,
567        );
568        let end = side(trigger_bounds, Some(Placement::Bottom), Align::End, popup);
569
570        assert_eq!(start.bounds.left(), px(200.));
571        assert_eq!(center.bounds.left(), px(230.));
572        assert_eq!(end.bounds.left(), px(260.));
573    }
574
575    #[test]
576    fn rtl_aligns_start_with_the_right_edge_of_the_trigger() {
577        let strategy = |align| Strategy::Side {
578            trigger_bounds: trigger(200., 200., 100., 20.),
579            placement: Some(Placement::Bottom),
580            align,
581            offset: px(0.),
582        };
583        let popup = Size::new(px(40.), px(30.));
584        let resolve_rtl = |align| {
585            resolve_in(
586                strategy(align),
587                popup,
588                viewport(),
589                Edges::all(MARGIN),
590                LayoutDirection::Rtl,
591            )
592        };
593
594        assert_eq!(resolve_rtl(Align::Start).bounds.right(), px(300.));
595        assert_eq!(resolve_rtl(Align::Center).bounds.left(), px(230.));
596        assert_eq!(resolve_rtl(Align::End).bounds.left(), px(200.));
597    }
598
599    #[test]
600    fn side_offset_adds_a_gap_between_trigger_and_popup() {
601        let position = resolve(
602            Strategy::Side {
603                trigger_bounds: trigger(200., 200., 40., 20.),
604                placement: Some(Placement::Bottom),
605                align: Align::Center,
606                offset: px(8.),
607            },
608            Size::new(px(40.), px(30.)),
609            viewport(),
610            Edges::all(MARGIN),
611        );
612
613        assert_eq!(position.bounds.top(), px(228.));
614    }
615
616    #[test]
617    fn corner_positioning_places_the_named_corner_and_never_reports_a_side() {
618        let position = resolve(
619            Strategy::Corner {
620                anchor: Anchor::TopLeft,
621                position: point(px(100.), px(100.)),
622            },
623            Size::new(px(40.), px(30.)),
624            viewport(),
625            Edges::all(MARGIN),
626        );
627
628        assert_eq!(position.placement, None);
629        assert_eq!(position.bounds.origin, point(px(100.), px(100.)));
630    }
631
632    #[test]
633    fn corner_positioning_clamps_but_does_not_flip() {
634        let position = resolve(
635            Strategy::Corner {
636                anchor: Anchor::TopLeft,
637                position: point(px(480.), px(390.)),
638            },
639            Size::new(px(40.), px(30.)),
640            viewport(),
641            Edges::all(MARGIN),
642        );
643
644        assert_eq!(position.placement, None);
645        assert_eq!(position.bounds.right(), viewport().width - MARGIN);
646        assert_eq!(position.bounds.bottom(), viewport().height - MARGIN);
647    }
648
649    #[test]
650    fn corner_position_can_be_updated_without_rebuilding_the_positioner() {
651        let positioner = Positioner::corner(Anchor::TopLeft, point(px(10.), px(20.)))
652            .position(point(px(30.), px(40.)));
653
654        assert!(matches!(
655            positioner.strategy,
656            Strategy::Corner {
657                position,
658                ..
659            } if position == point(px(30.), px(40.))
660        ));
661    }
662
663    /// A tiled edge draws no shadow, so a popup may run right up to the
664    /// margin there; an untiled edge keeps the whole client inset as well.
665    #[test]
666    fn frame_insets_apply_the_client_inset_only_on_untiled_edges() {
667        let inset = px(20.);
668
669        assert_eq!(
670            frame_insets(Decorations::Server, inset),
671            Edges::default(),
672            "a server-decorated window has no frame to keep clear of"
673        );
674        assert_eq!(
675            frame_insets(
676                Decorations::Client {
677                    tiling: Tiling::tiled()
678                },
679                inset
680            ),
681            Edges::default(),
682            "a window tiled on every side draws no shadow padding"
683        );
684        assert_eq!(
685            frame_insets(
686                Decorations::Client {
687                    tiling: Tiling {
688                        top: false,
689                        left: true,
690                        right: false,
691                        bottom: true,
692                    }
693                },
694                inset
695            ),
696            Edges {
697                top: inset,
698                right: inset,
699                bottom: px(0.),
700                left: px(0.),
701            }
702        );
703    }
704
705    /// The bug this guards: a menu opened from a trigger near the right edge
706    /// of a tiled window was pushed inward by the client inset although no
707    /// shadow was drawn there, so it no longer lined up with its trigger.
708    #[test]
709    fn clamping_keeps_only_the_margin_on_a_tiled_edge() {
710        let popup = Size::new(px(120.), px(30.));
711        // A menu aligned to a trigger that ends 10px short of the right edge.
712        let corner = Strategy::Corner {
713            anchor: Anchor::TopRight,
714            position: point(viewport().width - px(10.), px(100.)),
715        };
716        let margin = Edges::all(MARGIN);
717        let inset = px(20.);
718
719        let tiled = resolve(corner, popup, viewport(), margin);
720        assert_eq!(tiled.bounds.right(), viewport().width - px(10.));
721
722        let untiled = resolve(
723            corner,
724            popup,
725            viewport(),
726            margin.map(|margin| *margin + inset),
727        );
728        assert_eq!(untiled.bounds.right(), viewport().width - MARGIN - inset);
729    }
730
731    // Migrated from the tooltip module when its private positioning logic was
732    // merged into this one. They passed unchanged across that move, which is
733    // what proves the merge preserved tooltip placement behavior.
734    const WINDOW_MARGIN: Pixels = px(4.);
735
736    fn tooltip_placement(
737        trigger_bounds: Bounds<Pixels>,
738        popup: Size<Pixels>,
739        viewport: Size<Pixels>,
740        margin: Pixels,
741        placement: Option<Placement>,
742    ) -> (Bounds<Pixels>, Placement) {
743        let resolved = resolve(
744            Strategy::Side {
745                trigger_bounds,
746                placement,
747                align: Align::Center,
748                offset: px(0.),
749            },
750            popup,
751            viewport,
752            Edges::all(margin),
753        );
754        (resolved.bounds, resolved.placement.unwrap())
755    }
756
757    fn bounds(x: f32, y: f32, width: f32, height: f32) -> Bounds<Pixels> {
758        Bounds::new(point(px(x), px(y)), Size::new(px(width), px(height)))
759    }
760
761    fn size_px(width: f32, height: f32) -> Size<Pixels> {
762        Size::new(px(width), px(height))
763    }
764
765    #[test]
766    fn prefers_above_when_space_allows() {
767        let trigger = bounds(100., 80., 80., 24.);
768        let position = tooltip_placement(
769            trigger,
770            size_px(120., 30.),
771            size_px(300., 200.),
772            WINDOW_MARGIN,
773            None,
774        );
775        assert_eq!(position.1, Placement::Top);
776        assert_eq!(position.0.origin, point(px(80.), px(50.)));
777    }
778    #[test]
779    fn flips_and_clamps_on_each_axis() {
780        let top = tooltip_placement(
781            bounds(24., 4., 120., 32.),
782            size_px(240., 32.),
783            size_px(520., 260.),
784            WINDOW_MARGIN,
785            None,
786        );
787        assert_eq!(top.1, Placement::Bottom);
788
789        let right = tooltip_placement(
790            bounds(260., 60., 32., 32.),
791            size_px(120., 30.),
792            size_px(300., 200.),
793            WINDOW_MARGIN,
794            Some(Placement::Right),
795        );
796        assert_eq!(right.1, Placement::Left);
797
798        let left_edge = tooltip_placement(
799            bounds(4., 80., 24., 24.),
800            size_px(120., 30.),
801            size_px(300., 200.),
802            WINDOW_MARGIN,
803            None,
804        );
805        assert_eq!(left_edge.0.left(), WINDOW_MARGIN);
806    }
807    #[test]
808    fn places_tooltip_to_the_right() {
809        let trigger = bounds(20., 60., 32., 32.);
810        let position = tooltip_placement(
811            trigger,
812            size_px(120., 30.),
813            size_px(300., 200.),
814            WINDOW_MARGIN,
815            Some(Placement::Right),
816        );
817        assert_eq!(position.1, Placement::Right);
818        assert_eq!(position.0.left(), trigger.right());
819        assert_eq!(position.0.center().y, trigger.center().y);
820    }
821    #[test]
822    fn right_placement_clamps_vertical_edges() {
823        let trigger = bounds(20., 2., 32., 20.);
824        let position = tooltip_placement(
825            trigger,
826            size_px(120., 40.),
827            size_px(300., 200.),
828            WINDOW_MARGIN,
829            Some(Placement::Right),
830        );
831        assert_eq!(position.1, Placement::Right);
832        assert_eq!(position.0.top(), WINDOW_MARGIN);
833        assert_eq!(position.0.left(), trigger.right());
834    }
835    #[test]
836    fn uses_larger_side_when_neither_vertical_side_fits() {
837        let position = tooltip_placement(
838            bounds(120., 20., 40., 20.),
839            size_px(160., 120.),
840            size_px(300., 100.),
841            WINDOW_MARGIN,
842            None,
843        );
844        assert_eq!(position.1, Placement::Bottom);
845        assert_eq!(position.0.top(), WINDOW_MARGIN);
846        assert_eq!(position.0.left(), px(60.));
847    }
848}