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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
#![allow(clippy::type_complexity)]

use std::ops::Range;

use dioxus::prelude::*;
use freya_elements::{
    elements as dioxus_elements,
    events::{
        keyboard::Key,
        KeyboardEvent,
        MouseEvent,
        WheelEvent,
    },
};
use freya_hooks::{
    use_applied_theme,
    use_focus,
    use_node,
    ScrollBarThemeWith,
};

use crate::{
    get_container_size,
    get_corrected_scroll_position,
    get_scroll_position_from_cursor,
    get_scroll_position_from_wheel,
    get_scrollbar_pos_and_size,
    is_scrollbar_visible,
    manage_key_event,
    scroll_views::use_scroll_controller,
    Axis,
    ScrollBar,
    ScrollConfig,
    ScrollController,
    ScrollThumb,
    SCROLL_SPEED_MULTIPLIER,
};

/// Properties for the [`VirtualScrollView`] component.
#[derive(Props, Clone)]
pub struct VirtualScrollViewProps<
    Builder: 'static + Clone + Fn(usize, &Option<BuilderArgs>) -> Element,
    BuilderArgs: Clone + 'static + PartialEq = (),
> {
    /// Width of the VirtualScrollView container. Default to `fill`.
    #[props(default = "fill".into())]
    pub width: String,
    /// Height of the VirtualScrollView container. Default to `fill`.
    #[props(default = "fill".into())]
    pub height: String,
    /// Padding of the VirtualScrollView container.
    #[props(default = "0".to_string())]
    pub padding: String,
    /// Theme override for the scrollbars.
    pub scrollbar_theme: Option<ScrollBarThemeWith>,
    /// Quantity of items in the VirtualScrollView.
    pub length: usize,
    /// Size of the items, height for vertical direction and width for horizontal.
    pub item_size: f32,
    /// The item builder function.
    pub builder: Builder,
    /// The values for the item builder function.
    #[props(into)]
    pub builder_args: Option<BuilderArgs>,
    /// Direction of the VirtualScrollView, `vertical` or `horizontal`.
    #[props(default = "vertical".to_string(), into)]
    pub direction: String,
    /// Show the scrollbar, visible by default.
    #[props(default = true, into)]
    pub show_scrollbar: bool,
    /// Enable scrolling with arrow keys.
    #[props(default = true, into)]
    pub scroll_with_arrows: bool,
    /// Cache elements or not, changing `builder_args` will invalidate the cache if enabled.
    /// Default is `true`.
    #[props(default = true, into)]
    pub cache_elements: bool,
    /// Custom Scroll Controller for the Virtual ScrollView.
    pub scroll_controller: Option<ScrollController>,
    /// If `false` (default), wheel scroll with no shift will scroll vertically no matter the direction.
    /// If `true`, wheel scroll with no shift will scroll horizontally.
    #[props(default = false)]
    pub invert_scroll_wheel: bool,
}

impl<
        BuilderArgs: Clone + PartialEq,
        Builder: Clone + Fn(usize, &Option<BuilderArgs>) -> Element,
    > PartialEq for VirtualScrollViewProps<Builder, BuilderArgs>
{
    fn eq(&self, other: &Self) -> bool {
        self.width == other.width
            && self.height == other.height
            && self.padding == other.padding
            && self.length == other.length
            && self.item_size == other.item_size
            && self.direction == other.direction
            && self.show_scrollbar == other.show_scrollbar
            && self.scroll_with_arrows == other.scroll_with_arrows
            && self.builder_args == other.builder_args
            && self.scroll_controller == other.scroll_controller
            && self.invert_scroll_wheel == other.invert_scroll_wheel
    }
}

fn get_render_range(
    viewport_size: f32,
    scroll_position: f32,
    item_size: f32,
    item_length: f32,
) -> Range<usize> {
    let render_index_start = (-scroll_position) / item_size;
    let potentially_visible_length = (viewport_size / item_size) + 1.0;
    let remaining_length = item_length - render_index_start;

    let render_index_end = if remaining_length <= potentially_visible_length {
        item_length
    } else {
        render_index_start + potentially_visible_length
    };

    render_index_start as usize..(render_index_end as usize)
}

