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
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
use crate::context::TreeProps;
use crate::vg;
use crate::{modifiers::ModalModel, prelude::*};

/// A tooltip view.
///
/// Should be used with the [tooltip](crate::modifiers::ActionModifiers::tooltip) modifier.
///
/// # Example
/// ```
/// # use vizia_core::prelude::*;
/// #
/// # enum AppEvent {
/// #     Action,
/// # }
/// #
/// # let cx = &mut Context::default();
/// #
/// Button::new(cx, |cx| Label::new(cx, "Text"))
///     .tooltip(|cx|{
///         Tooltip::new(cx, |cx|{
///             Label::new(cx, "Tooltip Text");
///         })
///     })

#[derive(Lens)]
pub struct Tooltip {
    placement: Placement,
    shift: Placement,
    show_arrow: bool,
    arrow_size: Length,
}

impl Tooltip {
    /// Creates a new Tooltip view with the given content.
    ///
    /// Should be used with the [tooltip](crate::modifiers::ActionModifiers::tooltip) modifier.
    ///
    /// # Example
    /// ```
    /// # use vizia_core::prelude::*;
    /// #
    /// # enum AppEvent {
    /// #     Action,
    /// # }
    /// #
    /// # let cx = &mut Context::default();
    /// #
    /// Button::new(cx, |cx| Label::new(cx, "Text"))
    ///     .tooltip(|cx|{
    ///         Tooltip::new(cx, |cx|{
    ///             Label::new(cx, "Tooltip Text");
    ///         })
    ///     })
    /// ```
    pub fn new(cx: &mut Context, content: impl FnOnce(&mut Context)) -> Handle<Self> {
        Self {
            placement: Placement::Bottom,
            shift: Placement::Bottom,
            show_arrow: true,
            arrow_size: Length::Value(LengthValue::Px(8.0)),
        }
        .build(cx, |cx| {
            Binding::new(cx, Tooltip::show_arrow, |cx, show_arrow| {
                if show_arrow.get(cx) {
                    Arrow::new(cx);
                }
            });
            (content)(cx);
        })
        .z_index(110)
        .hoverable(false)
        .position_type(PositionType::SelfDirected)
        .space(Pixels(0.0))
        .on_build(|ex| {
            ex.add_listener(move |tooltip: &mut Tooltip, ex, event| {
                let flag = ModalModel::tooltip_visible.get(ex);
                event.map(|window_event, meta| match window_event {
                    WindowEvent::MouseDown(_) => {
                        if flag && meta.origin != ex.current() {
                            ex.toggle_class("vis", false);
                        }
                    }

                    WindowEvent::MouseMove(x, y) => {
                        if tooltip.placement == Placement::Cursor && !x.is_nan() && !y.is_nan() {
                            let scale = ex.scale_factor();
                            let parent = ex.parent();
                            let parent_bounds = ex.cache.get_bounds(parent);
                            if parent_bounds.contains_point(*x, *y) {
                                ex.set_left(Pixels(
                                    ((*x - parent_bounds.x) - ex.bounds().width() / 2.0) / scale,
                                ));
                                ex.set_top(Pixels((*y - parent_bounds.y) / scale));
                            }
                        }
                    }

                    _ => {}
                });
            });
        })
    }
}

