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
use std::collections::HashSet;

use dioxus::prelude::{
    current_scope_id,
    schedule_update_any,
    use_drop,
    use_hook,
    Readable,
    ScopeId,
    Signal,
    Writable,
    WritableVecExt,
};

#[derive(Default, PartialEq, Eq)]
pub enum ScrollPosition {
    #[default]
    Start,
    End,
    // Specific
}

#[derive(Default, PartialEq, Eq)]
pub enum ScrollDirection {
    #[default]
    Vertical,
    Horizontal,
}

#[derive(Default)]
pub struct ScrollConfig {
    pub default_vertical_position: ScrollPosition,
    pub default_horizontal_position: ScrollPosition,
}

pub struct ScrollRequest {
    pub(crate) position: ScrollPosition,
    pub(crate) direction: ScrollDirection,
    pub(crate) init: bool,
    pub(crate) applied_by: HashSet<ScopeId>,
}

impl ScrollRequest {
    pub fn new(position: ScrollPosition, direction: ScrollDirection) -> ScrollRequest {
        ScrollRequest {
            position,
            direction,
            init: false,
            applied_by: HashSet::default(),
        }
    }
}

#[derive(PartialEq, Eq, Clone, Copy)]
pub struct ScrollController {
    requests_subscribers: Signal<HashSet<ScopeId>>,
    requests: Signal<Vec<ScrollRequest>>,
    x: Signal<i32>,
    y: Signal<i32>,
}

impl From<ScrollController> for (Signal<i32>, Signal<i32>) {
    fn from(val: ScrollController) -> Self {
        (val.x, val.y)
    }
}

impl ScrollController {
    pub fn new(x: i32, y: i32, initial_requests: Vec<ScrollRequest>) -> Self {
        Self {
            x: Signal::new(x),
            y: Signal::new(y),
            requests_subscribers: Signal::new(HashSet::new()),
            requests: Signal::new(initial_requests),
        }
    }

    pub fn use_apply(&mut self, width: f32, height: f32) {
        let scope_id = current_scope_id().unwrap();

        if !self.requests_subscribers.peek().contains(&scope_id) {
            self.requests_subscribers.write().insert(scope_id);
        }

        let mut requests_subscribers = self.requests_subscribers;
        use_drop(move || {
            requests_subscribers.write().remove(&scope_id);
        });

        self.requests.write().retain_mut(|request| {
            if request.applied_by.contains(&scope_id) {
                return true;
            }

            match request {
                ScrollRequest {
                    position: ScrollPosition::Start,
                    direction: ScrollDirection::Vertical,
                    ..
                } => {
                    *self.y.write() = 0;
                }
                ScrollRequest {
                    position: ScrollPosition::Start,
                    direction: ScrollDirection::Horizontal,
                    ..
                } => {
                    *self.x.write() = 0;
                }
                ScrollRequest {
                    position: ScrollPosition::End,
                    direction: ScrollDirection::Vertical,
                    init,
                    ..
                } => {
                    if *init && height == 0. {
                        return true;
                    }
                    *self.y.write() = -height as i32;
                }
                ScrollRequest {
                    position: ScrollPosition::End,
                    direction: ScrollDirection::Horizontal,
                    init,
                    ..
                } => {
                    if *init && width == 0. {
                        return true;
                    }
                    *self.x.write() = -width as i32;
                }
            }

            request.applied_by.insert(scope_id);

            *self.requests_subscribers.peek() != request.applied_by
        });
    }

    pub fn scroll_to_x(&mut self, to: i32) {
        self.x.set(to);
    }

    pub fn scroll_to_y(&mut self, to: i32) {
        self.y.set(to);
    }

    pub fn scroll_to(
        &mut self,
        scroll_position: ScrollPosition,
        scroll_direction: ScrollDirection,
    ) {
        self.requests
            .push(ScrollRequest::new(scroll_position, scroll_direction));
        let schedule = schedule_update_any();
        for scope_id in self.requests_subscribers.read().iter() {
            schedule(*scope_id);
        }
    }
}

pub fn use_scroll_controller(init: impl FnOnce() -> ScrollConfig) -> ScrollController {
    use_hook(|| {
        let config = init();
        ScrollController::new(
            0,
            0,
            vec![
                ScrollRequest {
                    position: config.default_vertical_position,
                    direction: ScrollDirection::Vertical,
                    init: true,
                    applied_by: HashSet::default(),
                },
                ScrollRequest {
                    position: config.default_horizontal_position,
                    direction: ScrollDirection::Horizontal,
                    init: true,
                    applied_by: HashSet::default(),
                },
            ],
        )
    })
}

#[cfg(test)]
mod test {
    use freya::prelude::*;
    use freya_testing::prelude::*;

    #[tokio::test]
    pub async fn controlled_scroll_view() {
        fn scroll_view_app() -> Element {
            let mut scroll_controller = use_scroll_controller(|| ScrollConfig {
                default_vertical_position: ScrollPosition::End,
                ..Default::default()
            });

            rsx!(
                ScrollView {
                    scroll_controller,
                    Button {
                        onclick: move |_| {
                            scroll_controller.scroll_to(ScrollPosition::End, ScrollDirection::Vertical);
                        },
                        label {
                            "Scroll Down"
                        }
                    }
                    rect {
                        height: "200",
                        width: "200",
                    },
                    rect {
                        height: "200",
                        width: "200",
                    },
                    rect {
                        height: "200",
                        width: "200",
                    }
                    rect {
                        height: "200",
                        width: "200",
                    }
                    Button {
                        onclick: move |_| {
                            scroll_controller.scroll_to(ScrollPosition::Start, ScrollDirection::Vertical);
                        },
                        label {
                            "Scroll up"
                        }
                    }
                }
            )
        }

        let mut utils = launch_test(scroll_view_app);
        let root = utils.root();
        let content = root.get(0).get(0).get(0);
        utils.wait_for_update().await;

        // Only the last three items are visible
        assert!(!content.get(1).is_visible());
        assert!(content.get(2).is_visible());
        assert!(content.get(3).is_visible());
        assert!(content.get(4).is_visible());

        // Click on the button to scroll up
        utils.push_event(PlatformEvent::Mouse {
            name: EventName::Click,
            cursor: (15., 480.).into(),
            button: Some(MouseButton::Left),
        });
        utils.wait_for_update().await;

        // Only the first three items are visible
        assert!(content.get(1).is_visible());
        assert!(content.get(2).is_visible());
        assert!(content.get(3).is_visible());
        assert!(!content.get(4).is_visible());

        // Click on the button to scroll down
        utils.push_event(PlatformEvent::Mouse {
            name: EventName::Click,
            cursor: (15., 15.).into(),
            button: Some(MouseButton::Left),
        });

        utils.wait_for_update().await;

        // Only the first three items are visible
        assert!(!content.get(1).is_visible());
        assert!(content.get(2).is_visible());
        assert!(content.get(3).is_visible());
        assert!(content.get(4).is_visible());
    }
}