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
use crate::{
direction::Direction,
event::{Event, EventResult},
view::{CannotFocus, View, ViewWrapper},
With,
};
pub struct FocusTracker<T> {
view: T,
on_focus_lost: Box<dyn FnMut(&mut T) -> EventResult>,
on_focus: Box<dyn FnMut(&mut T) -> EventResult>,
}
impl<T> FocusTracker<T> {
pub fn new(view: T) -> Self {
FocusTracker {
view,
on_focus_lost: Box::new(|_| EventResult::Ignored),
on_focus: Box::new(|_| EventResult::Ignored),
}
}
#[must_use]
pub fn on_focus<F>(self, f: F) -> Self
where
F: 'static + FnMut(&mut T) -> EventResult,
{
self.with(|s| s.on_focus = Box::new(f))
}
#[must_use]
pub fn on_focus_lost<F>(self, f: F) -> Self
where
F: 'static + FnMut(&mut T) -> EventResult,
{
self.with(|s| s.on_focus_lost = Box::new(f))
}
}
impl<T: View> ViewWrapper for FocusTracker<T> {
wrap_impl!(self.view: T);
fn wrap_take_focus(
&mut self,
source: Direction,
) -> Result<EventResult, CannotFocus> {
match self.view.take_focus(source) {
Ok(res) => Ok(res.and((self.on_focus)(&mut self.view))),
Err(CannotFocus) => Err(CannotFocus),
}
}
fn wrap_on_event(&mut self, event: Event) -> EventResult {
let res = if let Event::FocusLost = event {
(self.on_focus_lost)(&mut self.view)
} else {
EventResult::Ignored
};
res.and(self.view.on_event(event))
}
}