1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
//! Display a widget over another.
use crate::event;
use crate::layout;
use crate::mouse;
use crate::renderer;
use crate::text;
use crate::widget;
use crate::widget::container;
use crate::widget::overlay;
use crate::widget::{Text, Tree};
use crate::{
    Clipboard, Element, Event, Layout, Length, Padding, Point, Rectangle,
    Shell, Size, Vector, Widget,
};

use std::borrow::Cow;

/// An element to display a widget over another.
#[allow(missing_debug_implementations)]
pub struct Tooltip<'a, Message, Renderer: text::Renderer>
where
    Renderer: text::Renderer,
    Renderer::Theme: container::StyleSheet + widget::text::StyleSheet,
{
    content: Element<'a, Message, Renderer>,
    tooltip: Text<'a, Renderer>,
    position: Position,
    gap: u16,
    padding: u16,
    snap_within_viewport: bool,
    style: <Renderer::Theme as container::StyleSheet>::Style,
}

impl<'a, Message, Renderer> Tooltip<'a, Message, Renderer>
where
    Renderer: text::Renderer,
    Renderer::Theme: container::StyleSheet + widget::text::StyleSheet,
{
    /// The default padding of a [`Tooltip`] drawn by this renderer.
    const DEFAULT_PADDING: u16 = 5;

    /// Creates a new [`Tooltip`].
    ///
    /// [`Tooltip`]: struct.Tooltip.html
    pub fn new(
        content: impl Into<Element<'a, Message, Renderer>>,
        tooltip: impl Into<Cow<'a, str>>,
        position: Position,
    ) -> Self {
        Tooltip {
            content: content.into(),
            tooltip: Text::new(tooltip),
            position,
            gap: 0,
            padding: Self::DEFAULT_PADDING,
            snap_within_viewport: true,
            style: Default::default(),
        }
    }

    /// Sets the size of the text of the [`Tooltip`].
    pub fn size(mut self, size: u16) -> Self {
        self.tooltip = self.tooltip.size(size);
        self
    }

    /// Sets the font of the [`Tooltip`].
    ///
    /// [`Font`]: Renderer::Font
    pub fn font(mut self, font: impl Into<Renderer::Font>) -> Self {
        self.tooltip = self.tooltip.font(font);
        self
    }

    /// Sets the gap between the content and its [`Tooltip`].
    pub fn gap(mut self, gap: u16) -> Self {
        self.gap = gap;
        self
    }

    /// Sets the padding of the [`Tooltip`].
    pub fn padding(mut self, padding: u16) -> Self {
        self.padding = padding;
        self
    }

    /// Sets whether the [`Tooltip`] is snapped within the viewport.
    pub fn snap_within_viewport(mut self, snap: bool) -> Self {
        self.snap_within_viewport = snap;
        self
    }

    /// Sets the style of the [`Tooltip`].
    pub fn style(
        mut self,
        style: impl Into<<Renderer::Theme as container::StyleSheet>::Style>,
    ) -> Self {
        self.style = style.into();
        self
    }
}

impl<'a, Message, Renderer> Widget<Message, Renderer>
    for Tooltip<'a, Message, Renderer>
where
    Renderer: text::Renderer,
    Renderer::Theme: container::StyleSheet + widget::text::StyleSheet,
{
    fn children(&self) -> Vec<Tree> {
        vec![Tree::new(&self.content)]
    }

    fn diff(&self, tree: &mut Tree) {
        tree.diff_children(std::slice::from_ref(&self.content))
    }

    fn width(&self) -> Length {
        self.content.as_widget().width()
    }

    fn height(&self) -> Length {
        self.content.as_widget().height()
    }

    fn layout(
        &self,
        renderer: &Renderer,
        limits: &layout::Limits,
    ) -> layout::Node {
        self.content.as_widget().layout(renderer, limits)
    }

    fn on_event(
        &mut self,
        tree: &mut Tree,
        event: Event,
        layout: Layout<'_>,
        cursor_position: Point,
        renderer: &Renderer,
        clipboard: &mut dyn Clipboard,
        shell: &mut Shell<'_, Message>,
    ) -> event::Status {
        self.content.as_widget_mut().on_event(
            &mut tree.children[0],
            event,
            layout,
            cursor_position,
            renderer,
            clipboard,
            shell,
        )
    }

    fn mouse_interaction(
        &self,
        tree: &Tree,
        layout: Layout<'_>,
        cursor_position: Point,
        viewport: &Rectangle,
        renderer: &Renderer,
    ) -> mouse::Interaction {
        self.content.as_widget().mouse_interaction(
            &tree.children[0],
            layout,
            cursor_position,
            viewport,
            renderer,
        )
    }

    fn draw(
        &self,
        tree: &Tree,
        renderer: &mut Renderer,
        theme: &Renderer::Theme,
        inherited_style: &renderer::Style,
        layout: Layout<'_>,
        cursor_position: Point,
        viewport: &Rectangle,
    ) {
        self.content.as_widget().draw(
            &tree.children[0],
            renderer,
            theme,
            inherited_style,
            layout,
            cursor_position,
            viewport,
        );

        let tooltip = &self.tooltip;

        draw(
            renderer,
            theme,
            inherited_style,
            layout,
            cursor_position,
            viewport,
            self.position,
            self.gap,
            self.padding,
            self.snap_within_viewport,
            &self.style,
            |renderer, limits| {
                Widget::<(), Renderer>::layout(tooltip, renderer, limits)
            },
            |renderer, defaults, layout, cursor_position, viewport| {
                Widget::<(), Renderer>::draw(
                    tooltip,
                    &Tree::empty(),
                    renderer,
                    theme,
                    defaults,
                    layout,
                    cursor_position,
                    viewport,
                );
            },
        );
    }

    fn overlay<'b>(
        &'b mut self,
        tree: &'b mut Tree,
        layout: Layout<'_>,
        renderer: &Renderer,
    ) -> Option<overlay::Element<'b, Message, Renderer>> {
        self.content.as_widget_mut().overlay(
            &mut tree.children[0],
            layout,
            renderer,
        )
    }
}