/// One-direction scrollable area that dynamically builds and renders items based in their size and current available size,
/// this is intended for apps using large sets of data that need good performance.
///
/// Use cases: text editors, chats, etc.
///
/// # Example
///
/// ```no_run
/// # use freya::prelude::*;
/// # use std::rc::Rc;
/// fn app() -> Element {
///     rsx!(VirtualScrollView {
///         length: 5,
///         item_size: 80.0,
///         direction: "vertical",
///         builder: move |i, _other_args: &Option<()>| {
///             rsx! {
///                 label {
///                     key: "{i}",
///                     height: "80",
///                     "Number {i}"
///                 }
///             }
///         }
///     })
/// }
/// ```
///
/// # With a Scroll Controller
///
/// ```no_run
/// # use freya::prelude::*;
/// # use std::rc::Rc;
/// fn app() -> Element {
///     let mut scroll_controller = use_scroll_controller(|| ScrollConfig::default());
///
///     rsx!(VirtualScrollView {
///         scroll_controller,
///         length: 5,
///         item_size: 80.0,
///         direction: "vertical",
///         builder: move |i, _other_args: &Option<()>| {
///             rsx! {
///                 label {
///                     key: "{i}",
///                     height: "80",
///                     onclick: move |_| {
///                          scroll_controller.scroll_to(ScrollPosition::Start, ScrollDirection::Vertical);
///                     },
///                     "Number {i}"
///                 }
///             }
///         }
///     })
/// }
/// ```
#[allow(non_snake_case)]
pub fn VirtualScrollView<
    Builder: Clone + Fn(usize, &Option<BuilderArgs>) -> Element,
    BuilderArgs: Clone + PartialEq,
