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
use crate::*;

/// Reads or writes a value owned by a source-of-truth.
pub trait Binding<S>: Clone + Copy + 'static {
    fn get<'a>(&self, cx: &'a Context) -> &'a S;
    fn get_mut<'a>(&self, cx: &'a mut Context) -> &'a mut S;

    fn with<T>(&self, cx: &Context, f: impl FnOnce(&S) -> T) -> T {
        f(self.get(cx))
    }

    fn with_mut<T>(&self, cx: &mut Context, f: impl FnOnce(&mut S) -> T) -> T {
        f(self.get_mut(cx))
    }
}

pub fn setter<S>(binding: impl Binding<S>) -> impl Fn(S, &mut Context) {
    move |s, cx| binding.with_mut(cx, |v| *v = s)
}

pub struct Map<B, L, S, T> {
    binding: B,
    lens: L,
    phantom_s: std::marker::PhantomData<S>,
    phantom_t: std::marker::PhantomData<T>,
}

impl<B, L, S, T> Clone for Map<B, L, S, T>
where
    B: Copy,
    L: Copy,
    S: 'static,
    T: 'static,
{
    fn clone(&self) -> Self {
        *self
    }
}

impl<B, L, S, T> Copy for Map<B, L, S, T>
where
    B: Copy,
    L: Copy,
    S: 'static,
    T: 'static,
{
}

impl<S, B, L, T> Map<B, L, S, T>
where
    B: Binding<T>,
    L: Lens<T, S>,
    S: 'static,
    T: 'static,
{
    pub fn new(binding: B, lens: L) -> Self {
        Self {
            binding,
            lens,
            phantom_s: Default::default(),
            phantom_t: Default::default(),
        }
    }
}

pub fn bind<S, T>(binding: impl Binding<S>, lens: impl Lens<S, T>) -> impl Binding<T>
where
    S: 'static,
    T: 'static,
{
    Map::new(binding, lens)
}

impl<S, B, L, T> Binding<S> for Map<B, L, S, T>
where
    B: Binding<T>,
    L: Lens<T, S>,
    S: 'static,
    T: 'static,
{
    fn get<'a>(&self, cx: &'a Context) -> &'a S {
        self.lens.focus(self.binding.get(cx))
    }
    fn get_mut<'a>(&self, cx: &'a mut Context) -> &'a mut S {
        self.lens.focus_mut(self.binding.get_mut(cx))
    }
}

#[cfg(test)]
mod tests {

    use super::*;

    #[derive(Clone, Default)]
    struct MyState {
        x: i32,
    }

    make_lens!(MyLens, MyState, i32, x);

    #[test]
    fn test_lens() {
        let mut s = MyState { x: 0 };
        *MyLens {}.focus_mut(&mut s) = 42;
        assert_eq!(*MyLens {}.focus(&s), 42);
    }

    #[test]
    fn test_bind() {
        let mut cx = Context::new();
        let id = ViewId::default();
        cx.init_state(id, &MyState::default);
        let s = StateHandle::new(id);

        let b = bind(s, MyLens {});

        *b.get_mut(&mut cx) = 42;

        assert_eq!(*b.get(&cx), 42);
    }
}