impl View for Tooltip {
    fn element(&self) -> Option<&'static str> {
        Some("tooltip")
    }

    fn event(&mut self, cx: &mut EventContext, event: &mut Event) {
        event.map(|window_event, _| match window_event {
            // Reposition popup if there isn't enough room for it.
            WindowEvent::GeometryChanged(_) => {
                let parent = cx.parent();
                let parent_bounds = cx.cache.get_bounds(parent);
                let bounds = cx.bounds();
                let window_bounds =
                    cx.cache.get_bounds(cx.parent_window().unwrap_or(Entity::root()));

                let arrow_size = self.arrow_size.to_px().unwrap() * cx.scale_factor();

                let mut available = AvailablePlacement::all();

                let top_start_bounds = BoundingBox::from_min_max(
                    parent_bounds.left(),
                    parent_bounds.top() - bounds.height() - arrow_size,
                    parent_bounds.left() + bounds.width(),
                    parent_bounds.top(),
                );

                available
                    .set(AvailablePlacement::TOP_START, window_bounds.contains(&top_start_bounds));

                let top_bounds = BoundingBox::from_min_max(
                    parent_bounds.center().0 - bounds.width() / 2.0,
                    parent_bounds.top() - bounds.height() - arrow_size,
                    parent_bounds.center().0 + bounds.width() / 2.0,
                    parent_bounds.top(),
                );

                available.set(AvailablePlacement::TOP, window_bounds.contains(&top_bounds));

                let top_end_bounds = BoundingBox::from_min_max(
                    parent_bounds.right() - bounds.width(),
                    parent_bounds.top() - bounds.height() - arrow_size,
                    parent_bounds.right(),
                    parent_bounds.top(),
                );

                available.set(AvailablePlacement::TOP_END, window_bounds.contains(&top_end_bounds));

                let bottom_start_bounds = BoundingBox::from_min_max(
                    parent_bounds.left(),
                    parent_bounds.bottom(),
                    parent_bounds.left() + bounds.width(),
                    parent_bounds.bottom() + bounds.height() + arrow_size,
                );

                available.set(
                    AvailablePlacement::BOTTOM_START,
                    window_bounds.contains(&bottom_start_bounds),
                );

                let bottom_bounds = BoundingBox::from_min_max(
                    parent_bounds.center().0 - bounds.width() / 2.0,
                    parent_bounds.bottom(),
                    parent_bounds.center().0 + bounds.width() / 2.0,
                    parent_bounds.bottom() + bounds.height() + arrow_size,
                );

                available.set(AvailablePlacement::BOTTOM, window_bounds.contains(&bottom_bounds));

                let bottom_end_bounds = BoundingBox::from_min_max(
                    parent_bounds.right() - bounds.width(),
                    parent_bounds.bottom(),
                    parent_bounds.right(),
                    parent_bounds.bottom() + bounds.height() + arrow_size,
                );

                available.set(
                    AvailablePlacement::BOTTOM_END,
                    window_bounds.contains(&bottom_end_bounds),
                );

                let left_start_bounds = BoundingBox::from_min_max(
                    parent_bounds.left() - bounds.width() - arrow_size,
                    parent_bounds.top(),
                    parent_bounds.left(),
                    parent_bounds.top() + bounds.height(),
                );

                available.set(
                    AvailablePlacement::LEFT_START,
                    window_bounds.contains(&left_start_bounds),
                );

                let left_bounds = BoundingBox::from_min_max(
                    parent_bounds.left() - bounds.width() - arrow_size,
                    parent_bounds.center().1 - bounds.height() / 2.0,
                    parent_bounds.left(),
                    parent_bounds.center().1 + bounds.height() / 2.0,
                );

                available.set(AvailablePlacement::LEFT, window_bounds.contains(&left_bounds));

                let left_end_bounds = BoundingBox::from_min_max(
                    parent_bounds.left() - bounds.width() - arrow_size,
                    parent_bounds.bottom() - bounds.height(),
                    parent_bounds.left(),
                    parent_bounds.bottom(),
                );

                available
                    .set(AvailablePlacement::LEFT_END, window_bounds.contains(&left_end_bounds));

                let right_start_bounds = BoundingBox::from_min_max(
                    parent_bounds.right(),
                    parent_bounds.top(),
                    parent_bounds.right() + bounds.width() + arrow_size,
                    parent_bounds.top() + bounds.height(),
                );

                available.set(
                    AvailablePlacement::RIGHT_START,
                    window_bounds.contains(&right_start_bounds),
                );

                let right_bounds = BoundingBox::from_min_max(
                    parent_bounds.right(),
                    parent_bounds.center().1 - bounds.height() / 2.0,
                    parent_bounds.right() + bounds.width() + arrow_size,
                    parent_bounds.center().1 + bounds.height() / 2.0,
                );

                available.set(AvailablePlacement::RIGHT, window_bounds.contains(&right_bounds));

                let right_end_bounds = BoundingBox::from_min_max(
                    parent_bounds.right(),
                    parent_bounds.bottom() - bounds.height(),
                    parent_bounds.right() + bounds.width() + arrow_size,
                    parent_bounds.bottom(),
                );

                available
                    .set(AvailablePlacement::RIGHT_END, window_bounds.contains(&right_end_bounds));

                let scale = cx.scale_factor();

                self.shift = self.placement.place(available);

                let arrow_size = self.arrow_size.to_px().unwrap();

                let translate = match self.shift {
                    Placement::Top => (
                        -(bounds.width() - parent_bounds.width()) / (2.0 * scale),
                        -bounds.height() / scale - arrow_size,
                    ),
                    Placement::TopStart => (0.0, -bounds.height() / scale - arrow_size),
                    Placement::TopEnd => (
                        -(bounds.width() - parent_bounds.width()) / scale,
                        -bounds.height() / scale - arrow_size,
                    ),
                    Placement::Bottom => (
                        -(bounds.width() - parent_bounds.width()) / (2.0 * scale),
                        parent_bounds.height() / scale + arrow_size,
                    ),
                    Placement::BottomStart => (0.0, parent_bounds.height() / scale + arrow_size),
                    Placement::BottomEnd => (
                        -(bounds.width() - parent_bounds.width()) / scale,
                        parent_bounds.height() / scale + arrow_size,
                    ),
                    Placement::LeftStart => (-(bounds.width() / scale) - arrow_size, 0.0),
                    Placement::Left => (
                        -(bounds.width() / scale) - arrow_size,
                        -(bounds.height() - parent_bounds.height()) / (2.0 * scale),
                    ),
                    Placement::LeftEnd => (
                        -(bounds.width() / scale) - arrow_size,
                        -(bounds.height() - parent_bounds.height()) / scale,
                    ),
                    Placement::RightStart => ((parent_bounds.width() / scale) + arrow_size, 0.0),
                    Placement::Right => (
                        (parent_bounds.width() / scale) + arrow_size,
                        -(bounds.height() - parent_bounds.height()) / (2.0 * scale),
                    ),
                    Placement::RightEnd => (
                        (parent_bounds.width() / scale) + arrow_size,
                        -(bounds.height() - parent_bounds.height()) / scale,
                    ),

                    _ => (0.0, 0.0),
                };

                cx.set_translate((Pixels(translate.0.round()), Pixels(translate.1.round())));
            }

            _ => {}
        });
    }
}

