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
use std::sync::Arc;

use crate::binding::RatioLens;
use crate::prelude::*;

pub(crate) const SCROLL_SENSITIVITY: f32 = 20.0;

pub enum ScrollEvent {
    /// Sets the progress of scroll position between 0 and 1 for the x axis
    SetX(f32),
    /// Sets the progress of scroll position between 0 and 1 for the y axis
    SetY(f32),
    /// Adds given progress to scroll position for the x axis and clamps between 0 and 1
    ScrollX(f32),
    /// Adds given progress to scroll position for the y axis and clamps between 0 and 1
    ScrollY(f32),
    /// Sets the Size for the inner VStack which holds the content
    ChildGeo(f32, f32),
}

#[derive(Lens, Data, Clone)]
pub struct ScrollView {
    /// Progress of scroll position between 0 and 1 for the x axis
    pub scroll_x: f32,
    /// Progress of scroll position between 0 and 1 for the y axis
    pub scroll_y: f32,

    /// Callback called when the scrollview is scrolled.
    #[lens(ignore)]
    pub on_scroll: Option<Arc<dyn Fn(&mut EventContext, f32, f32) + Send + Sync>>,

    /// Width of the inner VStack which holds the content (typically bigger than container_width)
    pub inner_width: f32,
    /// Height of the inner VStack which holds the content (typically bigger than container_height)
    pub inner_height: f32,
    /// Width of the outer `ScrollView` which wraps the inner (typically smaller than inner_width)
    pub container_width: f32,
    /// Height of the outer `ScrollView` which wraps the inner (typically smaller than inner_height)
    pub container_height: f32,

    pub scroll_to_cursor: bool,
}

impl ScrollView {
    pub fn new<F>(
        cx: &mut Context,
        initial_x: f32,
        initial_y: f32,
        scroll_x: bool,
        scroll_y: bool,
        content: F,
    ) -> Handle<Self>
    where
        F: 'static + FnOnce(&mut Context),
    {
        Self {
            scroll_to_cursor: false,
            scroll_x: initial_x,
            scroll_y: initial_y,
            on_scroll: None,
            inner_width: 0.0,
            inner_height: 0.0,
            container_width: 0.0,
            container_height: 0.0,
        }
        .build(cx, move |cx| {
            ScrollContent::new(cx, content).bind(ScrollView::root, |handle, data| {
                let scale_factor = handle.scale_factor();
                let data = data.get(&handle);
                let left = ((data.inner_width - data.container_width) * data.scroll_x).round()
                    / scale_factor;
                let top = ((data.inner_height - data.container_height) * data.scroll_y).round()
                    / scale_factor;
                handle.left(Units::Pixels(-left.abs())).top(Units::Pixels(-top.abs()));
            });

            if scroll_y {
                Scrollbar::new(
                    cx,
                    ScrollView::scroll_y,
                    RatioLens::new(ScrollView::container_height, ScrollView::inner_height),
                    Orientation::Vertical,
                    |cx, value| {
                        cx.emit(ScrollEvent::SetY(value));
                    },
                )
                .position_type(PositionType::SelfDirected)
                .scroll_to_cursor(Self::scroll_to_cursor);
            }

            if scroll_x {
                Scrollbar::new(
                    cx,
                    ScrollView::scroll_x,
                    RatioLens::new(ScrollView::container_width, ScrollView::inner_width),
                    Orientation::Horizontal,
                    |cx, value| {
                        cx.emit(ScrollEvent::SetX(value));
                    },
                )
                .position_type(PositionType::SelfDirected)
                .scroll_to_cursor(Self::scroll_to_cursor);
            }
        })
        .toggle_class(
            "h-scroll",
            ScrollView::root.map(|data| data.container_width < data.inner_width),
        )
        .toggle_class(
            "v-scroll",
            ScrollView::root.map(|data| data.container_height < data.inner_height),
        )
    }

