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
//! Run a closure on events when focused

use euclid::Size2D;

use crate::{event::Event, unit::Cell, Printer, View as ViewTrait};

/// The view itself
pub struct View<V, F> {
    inner: V,
    f: F,
}

impl<V, F> View<V, F> {
    pub fn new<A, B, C>(view: V, f: F) -> Self
    where
        F: Fn(&Event<A>, B) -> Box<dyn Iterator<Item = C>>,
    {
        Self {
            inner: view,
            f,
        }
    }
}

/// Shorthand for [`View::new()`]
///
/// [`View::new()`]: View::new
pub fn new<V, F, A, B, C>(view: V, f: F) -> View<V, F>
where
    F: Fn(&Event<A>, B) -> Box<dyn Iterator<Item = C>>,
{
    View::new(view, f)
}

impl<T, V, F, M> ViewTrait<T, M> for View<V, F>
where
    F: Fn(&Event<T>, bool) -> Box<dyn Iterator<Item = M>>,
    V: ViewTrait<T, M>,
{
    fn draw(&self, printer: &Printer, focused: bool) {
        self.inner.draw(&printer, focused);
    }

    fn width(&self) -> Size2D<u16, Cell> {
        self.inner.width()
    }

    fn height(&self) -> Size2D<u16, Cell> {
        self.inner.height()
    }

    fn layout(&self, constraint: Size2D<u16, Cell>) -> Size2D<u16, Cell> {
        self.inner.layout(constraint)
    }

    fn event(
        &mut self,
        event: &Event<T>,
        focused: bool,
    ) -> Box<dyn Iterator<Item = M>> {
        (self.f)(event, focused)
    }

    fn interactive(&self) -> bool {
        self.inner.interactive()
    }
}

pub trait ViewExt {
    fn on_event<F, A, B, C>(self, f: F) -> View<Self, F>
    where
        Self: Sized,
        F: Fn(&Event<A>, B) -> Box<dyn Iterator<Item = C>>,
    {
        View::new(self, f)
    }
}

impl<V> ViewExt for V {}