impl<'a> Handle<'a, Tooltip> {
    // TODO: Change this to use Res when lens value PR is merged
    /// Sets the position where the tooltip should appear relative to its parent element.
    /// Defaults to `Placement::Bottom`.
    pub fn placement(self, placement: Placement) -> Self {
        self.modify(|tooltip| {
            tooltip.placement = placement;
            tooltip.shift = placement;
        })
    }

    // TODO: Change this to use Res when lens value PR is merged
    /// Sets whether the tooltip should include an arrow. Defaults to true.
    pub fn arrow(self, show_arrow: bool) -> Self {
        self.modify(|tooltip| tooltip.show_arrow = show_arrow)
    }

    pub fn arrow_size(self, size: impl Into<Length>) -> Self {
        self.modify(|tooltip| tooltip.arrow_size = size.into())
    }
}

/// An arrow view used by the Tooltip view.
pub(crate) struct Arrow {}

impl Arrow {
    pub(crate) fn new(cx: &mut Context) -> Handle<Self> {
        Self {}.build(cx, |_| {}).bind(Tooltip::shift, |mut handle, placement| {
            let (t, b) = match placement.get(&handle) {
                Placement::TopStart | Placement::Top | Placement::TopEnd => {
                    (Percentage(100.0), Stretch(1.0))
                }
                Placement::BottomStart | Placement::Bottom | Placement::BottomEnd => {
                    (Stretch(1.0), Percentage(100.0))
                }
                _ => (Stretch(1.0), Stretch(1.0)),
            };

            let (l, r) = match placement.get(&handle) {
                Placement::LeftStart | Placement::Left | Placement::LeftEnd => {
                    (Percentage(100.0), Stretch(1.0))
                }
                Placement::RightStart | Placement::Right | Placement::RightEnd => {
                    (Stretch(1.0), Percentage(100.0))
                }
                Placement::TopStart | Placement::BottomStart => {
                    // TODO: Use border radius
                    (Pixels(8.0), Stretch(1.0))
                }
                Placement::TopEnd | Placement::BottomEnd => {
                    // TODO: Use border radius
                    (Stretch(1.0), Pixels(8.0))
                }
                _ => (Stretch(1.0), Stretch(1.0)),
            };

            handle = handle.top(t).bottom(b).left(l).right(r);

            handle.bind(Tooltip::arrow_size, move |handle, arrow_size| {
                let arrow_size = arrow_size.get(&handle).to_px().unwrap_or(8.0);
                let (w, h) = match placement.get(&handle) {
                    Placement::Top
                    | Placement::Bottom
                    | Placement::TopStart
                    | Placement::BottomStart
                    | Placement::TopEnd
                    | Placement::BottomEnd => (Pixels(arrow_size * 2.0), Pixels(arrow_size)),

                    _ => (Pixels(arrow_size), Pixels(arrow_size * 2.0)),
                };

                handle.width(w).height(h);
            });
        })
    }
}

impl View for Arrow {
    fn element(&self) -> Option<&'static str> {
        Some("arrow")
    }
    fn draw(&self, cx: &mut DrawContext, canvas: &Canvas) {
        let bounds = cx.bounds();
        let mut path = vg::Path::new();
        match Tooltip::shift.get(cx) {
            Placement::Bottom | Placement::BottomStart | Placement::BottomEnd => {
                path.move_to(bounds.bottom_left());
                path.line_to(bounds.center_top());
                path.line_to(bounds.bottom_right());
                path.line_to(bounds.bottom_left());
            }

            Placement::Top | Placement::TopStart | Placement::TopEnd => {
                path.move_to(bounds.top_left());
                path.line_to(bounds.center_bottom());
                path.line_to(bounds.top_right());
                path.line_to(bounds.top_left());
            }

            Placement::Left | Placement::LeftStart | Placement::LeftEnd => {
                path.move_to(bounds.top_left());
                path.line_to(bounds.center_right());
                path.line_to(bounds.bottom_left());
                path.line_to(bounds.top_left());
            }

            Placement::Right | Placement::RightStart | Placement::RightEnd => {
                path.move_to(bounds.top_right());
                path.line_to(bounds.center_left());
                path.line_to(bounds.bottom_right());
                path.line_to(bounds.top_right());
            }

            _ => {}
        }
        path.close();

        let bg = cx.background_color();

        let mut paint = vg::Paint::default();
        paint.set_color(bg);
        canvas.draw_path(&path, &paint);
    }
}