>(
    VirtualScrollViewProps {
        width,
        height,
        padding,
        scrollbar_theme,
        length,
        item_size,
        builder,
        builder_args,
        direction,
        show_scrollbar,
        scroll_with_arrows,
        cache_elements,
        scroll_controller,
        invert_scroll_wheel,
    }: VirtualScrollViewProps<Builder, BuilderArgs>,
) -> Element {
    let mut clicking_scrollbar = use_signal::<Option<(Axis, f64)>>(|| None);
    let mut clicking_shift = use_signal(|| false);
    let mut clicking_alt = use_signal(|| false);
    let mut scroll_controller =
        scroll_controller.unwrap_or_else(|| use_scroll_controller(ScrollConfig::default));
    let (mut scrolled_x, mut scrolled_y) = scroll_controller.into();
    let (node_ref, size) = use_node();
    let mut focus = use_focus();
    let applied_scrollbar_theme = use_applied_theme!(&scrollbar_theme, scroll_bar);

    let direction_is_vertical = direction == "vertical";

    let inner_size = item_size + (item_size * length as f32);

    scroll_controller.use_apply(inner_size, inner_size);

    let vertical_scrollbar_is_visible = direction != "horizontal"
        && is_scrollbar_visible(show_scrollbar, inner_size, size.area.height());
    let horizontal_scrollbar_is_visible = direction != "vertical"
        && is_scrollbar_visible(show_scrollbar, inner_size, size.area.width());

    let (container_width, content_width) = get_container_size(
        &width,
        direction_is_vertical,
        Axis::X,
        vertical_scrollbar_is_visible,
        &applied_scrollbar_theme.size,
    );
    let (container_height, content_height) = get_container_size(
        &height,
        direction_is_vertical,
        Axis::Y,
        horizontal_scrollbar_is_visible,
        &applied_scrollbar_theme.size,
    );

    let corrected_scrolled_y =
        get_corrected_scroll_position(inner_size, size.area.height(), *scrolled_y.read() as f32);
    let corrected_scrolled_x =
        get_corrected_scroll_position(inner_size, size.area.width(), *scrolled_x.read() as f32);

    let (scrollbar_y, scrollbar_height) =
        get_scrollbar_pos_and_size(inner_size, size.area.height(), corrected_scrolled_y);
    let (scrollbar_x, scrollbar_width) =
        get_scrollbar_pos_and_size(inner_size, size.area.width(), corrected_scrolled_x);

    // Moves the Y axis when the user scrolls in the container
    let onwheel = move |e: WheelEvent| {
        let speed_multiplier = if *clicking_alt.peek() {
            SCROLL_SPEED_MULTIPLIER
        } else {
            1.0
        };

        let wheel_movement = e.get_delta_y() as f32 * speed_multiplier;

        let scroll_vertically_or_not =
            (invert_scroll_wheel && clicking_shift()) || !invert_scroll_wheel && !clicking_shift();

        if scroll_vertically_or_not {
            let scroll_position_y = get_scroll_position_from_wheel(
                wheel_movement,
                inner_size,
                size.area.height(),
                corrected_scrolled_y,
            );

            // Only scroll when there is still area to scroll
            if *scrolled_y.peek() != scroll_position_y {
                e.stop_propagation();
                *scrolled_y.write() = scroll_position_y;
            } else {
                return;
            }
        } else {
            let scroll_position_x = get_scroll_position_from_wheel(
                wheel_movement,
                inner_size,
                size.area.width(),
                corrected_scrolled_x,
            );

            // Only scroll when there is still area to scroll
            if *scrolled_x.peek() != scroll_position_x {
                e.stop_propagation();
                *scrolled_x.write() = scroll_position_x;
            } else {
                return;
            }
        }

        focus.focus();
    };

    // Drag the scrollbars
    let onmousemove = move |e: MouseEvent| {
        let clicking_scrollbar = clicking_scrollbar.peek();

        if let Some((Axis::Y, y)) = *clicking_scrollbar {
            let coordinates = e.get_element_coordinates();
            let cursor_y = coordinates.y - y - size.area.min_y() as f64;

            let scroll_position =
                get_scroll_position_from_cursor(cursor_y as f32, inner_size, size.area.height());

            *scrolled_y.write() = scroll_position;
        } else if let Some((Axis::X, x)) = *clicking_scrollbar {
            let coordinates = e.get_element_coordinates();
            let cursor_x = coordinates.x - x - size.area.min_x() as f64;

            let scroll_position =
                get_scroll_position_from_cursor(cursor_x as f32, inner_size, size.area.width());

            *scrolled_x.write() = scroll_position;
        }

        if clicking_scrollbar.is_some() {
            focus.focus();
        }
    };

    let onglobalkeydown = move |e: KeyboardEvent| {
        match &e.key {
            Key::Shift => {
                clicking_shift.set(true);
            }
            Key::Alt => {
                clicking_alt.set(true);
            }
            k => {
                if !focus.is_focused() {
                    return;
                }

                if !scroll_with_arrows
                    && (k == &Key::ArrowUp
                        || k == &Key::ArrowRight
                        || k == &Key::ArrowDown
                        || k == &Key::ArrowLeft)
                {
                    return;
                }

                let x = corrected_scrolled_x;
                let y = corrected_scrolled_y;
                let inner_height = inner_size;
                let inner_width = inner_size;
                let viewport_height = size.area.height();
                let viewport_width = size.area.width();

                let (x, y) = manage_key_event(
                    e,
                    (x, y),
                    inner_height,
                    inner_width,
                    viewport_height,
                    viewport_width,
                );

                scrolled_x.set(x as i32);
                scrolled_y.set(y as i32);
            }
        };
    };

    let onglobalkeyup = move |e: KeyboardEvent| {
        if e.key == Key::Shift {
            clicking_shift.set(false);
        } else if e.key == Key::Alt {
            clicking_alt.set(false);
        }
    };

    // Mark the Y axis scrollbar as the one being dragged
    let onmousedown_y = move |e: MouseEvent| {
        let coordinates = e.get_element_coordinates();
        *clicking_scrollbar.write() = Some((Axis::Y, coordinates.y));
    };

    // Mark the X axis scrollbar as the one being dragged
    let onmousedown_x = move |e: MouseEvent| {
        let coordinates = e.get_element_coordinates();
        *clicking_scrollbar.write() = Some((Axis::X, coordinates.x));
    };

    // Unmark any scrollbar
    let onclick = move |_: MouseEvent| {
        if clicking_scrollbar.peek().is_some() {
            *clicking_scrollbar.write() = None;
        }
    };

    let horizontal_scrollbar_size = if horizontal_scrollbar_is_visible {
        &applied_scrollbar_theme.size
    } else {
        "0"
    };

    let vertical_scrollbar_size = if vertical_scrollbar_is_visible {
        &applied_scrollbar_theme.size
    } else {
        "0"
    };

    let (viewport_size, scroll_position) = if direction == "vertical" {
        (size.area.height(), corrected_scrolled_y)
    } else {
        (size.area.width(), corrected_scrolled_x)
    };

    // Calculate from what to what items must be rendered
    let render_range = get_render_range(viewport_size, scroll_position, item_size, length as f32);

    let children = if cache_elements {
        let children = use_memo(use_reactive(
            &(render_range, builder_args),
            move |(render_range, builder_args)| {
                render_range
                    .clone()
                    .map(|i| (builder)(i, &builder_args))
                    .collect::<Vec<Element>>()
            },
        ));
        rsx!({ children.read().iter() })
    } else {
        let children = render_range.map(|i| (builder)(i, &builder_args));
        rsx!({ children })
    };

    let is_scrolling_x = clicking_scrollbar
        .read()
        .as_ref()
        .map(|f| f.0 == Axis::X)
        .unwrap_or_default();
    let is_scrolling_y = clicking_scrollbar
        .read()
        .as_ref()
        .map(|f| f.0 == Axis::Y)
        .unwrap_or_default();

    let offset_y_min = (-corrected_scrolled_y / item_size).floor() * item_size;
    let offset_y = -corrected_scrolled_y - offset_y_min;

    let a11y_id = focus.attribute();

    rsx!(
        rect {
            a11y_role:"scrollView",
            overflow: "clip",
            direction: "horizontal",
            width: "{width}",
            height: "{height}",
            onglobalclick: onclick,
            onglobalmousemove: onmousemove,
            onglobalkeydown,
            onglobalkeyup,
            a11y_id,
            rect {
                direction: "vertical",
                width: "{container_width}",
                height: "{container_height}",
                rect {
                    overflow: "clip",
                    padding: "{padding}",
                    height: "{content_height}",
                    width: "{content_width}",
                    direction: "{direction}",
                    offset_y: "{-offset_y}",
                    reference: node_ref,
                    onwheel: onwheel,
                    {children}
                }
                ScrollBar {
                    width: "100%",
                    height: "{horizontal_scrollbar_size}",
                    offset_x: "{scrollbar_x}",
                    clicking_scrollbar: is_scrolling_x,
                    theme: scrollbar_theme.clone(),
                    ScrollThumb {
                        clicking_scrollbar: is_scrolling_x,
                        onmousedown: onmousedown_x,
                        width: "{scrollbar_width}",
                        height: "100%",
                        theme: scrollbar_theme.clone(),
                    }
                }
            }
            ScrollBar {
                width: "{vertical_scrollbar_size}",
                height: "100%",
                offset_y: "{scrollbar_y}",
                clicking_scrollbar: is_scrolling_y,
                theme: scrollbar_theme.clone(),
                ScrollThumb {
                    clicking_scrollbar: is_scrolling_y,
                    onmousedown: onmousedown_y,
                    width: "100%",
                    height: "{scrollbar_height}",
                    theme: scrollbar_theme,
                }
            }
        }
    )
}

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

    #[tokio::test]
    pub async fn virtual_scroll_view_wheel() {
        fn virtual_scroll_view_wheel_app() -> Element {
            let values = use_signal(|| ["Hello, World!"].repeat(30));

            rsx!(VirtualScrollView {
                length: values.read().len(),
                item_size: 50.0,
                direction: "vertical",
                builder: move |index, _: &Option<()>| {
                    let value = values.read()[index];
                    rsx! {
                        label {
                            key: "{index}",
                            height: "50",
                            "{index} {value}"
                        }
                    }
                }
            })
        }

        let mut utils = launch_test(virtual_scroll_view_wheel_app);
        let root = utils.root();

        utils.wait_for_update().await;
        utils.wait_for_update().await;

        let content = root.get(0).get(0).get(0);
        assert_eq!(content.children_ids().len(), 11);

        // Check that visible items are from indexes 0 to 11, because 500 / 50 = 10 + 1 (for smooth scrolling) = 11.
        for (n, i) in (0..11).enumerate() {
            let child = content.get(n);
            assert_eq!(
                child.get(0).text(),
                Some(format!("{i} Hello, World!").as_str())
            );
        }

        utils.push_event(PlatformEvent::Wheel {
            name: EventName::Wheel,
            scroll: (0., -300.).into(),
            cursor: (5., 5.).into(),
        });

        utils.wait_for_update().await;
        utils.wait_for_update().await;

        let content = root.get(0).get(0).get(0);
        assert_eq!(content.children_ids().len(), 11);

        // It has scrolled 300 pixels, which equals to 6 items since because 300 / 50 = 6
        // So we must start checking from 6 to +10, 16 in this case because 6 + 10 = 16 + 1 (for smooths scrolling) = 17.
        for (n, i) in (6..17).enumerate() {
            let child = content.get(n);
            assert_eq!(
                child.get(0).text(),
                Some(format!("{i} Hello, World!").as_str())
            );
        }
    }

    #[tokio::test]
    pub async fn virtual_scroll_view_scrollbar() {
        fn virtual_scroll_view_scrollar_app() -> Element {
            let values = use_signal(|| ["Hello, World!"].repeat(30));

            rsx!(VirtualScrollView {
                length: values.read().len(),
                item_size: 50.0,
                direction: "vertical",
                builder: move |index, _: &Option<()>| {
                    let value = values.read()[index];
                    rsx! {
                        label {
                            key: "{index}",
                            height: "50",
                            "{index} {value}"
                        }
                    }
                }
            })
        }

        let mut utils = launch_test(virtual_scroll_view_scrollar_app);
        let root = utils.root();

        utils.wait_for_update().await;
        utils.wait_for_update().await;
        utils.wait_for_update().await;

        let content = root.get(0).get(0).get(0);
        assert_eq!(content.children_ids().len(), 11);

        // Check that visible items are from indexes 0 to 10, because 500 / 50 = 10 + 1 (for smooth scrolling) = 11.
        for (n, i) in (0..11).enumerate() {
            let child = content.get(n);
            assert_eq!(
                child.get(0).text(),
                Some(format!("{i} Hello, World!").as_str())
            );
        }

        // Simulate the user dragging the scrollbar
        utils.push_event(PlatformEvent::Mouse {
            name: EventName::MouseMove,
            cursor: (490., 20.).into(),
            button: Some(MouseButton::Left),
        });
        utils.push_event(PlatformEvent::Mouse {
            name: EventName::MouseDown,
            cursor: (490., 20.).into(),
            button: Some(MouseButton::Left),
        });
        utils.push_event(PlatformEvent::Mouse {
            name: EventName::MouseMove,
            cursor: (490., 320.).into(),
            button: Some(MouseButton::Left),
        });
        utils.push_event(PlatformEvent::Mouse {
            name: EventName::MouseUp,
            cursor: (490., 320.).into(),
            button: Some(MouseButton::Left),
        });

        utils.wait_for_update().await;
        utils.wait_for_update().await;

        let content = root.get(0).get(0).get(0);
        assert_eq!(content.children_ids().len(), 11);

        // It has dragged the scrollbar 300 pixels
        for (n, i) in (18..29).enumerate() {
            let child = content.get(n);
            assert_eq!(
                child.get(0).text(),
                Some(format!("{i} Hello, World!").as_str())
            );
        }

        // Scroll up with arrows
        for _ in 0..11 {
            utils.push_event(PlatformEvent::Keyboard {
                name: EventName::KeyDown,
                key: Key::ArrowUp,
                code: Code::ArrowUp,
                modifiers: Modifiers::default(),
            });
            utils.wait_for_update().await;
        }

        let content = root.get(0).get(0).get(0);
        assert_eq!(content.children_ids().len(), 11);

        for (n, i) in (0..11).enumerate() {
            let child = content.get(n);
            assert_eq!(
                child.get(0).text(),
                Some(format!("{i} Hello, World!").as_str())
            );
        }

        // Scroll to the bottom with arrows
        utils.push_event(PlatformEvent::Keyboard {
            name: EventName::KeyDown,
            key: Key::End,
            code: Code::End,
            modifiers: Modifiers::default(),
        });
        utils.wait_for_update().await;
        utils.wait_for_update().await;

        let content = root.get(0).get(0).get(0);
        assert_eq!(content.children_ids().len(), 9);

        for (n, i) in (21..30).enumerate() {
            let child = content.get(n);
            assert_eq!(
                child.get(0).text(),
                Some(format!("{i} Hello, World!").as_str())
            );
        }
    }
}