impl<'a, Message, Renderer> From<Tooltip<'a, Message, Renderer>>
    for Element<'a, Message, Renderer>
where
    Message: 'a,
    Renderer: 'a + text::Renderer,
    Renderer::Theme: container::StyleSheet + widget::text::StyleSheet,
{
    fn from(
        tooltip: Tooltip<'a, Message, Renderer>,
    ) -> Element<'a, Message, Renderer> {
        Element::new(tooltip)
    }
}

/// The position of the tooltip. Defaults to following the cursor.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Position {
    /// The tooltip will follow the cursor.
    FollowCursor,
    /// The tooltip will appear on the top of the widget.
    Top,
    /// The tooltip will appear on the bottom of the widget.
    Bottom,
    /// The tooltip will appear on the left of the widget.
    Left,
    /// The tooltip will appear on the right of the widget.
    Right,
}

/// Draws a [`Tooltip`].
pub fn draw<Renderer>(
    renderer: &mut Renderer,
    theme: &Renderer::Theme,
    inherited_style: &renderer::Style,
    layout: Layout<'_>,
    cursor_position: Point,
    viewport: &Rectangle,
    position: Position,
    gap: u16,
    padding: u16,
    snap_within_viewport: bool,
    style: &<Renderer::Theme as container::StyleSheet>::Style,
    layout_text: impl FnOnce(&Renderer, &layout::Limits) -> layout::Node,
    draw_text: impl FnOnce(
        &mut Renderer,
        &renderer::Style,
        Layout<'_>,
        Point,
        &Rectangle,
    ),
) where
    Renderer: crate::Renderer,
    Renderer::Theme: container::StyleSheet,
{
    use container::StyleSheet;

    let bounds = layout.bounds();

    if bounds.contains(cursor_position) {
        let gap = f32::from(gap);
        let style = theme.appearance(style);

        let defaults = renderer::Style {
            text_color: style.text_color.unwrap_or(inherited_style.text_color),
        };

        let text_layout = layout_text(
            renderer,
            &layout::Limits::new(
                Size::ZERO,
                snap_within_viewport
                    .then(|| viewport.size())
                    .unwrap_or(Size::INFINITY),
            )
            .pad(Padding::new(padding)),
        );

        let padding = f32::from(padding);
        let text_bounds = text_layout.bounds();
        let x_center = bounds.x + (bounds.width - text_bounds.width) / 2.0;
        let y_center = bounds.y + (bounds.height - text_bounds.height) / 2.0;

        let mut tooltip_bounds = {
            let offset = match position {
                Position::Top => Vector::new(
                    x_center,
                    bounds.y - text_bounds.height - gap - padding,
                ),
                Position::Bottom => Vector::new(
                    x_center,
                    bounds.y + bounds.height + gap + padding,
                ),
                Position::Left => Vector::new(
                    bounds.x - text_bounds.width - gap - padding,
                    y_center,
                ),
                Position::Right => Vector::new(
                    bounds.x + bounds.width + gap + padding,
                    y_center,
                ),
                Position::FollowCursor => Vector::new(
                    cursor_position.x,
                    cursor_position.y - text_bounds.height,
                ),
            };

            Rectangle {
                x: offset.x - padding,
                y: offset.y - padding,
                width: text_bounds.width + padding * 2.0,
                height: text_bounds.height + padding * 2.0,
            }
        };

        if snap_within_viewport {
            if tooltip_bounds.x < viewport.x {
                tooltip_bounds.x = viewport.x;
            } else if viewport.x + viewport.width
                < tooltip_bounds.x + tooltip_bounds.width
            {
                tooltip_bounds.x =
                    viewport.x + viewport.width - tooltip_bounds.width;
            }

            if tooltip_bounds.y < viewport.y {
                tooltip_bounds.y = viewport.y;
            } else if viewport.y + viewport.height
                < tooltip_bounds.y + tooltip_bounds.height
            {
                tooltip_bounds.y =
                    viewport.y + viewport.height - tooltip_bounds.height;
            }
        }

        renderer.with_layer(Rectangle::with_size(Size::INFINITY), |renderer| {
            container::draw_background(renderer, &style, tooltip_bounds);

            draw_text(
                renderer,
                &defaults,
                Layout::with_offset(
                    Vector::new(
                        tooltip_bounds.x + padding,
                        tooltip_bounds.y + padding,
                    ),
                    &text_layout,
                ),
                cursor_position,
                viewport,
            )
        });
    }
}