Skip to main content

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