Skip to main content

freya_components/scrollviews/
scrollview.rs

1use std::time::Duration;
2
3use freya_core::prelude::*;
4use freya_sdk::timeout::use_timeout;
5use torin::{
6    geometry::{
7        CursorPoint,
8        Point2D,
9    },
10    node::Node,
11    prelude::{
12        Direction,
13        Length,
14    },
15    size::Size,
16};
17
18use crate::scrollviews::{
19    ScrollBar,
20    ScrollBarContext,
21    ScrollBarThumbEvents,
22    ScrollConfig,
23    ScrollController,
24    shared::{
25        Axis,
26        get_container_sizes,
27        get_corrected_scroll_position,
28        get_scroll_position_from_cursor,
29        get_scroll_position_from_wheel,
30        get_scrollbar_pos_and_size,
31        handle_key_event,
32        is_scrollbar_visible,
33    },
34    use_scroll_controller,
35};
36
37/// Scrollable area with bidirectional support and scrollbars.
38///
39/// It renders all of its children and scrolls over them, which makes it a good fit for small or
40/// medium amounts of content. For large data sets prefer
41/// [`VirtualScrollView`](crate::scrollviews::VirtualScrollView), which only renders the visible
42/// items. It scrolls vertically by default, use [`direction`](ScrollView::direction) for a
43/// horizontal layout. To drive the scroll position from code, build it with
44/// [`new_controlled`](ScrollView::new_controlled) and a [`ScrollController`].
45///
46/// # Example
47///
48/// ```rust
49/// # use freya::prelude::*;
50/// fn app() -> impl IntoElement {
51///     ScrollView::new()
52///         .child("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum laoreet tristique diam, ut gravida enim. Phasellus viverra vitae risus sit amet iaculis. Morbi porttitor quis nisl eu vulputate. Etiam vitae ligula a purus suscipit iaculis non ac risus. Suspendisse potenti. Aenean orci massa, ornare ut elit id, tristique commodo dui. Vestibulum laoreet tristique diam, ut gravida enim. Phasellus viverra vitae risus sit amet iaculis. Vestibulum laoreet tristique diam, ut gravida enim. Phasellus viverra vitae risus sit amet iaculis. Vestibulum laoreet tristique diam, ut gravida enim. Phasellus viverra vitae risus sit amet iaculis.")
53/// }
54/// ```
55///
56/// See the [interactive components demo](https://freyaui.dev/demo).
57#[derive(Clone, PartialEq)]
58pub struct ScrollView {
59    children: Vec<Element>,
60    layout: LayoutData,
61    show_scrollbar: bool,
62    auto_hide_scrollbars: bool,
63    scroll_with_arrows: bool,
64    scroll_controller: Option<ScrollController>,
65    follows_scroll_controller: bool,
66    invert_scroll_wheel: bool,
67    drag_scrolling: bool,
68    on_sized: Option<EventHandler<Event<SizedEventData>>>,
69    scrollbar: Callback<ScrollBarContext, Element>,
70    key: DiffKey,
71}
72
73impl ChildrenExt for ScrollView {
74    fn children_mut(&mut self) -> &mut Vec<Element> {
75        &mut self.children
76    }
77}
78
79impl KeyExt for ScrollView {
80    fn key_mut(&mut self) -> &mut DiffKey {
81        &mut self.key
82    }
83}
84
85impl Default for ScrollView {
86    fn default() -> Self {
87        Self {
88            children: Vec::default(),
89            layout: Node {
90                width: Size::fill(),
91                height: Size::fill(),
92                ..Default::default()
93            }
94            .into(),
95            show_scrollbar: true,
96            auto_hide_scrollbars: true,
97            scroll_with_arrows: true,
98            scroll_controller: None,
99            follows_scroll_controller: false,
100            invert_scroll_wheel: false,
101            drag_scrolling: true,
102            on_sized: None,
103            scrollbar: ScrollBar::default_renderer(),
104            key: DiffKey::None,
105        }
106    }
107}
108
109impl ScrollView {
110    /// Creates an uncontrolled scroll view that manages its own scroll position.
111    pub fn new() -> Self {
112        Self::default()
113    }
114
115    /// Creates a scroll view driven by the given [`ScrollController`].
116    pub fn new_controlled(scroll_controller: ScrollController) -> Self {
117        Self {
118            scroll_controller: Some(scroll_controller),
119            ..Default::default()
120        }
121    }
122
123    /// Attaches a controller and updates its bounds from this view's layout.
124    pub fn scroll_controller(
125        mut self,
126        scroll_controller: impl Into<Option<ScrollController>>,
127    ) -> Self {
128        self.scroll_controller = scroll_controller.into();
129        self.follows_scroll_controller = false;
130        self
131    }
132
133    /// Attaches a controller without updating its bounds from this view's layout.
134    pub fn follow_scroll_controller(mut self, scroll_controller: ScrollController) -> Self {
135        self.scroll_controller = Some(scroll_controller);
136        self.follows_scroll_controller = true;
137        self
138    }
139
140    /// Toggles whether the scrollbars are shown when the content overflows.
141    pub fn show_scrollbar(mut self, show_scrollbar: bool) -> Self {
142        self.show_scrollbar = show_scrollbar;
143        self
144    }
145
146    /// Toggles hiding idle scrollbars, enabled by default.
147    /// When disabled, scrollbars remain visible while the content overflows.
148    pub fn auto_hide_scrollbars(mut self, auto_hide_scrollbars: bool) -> Self {
149        self.auto_hide_scrollbars = auto_hide_scrollbars;
150        self
151    }
152
153    /// Sets the layout direction the children flow and scroll in.
154    pub fn direction(mut self, direction: Direction) -> Self {
155        self.layout.direction = direction;
156        self
157    }
158
159    /// Sets the gap between children along the scroll direction.
160    pub fn spacing(mut self, spacing: f32) -> Self {
161        self.layout.spacing = Length::new(spacing);
162        self
163    }
164
165    /// Toggles whether the arrow keys scroll the view while it is focused.
166    pub fn scroll_with_arrows(mut self, scroll_with_arrows: impl Into<bool>) -> Self {
167        self.scroll_with_arrows = scroll_with_arrows.into();
168        self
169    }
170
171    /// Inverts the direction of the mouse wheel relative to the content.
172    pub fn invert_scroll_wheel(mut self, invert_scroll_wheel: impl Into<bool>) -> Self {
173        self.invert_scroll_wheel = invert_scroll_wheel.into();
174        self
175    }
176
177    /// Toggles scrolling by dragging the content, useful mainly for touch input.
178    pub fn drag_scrolling(mut self, drag_scrolling: bool) -> Self {
179        self.drag_scrolling = drag_scrolling;
180        self
181    }
182
183    /// Sets the renderer used for each visible scrollbar.
184    pub fn scrollbar(mut self, scrollbar: impl Into<Callback<ScrollBarContext, Element>>) -> Self {
185        self.scrollbar = scrollbar.into();
186        self
187    }
188
189    /// Sets a handler called with the scroll view's area whenever it is laid out.
190    pub fn on_sized(mut self, on_sized: impl Into<EventHandler<Event<SizedEventData>>>) -> Self {
191        self.on_sized = Some(on_sized.into());
192        self
193    }
194
195    /// Caps the width of the scroll view.
196    pub fn max_width(mut self, max_width: impl Into<Size>) -> Self {
197        self.layout.maximum_width = max_width.into();
198        self
199    }
200
201    /// Caps the height of the scroll view.
202    pub fn max_height(mut self, max_height: impl Into<Size>) -> Self {
203        self.layout.maximum_height = max_height.into();
204        self
205    }
206}
207
208impl LayoutExt for ScrollView {
209    fn layout_mut(&mut self) -> &mut LayoutData {
210        &mut self.layout
211    }
212}
213
214impl ContainerSizeExt for ScrollView {}
215impl ContainerPositionExt for ScrollView {}
216
217impl Component for ScrollView {
218    fn render(self: &ScrollView) -> impl IntoElement {
219        let a11y_id = use_a11y();
220        let mut timeout = use_timeout(|| Duration::from_millis(800));
221        let mut pressing_shift = use_state(|| false);
222        let mut clicking_scrollbar = use_state::<Option<(Axis, f64)>>(|| None);
223        let mut size = use_state(SizedEventData::default);
224        let mut scroll_controller = self
225            .scroll_controller
226            .unwrap_or_else(|| use_scroll_controller(ScrollConfig::default));
227        let mut dragging_content = use_state::<Option<CursorPoint>>(|| None);
228        let mut drag_origin = use_state::<Option<CursorPoint>>(|| None);
229        let (scrolled_x, scrolled_y) = scroll_controller.into();
230        let layout = &self.layout.layout;
231        let direction = layout.direction;
232        let drag_scrolling = self.drag_scrolling;
233        let follows_scroll_controller = self.follows_scroll_controller;
234
235        let corrected_scrolled_x = get_corrected_scroll_position(
236            size.read().inner_sizes.width,
237            size.read().area.width(),
238            scrolled_x as f32,
239        );
240
241        let corrected_scrolled_y = get_corrected_scroll_position(
242            size.read().inner_sizes.height,
243            size.read().area.height(),
244            scrolled_y as f32,
245        );
246
247        let smooth_position = scroll_controller
248            .animated_position(Point2D::new(corrected_scrolled_x, corrected_scrolled_y));
249        let rendered_position = Point2D::new(
250            get_corrected_scroll_position(
251                size.read().inner_sizes.width,
252                size.read().area.width(),
253                smooth_position.x,
254            ),
255            get_corrected_scroll_position(
256                size.read().inner_sizes.height,
257                size.read().area.height(),
258                smooth_position.y,
259            ),
260        );
261
262        let horizontal_scrollbar_is_visible = is_scrollbar_visible(
263            self.show_scrollbar,
264            size.read().inner_sizes.width,
265            size.read().area.width(),
266        );
267        let vertical_scrollbar_is_visible = is_scrollbar_visible(
268            self.show_scrollbar,
269            size.read().inner_sizes.height,
270            size.read().area.height(),
271        );
272
273        let (scrollbar_x, scrollbar_width) = get_scrollbar_pos_and_size(
274            size.read().inner_sizes.width,
275            size.read().area.width(),
276            rendered_position.x,
277        );
278        let (scrollbar_y, scrollbar_height) = get_scrollbar_pos_and_size(
279            size.read().inner_sizes.height,
280            size.read().area.height(),
281            rendered_position.y,
282        );
283
284        let (container_width, content_width) = get_container_sizes(layout.width.clone());
285        let (container_height, content_height) = get_container_sizes(layout.height.clone());
286
287        let scroll_with_arrows = self.scroll_with_arrows;
288        let invert_scroll_wheel = self.invert_scroll_wheel;
289
290        let on_capture_global_pointer_up = move |e: Event<PointerEventData>| {
291            if clicking_scrollbar.read().is_some() {
292                e.prevent_default();
293                clicking_scrollbar.set(None);
294            }
295
296            if drag_scrolling && (dragging_content().is_some() || drag_origin().is_some()) {
297                if dragging_content().is_some() {
298                    e.prevent_default();
299                    let content = size.read().inner_sizes;
300                    let viewport = size.read().area.size;
301                    scroll_controller.release_drag(rendered_position, content, viewport);
302                }
303                dragging_content.set(None);
304                drag_origin.set(None);
305            }
306        };
307
308        let on_wheel = move |e: Event<WheelEventData>| {
309            // Only invert direction on deviced-sourced wheel events
310            let invert_direction = e.source.is_device()
311                && (*pressing_shift.read() || invert_scroll_wheel)
312                && (!*pressing_shift.read() || !invert_scroll_wheel);
313
314            let (x_movement, y_movement) = if invert_direction {
315                (e.delta_y as f32, e.delta_x as f32)
316            } else {
317                (e.delta_x as f32, e.delta_y as f32)
318            };
319
320            // TODO(marc2332): Enable and test touchpad smooth scrolling in mac and windows
321            let scroll_gesture =
322                TargetPlatform::get() == TargetPlatform::Linux && e.source == WheelSource::Pixel;
323            if scroll_gesture
324                && scroll_controller.scroll_gesture_phase(e.phase, (x_movement, y_movement).into())
325            {
326                return;
327            }
328
329            let animate = e.source == WheelSource::Line || scroll_gesture;
330            if animate {
331                let position = scroll_controller.animated_position(scroll_controller.position());
332                scroll_controller.animate_from(position);
333            } else {
334                scroll_controller.stop();
335            }
336            let position = if animate || follows_scroll_controller {
337                scroll_controller.position()
338            } else {
339                rendered_position
340            };
341            let (content, viewport) = if follows_scroll_controller {
342                scroll_controller
343                    .bounds
344                    .read()
345                    .unwrap_or((size.read().inner_sizes, size.read().area.size))
346            } else {
347                (size.read().inner_sizes, size.read().area.size)
348            };
349
350            // Vertical scroll
351            let scroll_position_y = get_scroll_position_from_wheel(
352                y_movement,
353                content.height,
354                viewport.height,
355                position.y,
356            );
357            if y_movement != 0. {
358                scroll_controller.scroll_to_y(scroll_position_y).then(|| {
359                    e.stop_propagation();
360                });
361            }
362
363            // Horizontal scroll
364            let scroll_position_x = get_scroll_position_from_wheel(
365                x_movement,
366                content.width,
367                viewport.width,
368                position.x,
369            );
370            if x_movement != 0. {
371                scroll_controller.scroll_to_x(scroll_position_x).then(|| {
372                    e.stop_propagation();
373                });
374            }
375            timeout.reset();
376        };
377
378        let on_mouse_move = move |_| {
379            timeout.reset();
380        };
381
382        let on_capture_global_pointer_move = move |e: Event<PointerEventData>| {
383            if drag_scrolling {
384                if let Some(prev) = dragging_content() {
385                    let coords = e.global_location();
386                    let delta = prev - coords;
387
388                    scroll_controller.drag(delta.to_f32());
389                    scroll_controller.scroll_to_y((rendered_position.y - delta.y as f32) as i32);
390                    scroll_controller.scroll_to_x((rendered_position.x - delta.x as f32) as i32);
391
392                    dragging_content.set(Some(coords));
393                    e.prevent_default();
394                    timeout.reset();
395                    a11y_id.request_focus();
396                    return;
397                } else if let Some(origin) = drag_origin() {
398                    let coords = e.global_location();
399                    let distance = (origin - coords).abs();
400
401                    // Small threshold so taps can reach children (e.g. hover on buttons)
402                    // without being immediately consumed by drag scrolling.
403                    const DRAG_THRESHOLD: f64 = 2.0;
404
405                    if distance.x > DRAG_THRESHOLD || distance.y > DRAG_THRESHOLD {
406                        let delta = origin - coords;
407
408                        scroll_controller.drag(delta.to_f32());
409                        scroll_controller
410                            .scroll_to_y((rendered_position.y - delta.y as f32) as i32);
411                        scroll_controller
412                            .scroll_to_x((rendered_position.x - delta.x as f32) as i32);
413
414                        dragging_content.set(Some(coords));
415                        e.prevent_default();
416                        timeout.reset();
417                        a11y_id.request_focus();
418                    }
419                    return;
420                }
421            }
422
423            let clicking_scrollbar = clicking_scrollbar.peek();
424
425            if clicking_scrollbar.is_some() {
426                scroll_controller.stop();
427            }
428
429            if let Some((Axis::Y, y)) = *clicking_scrollbar {
430                let coordinates = e.element_location();
431                let cursor_y = coordinates.y - y - size.read().area.min_y() as f64;
432
433                let scroll_position = get_scroll_position_from_cursor(
434                    cursor_y as f32,
435                    size.read().inner_sizes.height,
436                    size.read().area.height(),
437                );
438
439                scroll_controller.scroll_to_y(scroll_position);
440            } else if let Some((Axis::X, x)) = *clicking_scrollbar {
441                let coordinates = e.element_location();
442                let cursor_x = coordinates.x - x - size.read().area.min_x() as f64;
443
444                let scroll_position = get_scroll_position_from_cursor(
445                    cursor_x as f32,
446                    size.read().inner_sizes.width,
447                    size.read().area.width(),
448                );
449
450                scroll_controller.scroll_to_x(scroll_position);
451            }
452
453            if clicking_scrollbar.is_some() {
454                e.prevent_default();
455                timeout.reset();
456                a11y_id.request_focus();
457            }
458        };
459
460        let on_key_down = move |e: Event<KeyboardEventData>| {
461            if !scroll_with_arrows
462                && (e.key == Key::Named(NamedKey::ArrowUp)
463                    || e.key == Key::Named(NamedKey::ArrowRight)
464                    || e.key == Key::Named(NamedKey::ArrowDown)
465                    || e.key == Key::Named(NamedKey::ArrowLeft))
466            {
467                return;
468            }
469            let x = corrected_scrolled_x;
470            let y = corrected_scrolled_y;
471            let inner_height = size.read().inner_sizes.height;
472            let inner_width = size.read().inner_sizes.width;
473            let viewport_height = size.read().area.height();
474            let viewport_width = size.read().area.width();
475            if let Some((x, y)) = handle_key_event(
476                &e.key,
477                (x, y),
478                inner_height,
479                inner_width,
480                viewport_height,
481                viewport_width,
482                direction,
483            ) {
484                scroll_controller.animate_from(rendered_position);
485                scroll_controller.scroll_to_x(x as i32);
486                scroll_controller.scroll_to_y(y as i32);
487                e.stop_propagation();
488                timeout.reset();
489            }
490        };
491
492        let on_global_key_down = move |e: Event<KeyboardEventData>| {
493            let data = e;
494            if data.key == Key::Named(NamedKey::Shift) {
495                pressing_shift.set(true);
496            }
497        };
498
499        let on_global_key_up = move |e: Event<KeyboardEventData>| {
500            let data = e;
501            if data.key == Key::Named(NamedKey::Shift) {
502                pressing_shift.set(false);
503            }
504        };
505
506        let on_pointer_down = move |e: Event<PointerEventData>| {
507            if drag_scrolling && matches!(e.data(), PointerEventData::Touch(_)) {
508                scroll_controller.begin_drag();
509                drag_origin.set(Some(e.global_location()));
510            }
511        };
512
513        rect()
514            .width(layout.width.clone())
515            .height(layout.height.clone())
516            .max_width(layout.maximum_width.clone())
517            .max_height(layout.maximum_height.clone())
518            .a11y_id(a11y_id)
519            .a11y_role(AccessibilityRole::ScrollView)
520            .a11y_builder(move |node| {
521                node.set_scroll_x(rendered_position.x as f64);
522                node.set_scroll_y(rendered_position.y as f64)
523            })
524            .scrollable(true)
525            .map(self.on_sized.clone(), |el, on_sized| el.on_sized(on_sized))
526            .on_wheel(on_wheel)
527            .on_capture_global_pointer_up(on_capture_global_pointer_up)
528            .on_mouse_move(on_mouse_move)
529            .on_capture_global_pointer_move(on_capture_global_pointer_move)
530            .on_key_down(on_key_down)
531            .on_global_key_up(on_global_key_up)
532            .on_global_key_down(on_global_key_down)
533            .on_pointer_down(on_pointer_down)
534            .child(
535                rect()
536                    .width(container_width)
537                    .height(container_height)
538                    .horizontal()
539                    .child(
540                        rect()
541                            .direction(direction)
542                            .width(content_width)
543                            .height(content_height)
544                            .max_width(layout.maximum_width.clone())
545                            .max_height(layout.maximum_height.clone())
546                            .offset_x(rendered_position.x)
547                            .offset_y(rendered_position.y)
548                            .spacing(layout.spacing.get())
549                            .overflow(Overflow::Clip)
550                            .on_sized(move |e: Event<SizedEventData>| {
551                                size.set_if_modified(e.clone());
552                                if !follows_scroll_controller {
553                                    scroll_controller.apply_layout(e.inner_sizes, e.area.size);
554                                }
555                            })
556                            .children(self.children.clone()),
557                    )
558                    .maybe_child(vertical_scrollbar_is_visible.then_some({
559                        rect().child(self.scrollbar.call(ScrollBarContext {
560                            axis: Axis::Y,
561                            scroll_position: rendered_position,
562                            viewport_size: size.read().area.size,
563                            content_size: size.read().inner_sizes,
564                            scroll_controller,
565                            timeout,
566                            auto_hide_scrollbars: self.auto_hide_scrollbars,
567                            clicking_scrollbar,
568                            thumb_events: ScrollBarThumbEvents::new(Axis::Y, clicking_scrollbar),
569                            thumb_offset: scrollbar_y,
570                            track_size: Size::px(size.read().area.height()),
571                            thumb_length: scrollbar_height,
572                        }))
573                    })),
574            )
575            .maybe_child(horizontal_scrollbar_is_visible.then_some({
576                rect().child(self.scrollbar.call(ScrollBarContext {
577                    axis: Axis::X,
578                    scroll_position: rendered_position,
579                    viewport_size: size.read().area.size,
580                    content_size: size.read().inner_sizes,
581                    scroll_controller,
582                    timeout,
583                    auto_hide_scrollbars: self.auto_hide_scrollbars,
584                    clicking_scrollbar,
585                    thumb_events: ScrollBarThumbEvents::new(Axis::X, clicking_scrollbar),
586                    thumb_offset: scrollbar_x,
587                    track_size: Size::px(size.read().area.width()),
588                    thumb_length: scrollbar_width,
589                }))
590            }))
591    }
592
593    fn render_key(&self) -> DiffKey {
594        self.key.clone().or(self.default_key())
595    }
596}