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
use crate::ui::widgets::Controller;
use crate::ui::*;
/// Adds hover behavior to a widget.
pub struct Hover<T> {
/// A closure that will be invoked when the child widget is hovered.
action: Box<dyn Fn(bool, &Context<'_>, &mut T)>,
}
impl<T> Hover<T> {
/// Create a new hoverable [`Controller`] widget.
pub fn new(action: impl Fn(bool, &Context<'_>, &mut T) + 'static) -> Self {
Hover {
action: Box::new(action),
}
}
}
impl<T, W: Widget<T>> Controller<T, W> for Hover<T> {
fn event(
&mut self,
child: &mut W,
event: &WidgetEvent,
ctx: &Context<'_>,
data: &mut T,
) -> ControlFlow<()> {
match event {
WidgetEvent::MouseEnter { .. } => {
(self.action)(true, ctx, data);
// Continue because we want events to be triggered for other widgets
// in case the mouse has exited another widget.
return ControlFlow::Continue(());
}
WidgetEvent::MouseExit { .. } => {
(self.action)(false, ctx, data);
// Continue because we want events to be triggered for other widgets
// in case the mouse has entered another widget.
return ControlFlow::Continue(());
}
_ => {}
}
child.event(event, ctx, data)
}
}