Skip to main content

iced_cube/overlay/
tooltip.rs

1//! A small label shown while the pointer rests on an element, or while
2//! something inside the element has keyboard focus.
3//!
4//! A finger shows it while held. Once the finger lifts, the bubble stays
5//! closed until a mouse is used, so a tap on a phone does not leave it open.
6//!
7//! iced has no general focus model, so the tooltip follows the widgets that
8//! report focus to operations: text fields, text editors and the focusable
9//! parts of this library. Focus that arrives with a pointer press, such as
10//! clicking into a field, does not show the bubble.
11
12use iced::advanced::layout::{self, Layout};
13use iced::advanced::widget::operation::Focusable;
14use iced::advanced::widget::{Operation, Tree, Widget, tree};
15use iced::advanced::{Clipboard, Shell, overlay, renderer};
16use iced::time::{Duration, Instant};
17use iced::widget::{self, container, text};
18use iced::{
19    Background, Border, Element, Event, Length, Padding, Point, Rectangle, Renderer, Size, Theme,
20    Vector, mouse, touch, window,
21};
22
23use crate::after_touch::after_touch;
24use crate::theme::{Tokens, radius, space, text_size};
25
26/// Where the bubble appears relative to its element.
27#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
28pub enum Position {
29    #[default]
30    Top,
31    Bottom,
32    Left,
33    Right,
34    /// Follows the pointer. A bubble shown for keyboard focus sits on top.
35    FollowCursor,
36}
37
38impl Position {
39    pub const ALL: [Position; 5] = [
40        Position::Top,
41        Position::Bottom,
42        Position::Left,
43        Position::Right,
44        Position::FollowCursor,
45    ];
46}
47
48/// Gap between the element and the bubble's margin, in logical pixels.
49pub const GAP: f32 = 6.0;
50
51/// The bubble's margin: the closest it comes to the window edges, and part
52/// of the space between it and its element.
53pub const EDGE: f32 = 5.0;
54
55/// Labels longer than this many characters are sentences rather than
56/// names, and read at [`text_size::SM`] instead of [`text_size::XS`].
57pub const LONG_LABEL: usize = 40;
58
59/// The text size of the bubble: `explicit` when set, otherwise small for a
60/// short label and a size up for a longer one.
61pub fn label_size(label: &str, explicit: Option<f32>) -> f32 {
62    if let Some(size) = explicit {
63        return size;
64    }
65    if label.chars().count() > LONG_LABEL {
66        return text_size::SM;
67    }
68    text_size::XS
69}
70
71/// A tooltip builder. Convert it into an [`Element`] to render.
72pub struct Tooltip<'a, Message> {
73    content: Element<'a, Message>,
74    label: text::Fragment<'a>,
75    position: Position,
76    delay: Duration,
77    max_width: Option<f32>,
78    text_size: Option<f32>,
79}
80
81impl<Message> std::fmt::Debug for Tooltip<'_, Message> {
82    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
83        f.debug_struct("Tooltip")
84            .field("label", &self.label)
85            .field("position", &self.position)
86            .field("delay", &self.delay)
87            .field("max_width", &self.max_width)
88            .field("text_size", &self.text_size)
89            .finish_non_exhaustive()
90    }
91}
92
93/// Shows `label` in a bubble while the pointer is over `content`, or while
94/// something inside `content` has keyboard focus.
95pub fn tooltip<'a, Message>(
96    content: impl Into<Element<'a, Message>>,
97    label: impl text::IntoFragment<'a>,
98) -> Tooltip<'a, Message> {
99    Tooltip {
100        content: content.into(),
101        label: label.into_fragment(),
102        position: Position::default(),
103        delay: Duration::ZERO,
104        max_width: None,
105        text_size: None,
106    }
107}
108
109impl<'a, Message> Tooltip<'a, Message> {
110    pub fn position(mut self, position: Position) -> Self {
111        self.position = position;
112        self
113    }
114
115    /// How long the pointer has to rest before the bubble appears. Keyboard
116    /// focus shows it straight away.
117    pub fn delay(mut self, delay: Duration) -> Self {
118        self.delay = delay;
119        self
120    }
121
122    /// The widest the bubble grows, in logical pixels. A longer label wraps
123    /// onto more lines. Without it the bubble is as wide as the label, up
124    /// to the width of the window.
125    pub fn max_width(mut self, width: f32) -> Self {
126        self.max_width = Some(width);
127        self
128    }
129
130    /// The label's text size. Defaults to [`label_size`]: small for a few
131    /// words and a size up for a sentence.
132    pub fn text_size(mut self, size: f32) -> Self {
133        self.text_size = Some(size);
134        self
135    }
136}
137
138impl<'a, Message: 'a> From<Tooltip<'a, Message>> for Element<'a, Message> {
139    fn from(tooltip: Tooltip<'a, Message>) -> Self {
140        let size = label_size(&tooltip.label, tooltip.text_size);
141        let mut bubble = container(text(tooltip.label).size(size))
142            .padding([space::XS + 2.0, space::MD])
143            .style(|theme| style(&Tokens::of(theme)));
144        if let Some(width) = tooltip.max_width {
145            bubble = bubble.max_width(width);
146        }
147
148        after_touch(Element::new(Tip {
149            content: tooltip.content,
150            bubble: bubble.into(),
151            position: tooltip.position,
152            delay: tooltip.delay,
153        }))
154    }
155}
156
157/// The bubble style: inverted colours so it stands out from the page.
158pub fn style(tokens: &Tokens) -> container::Style {
159    container::Style {
160        background: Some(Background::Color(tokens.primary)),
161        text_color: Some(tokens.primary_foreground),
162        border: Border {
163            radius: radius::MD.into(),
164            ..Border::default()
165        },
166        ..container::Style::default()
167    }
168}
169
170/// How focus reached the content, if it has it.
171#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
172pub enum Focus {
173    #[default]
174    None,
175    /// Focus came with a pointer press, so the bubble stays hidden.
176    Pointer,
177    /// Focus came any other way, such as Tab, and shows the bubble.
178    Keyboard,
179}
180
181impl Focus {
182    /// The focus after an event, given whether the content is `focused`
183    /// now and whether the event was a pointer press.
184    pub fn next(self, focused: bool, pointer_press: bool) -> Focus {
185        if !focused {
186            return Focus::None;
187        }
188        if pointer_press {
189            return Focus::Pointer;
190        }
191        if self == Focus::None {
192            return Focus::Keyboard;
193        }
194        self
195    }
196}
197
198/// Whether the pointer has shown the bubble.
199#[derive(Debug, Clone, Copy, PartialEq, Default)]
200enum Hover {
201    #[default]
202    Idle,
203    Resting {
204        at: Instant,
205    },
206    Open {
207        cursor: Point,
208    },
209}
210
211#[derive(Debug, Clone, Copy, PartialEq, Default)]
212struct State {
213    hover: Hover,
214    focus: Focus,
215}
216
217impl State {
218    fn shown(&self) -> bool {
219        matches!(self.hover, Hover::Open { .. }) || self.focus == Focus::Keyboard
220    }
221
222    fn cursor(&self) -> Option<Point> {
223        match self.hover {
224            Hover::Open { cursor } => Some(cursor),
225            _ => None,
226        }
227    }
228}
229
230fn is_pointer_press(event: &Event) -> bool {
231    matches!(
232        event,
233        Event::Mouse(mouse::Event::ButtonPressed(_))
234            | Event::Touch(touch::Event::FingerPressed { .. })
235    )
236}
237
238/// Whether focus may have changed with `event`. Pointer movement never
239/// moves focus, so it skips the check.
240fn may_move_focus(event: &Event) -> bool {
241    !matches!(
242        event,
243        Event::Mouse(mouse::Event::CursorMoved { .. } | mouse::Event::WheelScrolled { .. })
244            | Event::Touch(touch::Event::FingerMoved { .. })
245    )
246}
247
248/// Finds out whether any widget it visits has focus.
249#[derive(Debug, Default)]
250struct Probe {
251    focused: bool,
252}
253
254impl Operation for Probe {
255    fn traverse(&mut self, operate: &mut dyn FnMut(&mut dyn Operation)) {
256        operate(self);
257    }
258
259    fn focusable(
260        &mut self,
261        _id: Option<&widget::Id>,
262        _bounds: Rectangle,
263        state: &mut dyn Focusable,
264    ) {
265        self.focused |= state.is_focused();
266    }
267}
268
269struct Tip<'a, Message> {
270    content: Element<'a, Message>,
271    bubble: Element<'a, Message>,
272    position: Position,
273    delay: Duration,
274}
275
276impl<Message> Tip<'_, Message> {
277    fn update_hover(
278        &self,
279        state: &mut State,
280        event: &Event,
281        layout: Layout<'_>,
282        cursor: mouse::Cursor,
283        shell: &mut Shell<'_, Message>,
284    ) {
285        if !matches!(
286            event,
287            Event::Mouse(_) | Event::Window(window::Event::RedrawRequested(_))
288        ) {
289            return;
290        }
291        let now = Instant::now();
292        let over = cursor.position_over(layout.bounds());
293
294        match (state.hover, over) {
295            (Hover::Idle, Some(position)) => {
296                if self.delay == Duration::ZERO {
297                    state.hover = Hover::Open { cursor: position };
298                    shell.invalidate_layout();
299                } else {
300                    state.hover = Hover::Resting { at: now };
301                }
302                shell.request_redraw_at(now + self.delay);
303            }
304            (Hover::Resting { .. }, None) => state.hover = Hover::Idle,
305            (Hover::Resting { at }, _) if at.elapsed() < self.delay => {
306                shell.request_redraw_at(now + self.delay - at.elapsed());
307            }
308            (Hover::Resting { .. }, Some(position)) => {
309                state.hover = Hover::Open { cursor: position };
310                shell.invalidate_layout();
311            }
312            (Hover::Open { cursor: last }, Some(position))
313                if self.position == Position::FollowCursor && last != position =>
314            {
315                state.hover = Hover::Open { cursor: position };
316                shell.request_redraw();
317            }
318            (Hover::Open { .. }, None) => {
319                state.hover = Hover::Idle;
320                shell.invalidate_layout();
321                if !matches!(event, Event::Window(window::Event::RedrawRequested(_))) {
322                    shell.request_redraw();
323                }
324            }
325            (Hover::Open { .. }, Some(_)) | (Hover::Idle, None) => {}
326        }
327    }
328}
329
330impl<Message> Widget<Message, Theme, Renderer> for Tip<'_, Message> {
331    fn size(&self) -> Size<Length> {
332        self.content.as_widget().size()
333    }
334
335    fn size_hint(&self) -> Size<Length> {
336        self.content.as_widget().size_hint()
337    }
338
339    fn tag(&self) -> tree::Tag {
340        tree::Tag::of::<State>()
341    }
342
343    fn state(&self) -> tree::State {
344        tree::State::new(State::default())
345    }
346
347    fn children(&self) -> Vec<Tree> {
348        vec![Tree::new(&self.content), Tree::new(&self.bubble)]
349    }
350
351    fn diff(&self, tree: &mut Tree) {
352        tree.diff_children(&[&self.content, &self.bubble]);
353    }
354
355    fn layout(
356        &mut self,
357        tree: &mut Tree,
358        renderer: &Renderer,
359        limits: &layout::Limits,
360    ) -> layout::Node {
361        self.content
362            .as_widget_mut()
363            .layout(&mut tree.children[0], renderer, limits)
364    }
365
366    fn draw(
367        &self,
368        tree: &Tree,
369        renderer: &mut Renderer,
370        theme: &Theme,
371        style: &renderer::Style,
372        layout: Layout<'_>,
373        cursor: mouse::Cursor,
374        viewport: &Rectangle,
375    ) {
376        self.content.as_widget().draw(
377            &tree.children[0],
378            renderer,
379            theme,
380            style,
381            layout,
382            cursor,
383            viewport,
384        );
385    }
386
387    fn operate(
388        &mut self,
389        tree: &mut Tree,
390        layout: Layout<'_>,
391        renderer: &Renderer,
392        operation: &mut dyn Operation,
393    ) {
394        operation.container(None, layout.bounds());
395        operation.traverse(&mut |operation| {
396            self.content.as_widget_mut().operate(
397                &mut tree.children[0],
398                layout,
399                renderer,
400                operation,
401            );
402        });
403    }
404
405    fn update(
406        &mut self,
407        tree: &mut Tree,
408        event: &Event,
409        layout: Layout<'_>,
410        cursor: mouse::Cursor,
411        renderer: &Renderer,
412        clipboard: &mut dyn Clipboard,
413        shell: &mut Shell<'_, Message>,
414        viewport: &Rectangle,
415    ) {
416        let state = tree.state.downcast_mut::<State>();
417        let was_shown = state.shown();
418        self.update_hover(state, event, layout, cursor, shell);
419
420        let content = &mut tree.children[0];
421        self.content.as_widget_mut().update(
422            content, event, layout, cursor, renderer, clipboard, shell, viewport,
423        );
424        if !may_move_focus(event) {
425            return;
426        }
427
428        let mut probe = Probe::default();
429        self.content
430            .as_widget_mut()
431            .operate(content, layout, renderer, &mut probe);
432        let state = tree.state.downcast_mut::<State>();
433        state.focus = state.focus.next(probe.focused, is_pointer_press(event));
434        if state.shown() != was_shown {
435            shell.invalidate_layout();
436            shell.request_redraw();
437        }
438    }
439
440    fn mouse_interaction(
441        &self,
442        tree: &Tree,
443        layout: Layout<'_>,
444        cursor: mouse::Cursor,
445        viewport: &Rectangle,
446        renderer: &Renderer,
447    ) -> mouse::Interaction {
448        self.content.as_widget().mouse_interaction(
449            &tree.children[0],
450            layout,
451            cursor,
452            viewport,
453            renderer,
454        )
455    }
456
457    fn overlay<'b>(
458        &'b mut self,
459        tree: &'b mut Tree,
460        layout: Layout<'b>,
461        renderer: &Renderer,
462        viewport: &Rectangle,
463        translation: Vector,
464    ) -> Option<overlay::Element<'b, Message, Theme, Renderer>> {
465        let state = *tree.state.downcast_ref::<State>();
466        let [content_tree, bubble_tree] = tree.children.as_mut_slice() else {
467            return None;
468        };
469
470        let content = self.content.as_widget_mut().overlay(
471            content_tree,
472            layout,
473            renderer,
474            viewport,
475            translation,
476        );
477        let bubble = state.shown().then(|| {
478            overlay::Element::new(Box::new(Bubble {
479                position: layout.position() + translation,
480                content_bounds: layout.bounds(),
481                cursor: state.cursor(),
482                placement: self.position,
483                bubble: &mut self.bubble,
484                tree: bubble_tree,
485            }))
486        });
487
488        let children: Vec<_> = content.into_iter().chain(bubble).collect();
489        (!children.is_empty()).then(|| overlay::Group::with_children(children).overlay())
490    }
491}
492
493/// Where the bubble goes: its top left corner, given the content's
494/// position and bounds, the bubble's size and the pointer, before it is
495/// kept inside the window.
496fn place(
497    placement: Position,
498    position: Point,
499    content: Rectangle,
500    bubble: Size,
501    cursor: Option<Point>,
502) -> Point {
503    let x_centre = position.x + (content.width - bubble.width) / 2.0;
504    let y_centre = position.y + (content.height - bubble.height) / 2.0;
505    let gap = GAP + EDGE;
506    let above = Point::new(x_centre, position.y - bubble.height - gap);
507
508    match (placement, cursor) {
509        (Position::Top, _) | (Position::FollowCursor, None) => above,
510        (Position::Bottom, _) => Point::new(x_centre, position.y + content.height + gap),
511        (Position::Left, _) => Point::new(position.x - bubble.width - gap, y_centre),
512        (Position::Right, _) => Point::new(position.x + content.width + gap, y_centre),
513        (Position::FollowCursor, Some(cursor)) => {
514            let shift = position - content.position();
515            Point::new(cursor.x, cursor.y - bubble.height) + shift
516        }
517    }
518}
519
520/// The side the bubble goes on: `placement`, or the opposite side when
521/// `placement` would run out of `viewport` and the opposite would not, so
522/// a bubble near an edge is never pushed back over its own control.
523fn side_that_fits(
524    placement: Position,
525    position: Point,
526    content: Rectangle,
527    bubble: Size,
528    viewport: Rectangle,
529) -> Position {
530    // Only the side's own axis matters: sliding along the edge is left to
531    // `keep_inside`.
532    let fits = |side| {
533        let corner = place(side, position, content, bubble, None);
534        match side {
535            Position::Top | Position::Bottom => {
536                corner.y - EDGE >= viewport.y
537                    && corner.y + bubble.height + EDGE <= viewport.y + viewport.height
538            }
539            Position::Left | Position::Right | Position::FollowCursor => {
540                corner.x - EDGE >= viewport.x
541                    && corner.x + bubble.width + EDGE <= viewport.x + viewport.width
542            }
543        }
544    };
545    let opposite = match placement {
546        Position::Top => Position::Bottom,
547        Position::Bottom => Position::Top,
548        Position::Left => Position::Right,
549        Position::Right => Position::Left,
550        Position::FollowCursor => return placement,
551    };
552    if !fits(placement) && fits(opposite) {
553        return opposite;
554    }
555    placement
556}
557
558/// Moves `bounds` back inside `viewport`, leaving it where it is if it
559/// already fits.
560fn keep_inside(mut bounds: Rectangle, viewport: Rectangle) -> Rectangle {
561    if bounds.x < viewport.x {
562        bounds.x = viewport.x;
563    } else if viewport.x + viewport.width < bounds.x + bounds.width {
564        bounds.x = viewport.x + viewport.width - bounds.width;
565    }
566    if bounds.y < viewport.y {
567        bounds.y = viewport.y;
568    } else if viewport.y + viewport.height < bounds.y + bounds.height {
569        bounds.y = viewport.y + viewport.height - bounds.height;
570    }
571    bounds
572}
573
574struct Bubble<'a, 'b, Message> {
575    position: Point,
576    content_bounds: Rectangle,
577    cursor: Option<Point>,
578    placement: Position,
579    bubble: &'b mut Element<'a, Message>,
580    tree: &'b mut Tree,
581}
582
583impl<Message> overlay::Overlay<Message, Theme, Renderer> for Bubble<'_, '_, Message> {
584    fn layout(&mut self, renderer: &Renderer, bounds: Size) -> layout::Node {
585        let viewport = Rectangle::with_size(bounds);
586        let limits = layout::Limits::new(Size::ZERO, viewport.size()).shrink(Padding::new(EDGE));
587        let node = self
588            .bubble
589            .as_widget_mut()
590            .layout(self.tree, renderer, &limits);
591        let size = node.size();
592
593        let side = side_that_fits(
594            self.placement,
595            self.position,
596            self.content_bounds,
597            size,
598            viewport,
599        );
600        let corner = place(side, self.position, self.content_bounds, size, self.cursor);
601        // The edge margin surrounds the bubble, so it never touches the
602        // window border once kept inside.
603        let framed = Rectangle {
604            x: corner.x - EDGE,
605            y: corner.y - EDGE,
606            width: size.width + EDGE * 2.0,
607            height: size.height + EDGE * 2.0,
608        };
609        let framed = keep_inside(framed, viewport);
610
611        layout::Node::with_children(framed.size(), vec![node.translate(Vector::new(EDGE, EDGE))])
612            .translate(Vector::new(framed.x, framed.y))
613    }
614
615    fn draw(
616        &self,
617        renderer: &mut Renderer,
618        theme: &Theme,
619        style: &renderer::Style,
620        layout: Layout<'_>,
621        cursor: mouse::Cursor,
622    ) {
623        let Some(bubble) = layout.children().next() else {
624            return;
625        };
626        self.bubble.as_widget().draw(
627            self.tree,
628            renderer,
629            theme,
630            style,
631            bubble,
632            cursor,
633            &Rectangle::with_size(Size::INFINITE),
634        );
635    }
636
637    fn operate(&mut self, layout: Layout<'_>, renderer: &Renderer, operation: &mut dyn Operation) {
638        let Some(bubble) = layout.children().next() else {
639            return;
640        };
641        self.bubble
642            .as_widget_mut()
643            .operate(self.tree, bubble, renderer, operation);
644    }
645}
646
647#[cfg(test)]
648mod tests {
649    use super::*;
650    use crate::theme::{dark, light};
651
652    #[test]
653    fn defaults_to_top_without_delay() {
654        let t: Tooltip<'_, ()> = tooltip(text("Hover"), "Hint");
655        assert_eq!(t.position, Position::Top);
656        assert_eq!(t.delay, Duration::ZERO);
657        assert_eq!(t.max_width, None);
658        assert_eq!(t.text_size, None);
659    }
660
661    #[test]
662    fn builder_sets_every_option() {
663        let t: Tooltip<'_, ()> = tooltip(text("Hover"), "Hint")
664            .position(Position::Left)
665            .delay(Duration::from_millis(300))
666            .max_width(240.0)
667            .text_size(13.0);
668        assert_eq!(t.position, Position::Left);
669        assert_eq!(t.delay, Duration::from_millis(300));
670        assert_eq!(t.max_width, Some(240.0));
671        assert_eq!(t.text_size, Some(13.0));
672    }
673
674    #[test]
675    fn bubble_inverts_the_page_in_both_themes() {
676        for theme in [light(), dark()] {
677            let tokens = Tokens::of(&theme);
678            let style = style(&tokens);
679            assert_eq!(style.background, Some(Background::Color(tokens.primary)));
680            assert_eq!(style.text_color, Some(tokens.primary_foreground));
681            assert_ne!(tokens.primary, tokens.background);
682        }
683    }
684
685    #[test]
686    fn short_labels_are_small_and_sentences_a_size_up() {
687        assert_eq!(label_size("Bold", None), text_size::XS);
688        assert_eq!(label_size(&"a".repeat(LONG_LABEL), None), text_size::XS);
689        assert_eq!(label_size(&"a".repeat(LONG_LABEL + 1), None), text_size::SM);
690        assert_eq!(label_size("Bold", Some(16.0)), 16.0);
691        assert_eq!(label_size(&"a".repeat(80), Some(11.0)), 11.0);
692    }
693
694    #[test]
695    fn keyboard_focus_shows_but_pointer_focus_does_not() {
696        assert_eq!(Focus::None.next(true, false), Focus::Keyboard);
697        assert_eq!(Focus::None.next(true, true), Focus::Pointer);
698        assert_eq!(Focus::Pointer.next(true, false), Focus::Pointer);
699        assert_eq!(Focus::Keyboard.next(true, false), Focus::Keyboard);
700        assert_eq!(Focus::Keyboard.next(true, true), Focus::Pointer);
701        for focus in [Focus::None, Focus::Pointer, Focus::Keyboard] {
702            assert_eq!(focus.next(false, false), Focus::None);
703            assert_eq!(focus.next(false, true), Focus::None);
704        }
705    }
706
707    #[test]
708    fn shown_while_hovered_or_keyboard_focused() {
709        let hovered = State {
710            hover: Hover::Open {
711                cursor: Point::ORIGIN,
712            },
713            focus: Focus::None,
714        };
715        assert!(hovered.shown());
716        assert_eq!(hovered.cursor(), Some(Point::ORIGIN));
717
718        let focused = State {
719            hover: Hover::Idle,
720            focus: Focus::Keyboard,
721        };
722        assert!(focused.shown());
723        assert_eq!(focused.cursor(), None);
724
725        assert!(!State::default().shown());
726        assert!(
727            !State {
728                focus: Focus::Pointer,
729                ..State::default()
730            }
731            .shown()
732        );
733    }
734
735    #[test]
736    fn bubble_sits_on_the_requested_side() {
737        let content = Rectangle::new(Point::new(100.0, 100.0), Size::new(40.0, 20.0));
738        let bubble = Size::new(60.0, 24.0);
739        let at = |placement, cursor| place(placement, content.position(), content, bubble, cursor);
740        let gap = GAP + EDGE;
741
742        assert_eq!(
743            at(Position::Top, None),
744            Point::new(90.0, 100.0 - 24.0 - gap)
745        );
746        assert_eq!(at(Position::Bottom, None), Point::new(90.0, 120.0 + gap));
747        assert_eq!(
748            at(Position::Left, None),
749            Point::new(100.0 - 60.0 - gap, 98.0)
750        );
751        assert_eq!(at(Position::Right, None), Point::new(140.0 + gap, 98.0));
752        assert_eq!(
753            at(Position::FollowCursor, Some(Point::new(110.0, 105.0))),
754            Point::new(110.0, 81.0)
755        );
756        assert_eq!(
757            at(Position::FollowCursor, None),
758            at(Position::Top, None),
759            "keyboard focus has no pointer to follow"
760        );
761    }
762
763    #[test]
764    fn a_bubble_with_no_room_flips_to_the_other_side() {
765        let window = Rectangle::with_size(Size::new(300.0, 200.0));
766        let bubble = Size::new(60.0, 24.0);
767        let side = |placement, content: Rectangle| {
768            side_that_fits(placement, content.position(), content, bubble, window)
769        };
770        let middle = Rectangle::new(Point::new(120.0, 90.0), Size::new(40.0, 20.0));
771        for placement in [
772            Position::Top,
773            Position::Bottom,
774            Position::Left,
775            Position::Right,
776        ] {
777            assert_eq!(side(placement, middle), placement);
778        }
779        let top_right = Rectangle::new(Point::new(256.0, 4.0), Size::new(40.0, 20.0));
780        assert_eq!(side(Position::Top, top_right), Position::Bottom);
781        assert_eq!(side(Position::Right, top_right), Position::Left);
782        let bottom_left = Rectangle::new(Point::new(4.0, 176.0), Size::new(40.0, 20.0));
783        assert_eq!(side(Position::Bottom, bottom_left), Position::Top);
784        assert_eq!(side(Position::Left, bottom_left), Position::Right);
785        assert_eq!(
786            side(Position::FollowCursor, top_right),
787            Position::FollowCursor
788        );
789    }
790
791    #[test]
792    fn bubble_is_kept_inside_the_window() {
793        let window = Rectangle::with_size(Size::new(200.0, 100.0));
794        let inside = Rectangle::new(Point::new(10.0, 10.0), Size::new(50.0, 20.0));
795        assert_eq!(keep_inside(inside, window), inside);
796
797        let left = Rectangle::new(Point::new(-20.0, -5.0), Size::new(50.0, 20.0));
798        assert_eq!(keep_inside(left, window).position(), Point::ORIGIN);
799
800        let right = Rectangle::new(Point::new(180.0, 90.0), Size::new(50.0, 20.0));
801        assert_eq!(
802            keep_inside(right, window).position(),
803            Point::new(150.0, 80.0)
804        );
805    }
806}