Skip to main content

freya_components/scrollviews/
virtual_scrollview.rs

1use std::{
2    ops::Range,
3    time::Duration,
4};
5
6use freya_core::prelude::*;
7use freya_sdk::timeout::use_timeout;
8use torin::{
9    geometry::{
10        CursorPoint,
11        Point2D,
12        Size2D,
13    },
14    node::Node,
15    prelude::Direction,
16    size::Size,
17};
18
19use crate::scrollviews::{
20    ScrollBar,
21    ScrollBarContext,
22    ScrollBarThumbEvents,
23    ScrollConfig,
24    ScrollController,
25    shared::{
26        Axis,
27        get_container_sizes,
28        get_corrected_scroll_position,
29        get_scroll_position_from_cursor,
30        get_scroll_position_from_wheel,
31        get_scrollbar_pos_and_size,
32        handle_key_event,
33        is_scrollbar_visible,
34    },
35    use_scroll_controller,
36};
37
38/// Defines how each item of a [`VirtualScrollView`] is sized along the scroll axis.
39///
40/// Build one from a fixed value or from a closure that resolves the size of each
41/// item by its index:
42///
43/// ```rust
44/// # use freya::prelude::*;
45/// let fixed: ItemSize = 25.0f32.into();
46/// let dynamic: ItemSize =
47///     (|index: usize| if index.is_multiple_of(2) { 25.0 } else { 50.0 }).into();
48/// ```
49#[derive(Clone, PartialEq)]
50pub enum ItemSize {
51    /// Every item shares the same size in pixels.
52    Fixed(f32),
53    /// Each item is sized individually through a callback that receives its index.
54    Dynamic(Callback<usize, f32>),
55}
56
57impl ItemSize {
58    /// Size in pixels of the item at `index`.
59    fn at(&self, index: usize) -> f32 {
60        match self {
61            Self::Fixed(size) => *size,
62            Self::Dynamic(callback) => callback.call(index),
63        }
64    }
65
66    /// Range of items that fall inside the viewport for the given scroll position,
67    /// together with the offset that positions the first visible item correctly.
68    fn visible_range(
69        &self,
70        viewport_size: f32,
71        scroll_position: f32,
72        length: usize,
73    ) -> (Range<usize>, f32) {
74        let scroll_distance = (-scroll_position).max(0.0);
75        match self {
76            Self::Fixed(size) => {
77                if *size <= 0.0 {
78                    return (0..0, 0.0);
79                }
80                let start = scroll_distance / size;
81                let potentially_visible = (viewport_size / size) + 1.0;
82                let start_index = (start as usize).min(length);
83                let end_index = ((start + potentially_visible) as usize).min(length);
84                (
85                    start_index..end_index,
86                    start.floor() * size - scroll_distance,
87                )
88            }
89            Self::Dynamic(callback) => {
90                let mut start = 0;
91                let mut cumulative = 0.0;
92                while start < length {
93                    let item = callback.call(start);
94                    if cumulative + item > scroll_distance {
95                        break;
96                    }
97                    cumulative += item;
98                    start += 1;
99                }
100                let offset = cumulative - scroll_distance;
101                let mut end = start;
102                while end < length && cumulative < scroll_distance + viewport_size {
103                    cumulative += callback.call(end);
104                    end += 1;
105                }
106                (start..end, offset)
107            }
108        }
109    }
110
111    /// Total size of the content along the scroll axis.
112    ///
113    /// [`Self::Fixed`] is exact. [`Self::Dynamic`] extrapolates from the average size of
114    /// the items down to the viewport bottom, keeping the scrollbar stable as it scrolls.
115    fn total_size(&self, viewport_size: f32, scroll_position: f32, length: usize) -> f32 {
116        match self {
117            Self::Fixed(size) => size * length as f32,
118            Self::Dynamic(callback) => {
119                if length == 0 {
120                    return 0.0;
121                }
122                let viewport_bottom = (-scroll_position).max(0.0) + viewport_size;
123                let mut measured = callback.call(0);
124                let mut count = 1;
125                while count < length && measured < viewport_bottom {
126                    measured += callback.call(count);
127                    count += 1;
128                }
129                (measured / count as f32) * length as f32
130            }
131        }
132    }
133}
134
135impl Default for ItemSize {
136    fn default() -> Self {
137        Self::Fixed(0.)
138    }
139}
140
141impl From<f32> for ItemSize {
142    fn from(size: f32) -> Self {
143        Self::Fixed(size)
144    }
145}
146
147impl<F: Fn(usize) -> f32 + 'static> From<F> for ItemSize {
148    fn from(callback: F) -> Self {
149        Self::Dynamic(Callback::new(callback))
150    }
151}
152
153/// Data passed to a [`VirtualScrollView`] builder for each rendered item.
154#[derive(Debug, Clone, Copy, PartialEq)]
155pub struct VirtualItem {
156    pub index: usize,
157    pub size: f32,
158}
159
160/// One-direction scrollable area that dynamically builds and renders items based in their size and current available size,
161/// this is intended for apps using large sets of data that need good performance.
162///
163/// Unlike [`ScrollView`](crate::scrollviews::ScrollView), which lays out every child even when it is
164/// off screen, a `VirtualScrollView` takes a builder closure and only calls it for the items that
165/// are actually visible, so the cost stays roughly constant no matter how long the list is.
166///
167/// It needs two things to know which items fall inside the viewport:
168/// [`item_size`](VirtualScrollView::item_size), the fixed size of each item along the scroll axis,
169/// and [`length`](VirtualScrollView::length), the total number of items.
170///
171/// # Example
172///
173/// ```rust
174/// # use freya::prelude::*;
175/// fn app() -> impl IntoElement {
176///     rect().child(
177///         VirtualScrollView::new(|item, _| {
178///             rect()
179///                 .key(item.index)
180///                 .height(Size::px(item.size))
181///                 .padding(4.)
182///                 .child(format!("Item {}", item.index))
183///                 .into()
184///         })
185///         .length(300usize)
186///         .item_size(25.),
187///     )
188/// }
189/// ```
190///
191/// See the [interactive components demo](https://freyaui.dev/demo).
192#[derive(Clone)]
193pub struct VirtualScrollView<D, B: Fn(VirtualItem, &D) -> Element> {
194    builder: B,
195    builder_data: D,
196    item_size: ItemSize,
197    length: usize,
198    layout: LayoutData,
199    show_scrollbar: bool,
200    auto_hide_scrollbars: bool,
201    scroll_with_arrows: bool,
202    scroll_controller: Option<ScrollController>,
203    follows_scroll_controller: bool,
204    on_sized: Option<EventHandler<Event<SizedEventData>>>,
205    invert_scroll_wheel: bool,
206    drag_scrolling: bool,
207    scrollbar: Callback<ScrollBarContext, Element>,
208    key: DiffKey,
209}
210
211impl<D: PartialEq, B: Fn(VirtualItem, &D) -> Element> LayoutExt for VirtualScrollView<D, B> {
212    fn layout_mut(&mut self) -> &mut LayoutData {
213        &mut self.layout
214    }
215}
216
217impl<D: PartialEq, B: Fn(VirtualItem, &D) -> Element> ContainerSizeExt for VirtualScrollView<D, B> {}
218
219impl<D: PartialEq, B: Fn(VirtualItem, &D) -> Element> KeyExt for VirtualScrollView<D, B> {
220    fn key_mut(&mut self) -> &mut DiffKey {
221        &mut self.key
222    }
223}
224
225impl<D: PartialEq, B: Fn(VirtualItem, &D) -> Element> PartialEq for VirtualScrollView<D, B> {
226    fn eq(&self, other: &Self) -> bool {
227        self.builder_data == other.builder_data
228            && self.item_size == other.item_size
229            && self.length == other.length
230            && self.layout == other.layout
231            && self.show_scrollbar == other.show_scrollbar
232            && self.auto_hide_scrollbars == other.auto_hide_scrollbars
233            && self.scroll_with_arrows == other.scroll_with_arrows
234            && self.scroll_controller == other.scroll_controller
235            && self.follows_scroll_controller == other.follows_scroll_controller
236            && self.invert_scroll_wheel == other.invert_scroll_wheel
237            && self.scrollbar == other.scrollbar
238    }
239}
240
241impl<B: Fn(VirtualItem, &()) -> Element> VirtualScrollView<(), B> {
242    /// Creates a virtual scroll view that builds each item on demand from its [`VirtualItem`].
243    pub fn new(builder: B) -> Self {
244        Self {
245            builder,
246            builder_data: (),
247            item_size: ItemSize::default(),
248            length: 0,
249            layout: {
250                let mut l = LayoutData::default();
251                l.layout.width = Size::fill();
252                l.layout.height = Size::fill();
253                l
254            },
255            show_scrollbar: true,
256            auto_hide_scrollbars: true,
257            scroll_with_arrows: true,
258            scroll_controller: None,
259            follows_scroll_controller: false,
260            on_sized: None,
261            invert_scroll_wheel: false,
262            drag_scrolling: true,
263            scrollbar: ScrollBar::default_renderer(),
264            key: DiffKey::None,
265        }
266    }
267
268    /// Like [`new`](Self::new) but driven by the given [`ScrollController`].
269    pub fn new_controlled(builder: B, scroll_controller: ScrollController) -> Self {
270        Self {
271            builder,
272            builder_data: (),
273            item_size: ItemSize::default(),
274            length: 0,
275            layout: {
276                let mut l = LayoutData::default();
277                l.layout.width = Size::fill();
278                l.layout.height = Size::fill();
279                l
280            },
281            show_scrollbar: true,
282            auto_hide_scrollbars: true,
283            scroll_with_arrows: true,
284            scroll_controller: Some(scroll_controller),
285            follows_scroll_controller: false,
286            on_sized: None,
287            invert_scroll_wheel: false,
288            drag_scrolling: true,
289            scrollbar: ScrollBar::default_renderer(),
290            key: DiffKey::None,
291        }
292    }
293}
294
295impl<D, B: Fn(VirtualItem, &D) -> Element> VirtualScrollView<D, B> {
296    /// Like [`new`](Self::new) but passes shared `builder_data` to every item build.
297    ///
298    /// The builder closure cannot be compared across renders, so data captured inside it never
299    /// triggers a rebuild. Passing the data here instead makes it part of the view's `PartialEq`,
300    /// so the visible items are rebuilt whenever it changes.
301    ///
302    /// ```rust
303    /// # use freya::prelude::*;
304    /// fn app() -> impl IntoElement {
305    ///     let items = use_state(|| vec!["a".to_string(), "b".to_string(), "c".to_string()]);
306    ///
307    ///     // The current items are passed as data, so editing `items` rebuilds the visible rows.
308    ///     VirtualScrollView::new_with_data(items.read().clone(), |item, items: &Vec<String>| {
309    ///         rect()
310    ///             .key(item.index)
311    ///             .height(Size::px(item.size))
312    ///             .child(items[item.index].clone())
313    ///             .into()
314    ///     })
315    ///     .length(items.read().len())
316    ///     .item_size(25.)
317    /// }
318    /// ```
319    pub fn new_with_data(builder_data: D, builder: B) -> Self {
320        Self {
321            builder,
322            builder_data,
323            item_size: ItemSize::default(),
324            length: 0,
325            layout: Node {
326                width: Size::fill(),
327                height: Size::fill(),
328                ..Default::default()
329            }
330            .into(),
331            show_scrollbar: true,
332            auto_hide_scrollbars: true,
333            scroll_with_arrows: true,
334            scroll_controller: None,
335            follows_scroll_controller: false,
336            on_sized: None,
337            invert_scroll_wheel: false,
338            drag_scrolling: true,
339            scrollbar: ScrollBar::default_renderer(),
340            key: DiffKey::None,
341        }
342    }
343
344    /// Like [`new_with_data`](Self::new_with_data) but driven by the given [`ScrollController`].
345    pub fn new_with_data_controlled(
346        builder_data: D,
347        builder: B,
348        scroll_controller: ScrollController,
349    ) -> Self {
350        Self {
351            builder,
352            builder_data,
353            item_size: ItemSize::default(),
354            length: 0,
355
356            layout: Node {
357                width: Size::fill(),
358                height: Size::fill(),
359                ..Default::default()
360            }
361            .into(),
362            show_scrollbar: true,
363            auto_hide_scrollbars: true,
364            scroll_with_arrows: true,
365            scroll_controller: Some(scroll_controller),
366            follows_scroll_controller: false,
367            on_sized: None,
368            invert_scroll_wheel: false,
369            drag_scrolling: true,
370            scrollbar: ScrollBar::default_renderer(),
371            key: DiffKey::None,
372        }
373    }
374
375    /// Toggles whether the scrollbar is shown when the content overflows.
376    pub fn show_scrollbar(mut self, show_scrollbar: bool) -> Self {
377        self.show_scrollbar = show_scrollbar;
378        self
379    }
380
381    /// Toggles hiding idle scrollbars, enabled by default.
382    /// When disabled, scrollbars remain visible while the content overflows.
383    pub fn auto_hide_scrollbars(mut self, auto_hide_scrollbars: bool) -> Self {
384        self.auto_hide_scrollbars = auto_hide_scrollbars;
385        self
386    }
387
388    /// Sets the axis the items flow and scroll in.
389    pub fn direction(mut self, direction: Direction) -> Self {
390        self.layout.direction = direction;
391        self
392    }
393
394    /// Toggles whether the arrow keys scroll the view while it is focused.
395    pub fn scroll_with_arrows(mut self, scroll_with_arrows: impl Into<bool>) -> Self {
396        self.scroll_with_arrows = scroll_with_arrows.into();
397        self
398    }
399
400    /// Sets the size of the items along the scroll axis, used to decide which items to render.
401    ///
402    /// Accepts an [`ItemSize`], so it can be a fixed size for every item or a closure that
403    /// resolves the size of each item by its index.
404    pub fn item_size(mut self, item_size: impl Into<ItemSize>) -> Self {
405        self.item_size = item_size.into();
406        self
407    }
408
409    /// Sets the total number of items the view can scroll through.
410    pub fn length(mut self, length: impl Into<usize>) -> Self {
411        self.length = length.into();
412        self
413    }
414
415    /// Inverts the direction of the mouse wheel relative to the content.
416    pub fn invert_scroll_wheel(mut self, invert_scroll_wheel: impl Into<bool>) -> Self {
417        self.invert_scroll_wheel = invert_scroll_wheel.into();
418        self
419    }
420
421    /// Toggles scrolling by dragging the content, useful mainly for touch input.
422    pub fn drag_scrolling(mut self, drag_scrolling: bool) -> Self {
423        self.drag_scrolling = drag_scrolling;
424        self
425    }
426
427    /// Sets the renderer used for each visible scrollbar.
428    pub fn scrollbar(mut self, scrollbar: impl Into<Callback<ScrollBarContext, Element>>) -> Self {
429        self.scrollbar = scrollbar.into();
430        self
431    }
432
433    /// Attaches a [`ScrollController`] to drive this view externally.
434    pub fn scroll_controller(
435        mut self,
436        scroll_controller: impl Into<Option<ScrollController>>,
437    ) -> Self {
438        self.scroll_controller = scroll_controller.into();
439        self.follows_scroll_controller = false;
440        self
441    }
442
443    /// Attaches a controller without updating its bounds from this view's layout.
444    pub fn follow_scroll_controller(mut self, scroll_controller: ScrollController) -> Self {
445        self.scroll_controller = Some(scroll_controller);
446        self.follows_scroll_controller = true;
447        self
448    }
449
450    /// Runs the handler with the size of the visible area, which excludes the scrollbars.
451    pub fn on_sized(mut self, on_sized: impl Into<EventHandler<Event<SizedEventData>>>) -> Self {
452        self.on_sized = Some(on_sized.into());
453        self
454    }
455
456    /// Sets the minimum width the scroll view can shrink to.
457    pub fn min_width(mut self, min_width: impl Into<Size>) -> Self {
458        self.layout.minimum_width = min_width.into();
459        self
460    }
461
462    /// Sets the minimum height the scroll view can shrink to.
463    pub fn min_height(mut self, min_height: impl Into<Size>) -> Self {
464        self.layout.minimum_height = min_height.into();
465        self
466    }
467
468    /// Caps the width of the scroll view.
469    pub fn max_width(mut self, max_width: impl Into<Size>) -> Self {
470        self.layout.maximum_width = max_width.into();
471        self
472    }
473
474    /// Caps the height of the scroll view.
475    pub fn max_height(mut self, max_height: impl Into<Size>) -> Self {
476        self.layout.maximum_height = max_height.into();
477        self
478    }
479}
480
481impl<D: PartialEq + 'static, B: Fn(VirtualItem, &D) -> Element + 'static> Component
482    for VirtualScrollView<D, B>
483{
484    fn render(self: &VirtualScrollView<D, B>) -> impl IntoElement {
485        let a11y_id = use_a11y();
486        let mut timeout = use_timeout(|| Duration::from_millis(800));
487        let mut pressing_shift = use_state(|| false);
488        let mut clicking_scrollbar = use_state::<Option<(Axis, f64)>>(|| None);
489        let mut size = use_state(SizedEventData::default);
490        let mut scroll_controller = self
491            .scroll_controller
492            .unwrap_or_else(|| use_scroll_controller(ScrollConfig::default));
493        let mut dragging_content = use_state::<Option<CursorPoint>>(|| None);
494        let mut drag_origin = use_state::<Option<CursorPoint>>(|| None);
495        let (scrolled_x, scrolled_y) = scroll_controller.into();
496        let layout = &self.layout.layout;
497        let direction = layout.direction;
498        let drag_scrolling = self.drag_scrolling;
499
500        let viewport_width = size.read().area.width();
501        let viewport_height = size.read().area.height();
502
503        let (inner_width, inner_height) = match direction {
504            Direction::Vertical => (
505                size.read().inner_sizes.width,
506                self.item_size
507                    .total_size(viewport_height, scrolled_y as f32, self.length),
508            ),
509            Direction::Horizontal => (
510                self.item_size
511                    .total_size(viewport_width, scrolled_x as f32, self.length),
512                size.read().inner_sizes.height,
513            ),
514        };
515
516        let corrected_scrolled_x =
517            get_corrected_scroll_position(inner_width, size.read().area.width(), scrolled_x as f32);
518
519        let corrected_scrolled_y = get_corrected_scroll_position(
520            inner_height,
521            size.read().area.height(),
522            scrolled_y as f32,
523        );
524
525        let smooth_position = scroll_controller
526            .animated_position(Point2D::new(corrected_scrolled_x, corrected_scrolled_y));
527        let rendered_position = Point2D::new(
528            get_corrected_scroll_position(inner_width, size.read().area.width(), smooth_position.x),
529            get_corrected_scroll_position(
530                inner_height,
531                size.read().area.height(),
532                smooth_position.y,
533            ),
534        );
535
536        let horizontal_scrollbar_is_visible =
537            is_scrollbar_visible(self.show_scrollbar, inner_width, size.read().area.width());
538        let vertical_scrollbar_is_visible =
539            is_scrollbar_visible(self.show_scrollbar, inner_height, size.read().area.height());
540
541        let (scrollbar_x, scrollbar_width) =
542            get_scrollbar_pos_and_size(inner_width, size.read().area.width(), rendered_position.x);
543        let (scrollbar_y, scrollbar_height) = get_scrollbar_pos_and_size(
544            inner_height,
545            size.read().area.height(),
546            rendered_position.y,
547        );
548
549        let (container_width, content_width) = get_container_sizes(self.layout.width.clone());
550        let (container_height, content_height) = get_container_sizes(self.layout.height.clone());
551
552        let scroll_with_arrows = self.scroll_with_arrows;
553        let invert_scroll_wheel = self.invert_scroll_wheel;
554        let follows_scroll_controller = self.follows_scroll_controller;
555
556        let on_capture_global_pointer_up = move |e: Event<PointerEventData>| {
557            if clicking_scrollbar.read().is_some() {
558                e.prevent_default();
559                clicking_scrollbar.set(None);
560            }
561
562            if drag_scrolling && (dragging_content().is_some() || drag_origin().is_some()) {
563                if dragging_content().is_some() {
564                    e.prevent_default();
565                    let content = Size2D::new(inner_width, inner_height);
566                    scroll_controller.release_drag(
567                        rendered_position,
568                        content,
569                        size.read().area.size,
570                    );
571                }
572                dragging_content.set(None);
573                drag_origin.set(None);
574            }
575        };
576
577        let on_wheel = move |e: Event<WheelEventData>| {
578            // Only invert direction on deviced-sourced wheel events
579            let invert_direction = e.source.is_device()
580                && (*pressing_shift.read() || invert_scroll_wheel)
581                && (!*pressing_shift.read() || !invert_scroll_wheel);
582
583            let (x_movement, y_movement) = if invert_direction {
584                (e.delta_y as f32, e.delta_x as f32)
585            } else {
586                (e.delta_x as f32, e.delta_y as f32)
587            };
588
589            // TODO(marc2332): Enable and test touchpad smooth scrolling in mac and windows
590            let scroll_gesture =
591                TargetPlatform::get() == TargetPlatform::Linux && e.source == WheelSource::Pixel;
592            if scroll_gesture
593                && scroll_controller.scroll_gesture_phase(e.phase, (x_movement, y_movement).into())
594            {
595                return;
596            }
597
598            let animate = e.source == WheelSource::Line || scroll_gesture;
599            if animate {
600                let position = scroll_controller.animated_position(scroll_controller.position());
601                scroll_controller.animate_from(position);
602            } else {
603                scroll_controller.stop();
604            }
605            let position = if animate || follows_scroll_controller {
606                scroll_controller.position()
607            } else {
608                rendered_position
609            };
610            let (content, viewport) = if follows_scroll_controller {
611                scroll_controller.bounds.read().unwrap_or((
612                    Size2D::new(inner_width, inner_height),
613                    size.read().area.size,
614                ))
615            } else {
616                (
617                    Size2D::new(inner_width, inner_height),
618                    size.read().area.size,
619                )
620            };
621
622            // Vertical scroll
623            let scroll_position_y = get_scroll_position_from_wheel(
624                y_movement,
625                content.height,
626                viewport.height,
627                position.y,
628            );
629            if y_movement != 0. {
630                scroll_controller.scroll_to_y(scroll_position_y).then(|| {
631                    e.stop_propagation();
632                });
633            }
634
635            // Horizontal scroll
636            let scroll_position_x = get_scroll_position_from_wheel(
637                x_movement,
638                content.width,
639                viewport.width,
640                position.x,
641            );
642            if x_movement != 0. {
643                scroll_controller.scroll_to_x(scroll_position_x).then(|| {
644                    e.stop_propagation();
645                });
646            }
647            timeout.reset();
648        };
649
650        let on_mouse_move = move |_| {
651            timeout.reset();
652        };
653
654        let on_capture_global_pointer_move = move |e: Event<PointerEventData>| {
655            if drag_scrolling {
656                if let Some(prev) = dragging_content() {
657                    let coords = e.global_location();
658                    let delta = prev - coords;
659
660                    scroll_controller.drag(delta.to_f32());
661                    scroll_controller.scroll_to_y((rendered_position.y - delta.y as f32) as i32);
662                    scroll_controller.scroll_to_x((rendered_position.x - delta.x as f32) as i32);
663
664                    dragging_content.set(Some(coords));
665                    e.prevent_default();
666                    timeout.reset();
667                    a11y_id.request_focus();
668                    return;
669                } else if let Some(origin) = drag_origin() {
670                    let coords = e.global_location();
671                    let distance = (origin - coords).abs();
672
673                    // Small threshold so taps can reach children (e.g. hover on buttons)
674                    // without being immediately consumed by drag scrolling.
675                    const DRAG_THRESHOLD: f64 = 2.0;
676
677                    if distance.x > DRAG_THRESHOLD || distance.y > DRAG_THRESHOLD {
678                        let delta = origin - coords;
679
680                        scroll_controller.drag(delta.to_f32());
681                        scroll_controller
682                            .scroll_to_y((rendered_position.y - delta.y as f32) as i32);
683                        scroll_controller
684                            .scroll_to_x((rendered_position.x - delta.x as f32) as i32);
685
686                        dragging_content.set(Some(coords));
687                        e.prevent_default();
688                        timeout.reset();
689                        a11y_id.request_focus();
690                    }
691                    return;
692                }
693            }
694
695            let clicking_scrollbar = clicking_scrollbar.peek();
696
697            if clicking_scrollbar.is_some() {
698                scroll_controller.stop();
699            }
700
701            if let Some((Axis::Y, y)) = *clicking_scrollbar {
702                let coordinates = e.element_location();
703                let cursor_y = coordinates.y - y - size.read().area.min_y() as f64;
704
705                let scroll_position = get_scroll_position_from_cursor(
706                    cursor_y as f32,
707                    inner_height,
708                    size.read().area.height(),
709                );
710
711                scroll_controller.scroll_to_y(scroll_position);
712            } else if let Some((Axis::X, x)) = *clicking_scrollbar {
713                let coordinates = e.element_location();
714                let cursor_x = coordinates.x - x - size.read().area.min_x() as f64;
715
716                let scroll_position = get_scroll_position_from_cursor(
717                    cursor_x as f32,
718                    inner_width,
719                    size.read().area.width(),
720                );
721
722                scroll_controller.scroll_to_x(scroll_position);
723            }
724
725            if clicking_scrollbar.is_some() {
726                e.prevent_default();
727                timeout.reset();
728                a11y_id.request_focus();
729            }
730        };
731
732        let on_key_down = move |e: Event<KeyboardEventData>| {
733            if !scroll_with_arrows
734                && (e.key == Key::Named(NamedKey::ArrowUp)
735                    || e.key == Key::Named(NamedKey::ArrowRight)
736                    || e.key == Key::Named(NamedKey::ArrowDown)
737                    || e.key == Key::Named(NamedKey::ArrowLeft))
738            {
739                return;
740            }
741            let x = corrected_scrolled_x;
742            let y = corrected_scrolled_y;
743            let inner_height = inner_height;
744            let inner_width = inner_width;
745            let viewport_height = size.read().area.height();
746            let viewport_width = size.read().area.width();
747            if let Some((x, y)) = handle_key_event(
748                &e.key,
749                (x, y),
750                inner_height,
751                inner_width,
752                viewport_height,
753                viewport_width,
754                direction,
755            ) {
756                scroll_controller.animate_from(rendered_position);
757                scroll_controller.scroll_to_x(x as i32);
758                scroll_controller.scroll_to_y(y as i32);
759                e.stop_propagation();
760                timeout.reset();
761            }
762        };
763
764        let on_global_key_down = move |e: Event<KeyboardEventData>| {
765            let data = e;
766            if data.key == Key::Named(NamedKey::Shift) {
767                pressing_shift.set(true);
768            }
769        };
770
771        let on_global_key_up = move |e: Event<KeyboardEventData>| {
772            let data = e;
773            if data.key == Key::Named(NamedKey::Shift) {
774                pressing_shift.set(false);
775            }
776        };
777
778        let (viewport_size, scroll_position) = if direction == Direction::vertical() {
779            (viewport_height, rendered_position.y)
780        } else {
781            (viewport_width, rendered_position.x)
782        };
783
784        let (render_range, item_offset) =
785            self.item_size
786                .visible_range(viewport_size, scroll_position, self.length);
787
788        let children = render_range
789            .map(|i| {
790                let item = VirtualItem {
791                    index: i,
792                    size: self.item_size.at(i),
793                };
794                (self.builder)(item, &self.builder_data)
795            })
796            .collect::<Vec<Element>>();
797
798        let (offset_x, offset_y) = match direction {
799            Direction::Vertical => (rendered_position.x, item_offset),
800            Direction::Horizontal => (item_offset, rendered_position.y),
801        };
802
803        let on_pointer_down = move |e: Event<PointerEventData>| {
804            if drag_scrolling && matches!(e.data(), PointerEventData::Touch(_)) {
805                scroll_controller.begin_drag();
806                drag_origin.set(Some(e.global_location()));
807            }
808        };
809
810        rect()
811            .width(layout.width.clone())
812            .height(layout.height.clone())
813            .min_width(layout.minimum_width.clone())
814            .min_height(layout.minimum_height.clone())
815            .max_width(layout.maximum_width.clone())
816            .max_height(layout.maximum_height.clone())
817            .a11y_id(a11y_id)
818            .a11y_role(AccessibilityRole::ScrollView)
819            .a11y_builder(move |node| {
820                node.set_scroll_x(rendered_position.x as f64);
821                node.set_scroll_y(rendered_position.y as f64)
822            })
823            .scrollable(true)
824            .on_wheel(on_wheel)
825            .on_capture_global_pointer_up(on_capture_global_pointer_up)
826            .on_mouse_move(on_mouse_move)
827            .on_capture_global_pointer_move(on_capture_global_pointer_move)
828            .on_key_down(on_key_down)
829            .on_global_key_up(on_global_key_up)
830            .on_global_key_down(on_global_key_down)
831            .on_pointer_down(on_pointer_down)
832            .child(
833                rect()
834                    .width(container_width)
835                    .height(container_height)
836                    .horizontal()
837                    .child(
838                        rect()
839                            .direction(direction)
840                            .width(content_width)
841                            .height(content_height)
842                            .offset_x(offset_x)
843                            .offset_y(offset_y)
844                            .overflow(Overflow::Clip)
845                            .on_sized({
846                                let item_size = self.item_size.clone();
847                                let length = self.length;
848                                let on_sized = self.on_sized.clone();
849                                let follows_scroll_controller = self.follows_scroll_controller;
850                                move |e: Event<SizedEventData>| {
851                                    size.set_if_modified(e.clone());
852                                    if !follows_scroll_controller {
853                                        let content_size = match direction {
854                                            Direction::Vertical => Size2D::new(
855                                                e.inner_sizes.width,
856                                                item_size.total_size(
857                                                    e.area.height(),
858                                                    scrolled_y as f32,
859                                                    length,
860                                                ),
861                                            ),
862                                            Direction::Horizontal => Size2D::new(
863                                                item_size.total_size(
864                                                    e.area.width(),
865                                                    scrolled_x as f32,
866                                                    length,
867                                                ),
868                                                e.inner_sizes.height,
869                                            ),
870                                        };
871
872                                        scroll_controller.apply_layout(content_size, e.area.size);
873                                    }
874                                    if let Some(on_sized) = &on_sized {
875                                        on_sized.call(e);
876                                    }
877                                }
878                            })
879                            .children(children),
880                    )
881                    .maybe_child(vertical_scrollbar_is_visible.then_some({
882                        rect().child(self.scrollbar.call(ScrollBarContext {
883                            axis: Axis::Y,
884                            scroll_position: rendered_position,
885                            viewport_size: size.read().area.size,
886                            content_size: Size2D::new(inner_width, inner_height),
887                            scroll_controller,
888                            timeout,
889                            auto_hide_scrollbars: self.auto_hide_scrollbars,
890                            clicking_scrollbar,
891                            thumb_events: ScrollBarThumbEvents::new(Axis::Y, clicking_scrollbar),
892                            thumb_offset: scrollbar_y,
893                            track_size: Size::px(size.read().area.height()),
894                            thumb_length: scrollbar_height,
895                        }))
896                    })),
897            )
898            .maybe_child(horizontal_scrollbar_is_visible.then_some({
899                rect().child(self.scrollbar.call(ScrollBarContext {
900                    axis: Axis::X,
901                    scroll_position: rendered_position,
902                    viewport_size: size.read().area.size,
903                    content_size: Size2D::new(inner_width, inner_height),
904                    scroll_controller,
905                    timeout,
906                    auto_hide_scrollbars: self.auto_hide_scrollbars,
907                    clicking_scrollbar,
908                    thumb_events: ScrollBarThumbEvents::new(Axis::X, clicking_scrollbar),
909                    thumb_offset: scrollbar_x,
910                    track_size: Size::px(size.read().area.width()),
911                    thumb_length: scrollbar_width,
912                }))
913            }))
914    }
915
916    fn render_key(&self) -> DiffKey {
917        self.key.clone().or(self.default_key())
918    }
919}