    fn reset(&mut self) {
        if self.inner_width == self.container_width {
            self.scroll_x = 0.0;
        }

        if self.inner_height == self.container_height {
            self.scroll_y = 0.0;
        }
    }
}

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

    fn event(&mut self, cx: &mut EventContext, event: &mut Event) {
        event.map(|scroll_update, meta| {
            match scroll_update {
                ScrollEvent::ScrollX(f) => {
                    self.scroll_x = (self.scroll_x + *f).clamp(0.0, 1.0);

                    if let Some(callback) = &self.on_scroll {
                        (callback)(cx, self.scroll_x, self.scroll_y);
                    }
                }

                ScrollEvent::ScrollY(f) => {
                    self.scroll_y = (self.scroll_y + *f).clamp(0.0, 1.0);
                    if let Some(callback) = &self.on_scroll {
                        (callback)(cx, self.scroll_x, self.scroll_y);
                    }
                }

                ScrollEvent::SetX(f) => {
                    self.scroll_x = *f;
                    if let Some(callback) = &self.on_scroll {
                        (callback)(cx, self.scroll_x, self.scroll_y);
                    }
                }

                ScrollEvent::SetY(f) => {
                    self.scroll_y = *f;
                    if let Some(callback) = &self.on_scroll {
                        (callback)(cx, self.scroll_x, self.scroll_y);
                    }
                }

                ScrollEvent::ChildGeo(w, h) => {
                    self.inner_width = *w;
                    self.inner_height = *h;
                    self.reset();
                }
            }

            // Prevent scroll events propagating to any parent scrollviews.
            // TODO: This might be desired behavior when the scrollview is scrolled all the way.
            meta.consume();
        });

        event.map(|window_event, meta| match window_event {
            WindowEvent::GeometryChanged(geo) => {
                if geo.contains(GeoChanged::WIDTH_CHANGED)
                    || geo.contains(GeoChanged::HEIGHT_CHANGED)
                {
                    let bounds = cx.bounds();
                    let scale_factor = cx.scale_factor();
                    let top = ((self.inner_height - self.container_height) * self.scroll_y).round()
                        / scale_factor;
                    let left = ((self.inner_width - self.container_width) * self.scroll_x).round()
                        / scale_factor;
                    self.container_width = bounds.width();
                    self.container_height = bounds.height();
                    self.scroll_y = ((top * scale_factor)
                        / (self.inner_height - self.container_height))
                        .clamp(0.0, 1.0);
                    self.scroll_x = ((left * scale_factor)
                        / (self.inner_width - self.container_width))
                        .clamp(0.0, 1.0);
                    if let Some(callback) = &self.on_scroll {
                        (callback)(cx, self.scroll_x, self.scroll_y);
                    }

                    self.reset();
                }
            }

            WindowEvent::MouseScroll(x, y) => {
                cx.set_active(true);
                let (x, y) = if cx.modifiers.shift() { (-*y, -*x) } else { (-*x, -*y) };

                // What percentage of the negative space does this cross?
                if x != 0.0 && self.inner_width > self.container_width {
                    let negative_space = self.inner_width - self.container_width;
                    if negative_space != 0.0 {
                        let logical_delta = x * SCROLL_SENSITIVITY / negative_space;
                        cx.emit(ScrollEvent::ScrollX(logical_delta));
                    }
                    // Prevent event propagating to ancestor scrollviews.
                    meta.consume();
                }
                if y != 0.0 && self.inner_height > self.container_height {
                    let negative_space = self.inner_height - self.container_height;
                    if negative_space != 0.0 {
                        let logical_delta = y * SCROLL_SENSITIVITY / negative_space;
                        cx.emit(ScrollEvent::ScrollY(logical_delta));
                    }
                    // Prevent event propagating to ancestor scrollviews.
                    meta.consume();
                }
            }

            WindowEvent::MouseOut => {
                cx.set_active(false);
            }

            _ => {}
        });
    }
}

impl<'a> Handle<'a, ScrollView> {
    /// Sets a callback which will be called when a scrollview is scrolled, either with the mouse wheel, touchpad, or using the scroll bars.
    pub fn on_scroll(
        self,
        callback: impl Fn(&mut EventContext, f32, f32) + 'static + Send + Sync,
    ) -> Self {
        self.modify(|scrollview: &mut ScrollView| scrollview.on_scroll = Some(Arc::new(callback)))
    }

    pub fn scroll_to_cursor(self, scroll_to_cursor: bool) -> Self {
        self.modify(|scrollview: &mut ScrollView| scrollview.scroll_to_cursor = scroll_to_cursor)
    }

    pub fn scrollx(self, scrollx: impl Res<f32>) -> Self {
        self.bind(scrollx, |handle, scrollx| {
            let sx = scrollx.get(&handle);
            handle.modify(|scrollview| scrollview.scroll_x = sx);
        })
    }

    pub fn scrolly(self, scrollx: impl Res<f32>) -> Self {
        self.bind(scrollx, |handle, scrolly| {
            let sy = scrolly.get(&handle);
            handle.modify(|scrollview| scrollview.scroll_y = sy);
        })
    }
}

struct ScrollContent {}

impl ScrollContent {
    pub fn new(cx: &mut Context, content: impl FnOnce(&mut Context)) -> Handle<Self> {
        Self {}.build(cx, content)
    }
}

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

    fn event(&mut self, cx: &mut EventContext, event: &mut Event) {
        event.map(|window_event, _| match window_event {
            WindowEvent::GeometryChanged(geo) => {
                if geo.contains(GeoChanged::WIDTH_CHANGED)
                    || geo.contains(GeoChanged::HEIGHT_CHANGED)
                {
                    let bounds = cx.bounds();
                    // If the width or height have changed then send this back up to the ScrollData.
                    cx.emit(ScrollEvent::ChildGeo(bounds.w, bounds.h));
                }
            }

            _ => {}
        });
    }
}