iced_widget/
scrollable.rs

1//! Scrollables let users navigate an endless amount of content with a scrollbar.
2//!
3//! # Example
4//! ```no_run
5//! # mod iced { pub mod widget { pub use iced_widget::*; } }
6//! # pub type State = ();
7//! # pub type Element<'a, Message> = iced_widget::core::Element<'a, Message, iced_widget::Theme, iced_widget::Renderer>;
8//! use iced::widget::{column, scrollable, space};
9//!
10//! enum Message {
11//!     // ...
12//! }
13//!
14//! fn view(state: &State) -> Element<'_, Message> {
15//!     scrollable(column![
16//!         "Scroll me!",
17//!         space().height(3000),
18//!         "You did it!",
19//!     ]).into()
20//! }
21//! ```
22use crate::container;
23use crate::core::alignment;
24use crate::core::border::{self, Border};
25use crate::core::keyboard;
26use crate::core::layout;
27use crate::core::mouse;
28use crate::core::overlay;
29use crate::core::renderer;
30use crate::core::text;
31use crate::core::time::{Duration, Instant};
32use crate::core::touch;
33use crate::core::widget;
34use crate::core::widget::operation::{self, Operation};
35use crate::core::widget::tree::{self, Tree};
36use crate::core::window;
37use crate::core::{
38    self, Background, Clipboard, Color, Element, Event, InputMethod, Layout, Length, Padding,
39    Pixels, Point, Rectangle, Shadow, Shell, Size, Theme, Vector, Widget,
40};
41
42pub use operation::scrollable::{AbsoluteOffset, RelativeOffset};
43
44/// A widget that can vertically display an infinite amount of content with a
45/// scrollbar.
46///
47/// # Example
48/// ```no_run
49/// # mod iced { pub mod widget { pub use iced_widget::*; } }
50/// # pub type State = ();
51/// # pub type Element<'a, Message> = iced_widget::core::Element<'a, Message, iced_widget::Theme, iced_widget::Renderer>;
52/// use iced::widget::{column, scrollable, space};
53///
54/// enum Message {
55///     // ...
56/// }
57///
58/// fn view(state: &State) -> Element<'_, Message> {
59///     scrollable(column![
60///         "Scroll me!",
61///         space().height(3000),
62///         "You did it!",
63///     ]).into()
64/// }
65/// ```
66pub struct Scrollable<'a, Message, Theme = crate::Theme, Renderer = crate::Renderer>
67where
68    Theme: Catalog,
69    Renderer: text::Renderer,
70{
71    id: Option<widget::Id>,
72    width: Length,
73    height: Length,
74    direction: Direction,
75    auto_scroll: bool,
76    content: Element<'a, Message, Theme, Renderer>,
77    on_scroll: Option<Box<dyn Fn(Viewport) -> Message + 'a>>,
78    class: Theme::Class<'a>,
79    last_status: Option<Status>,
80}
81
82impl<'a, Message, Theme, Renderer> Scrollable<'a, Message, Theme, Renderer>
83where
84    Theme: Catalog,
85    Renderer: text::Renderer,
86{
87    /// Creates a new vertical [`Scrollable`].
88    pub fn new(content: impl Into<Element<'a, Message, Theme, Renderer>>) -> Self {
89        Self::with_direction(content, Direction::default())
90    }
91
92    /// Creates a new [`Scrollable`] with the given [`Direction`].
93    pub fn with_direction(
94        content: impl Into<Element<'a, Message, Theme, Renderer>>,
95        direction: impl Into<Direction>,
96    ) -> Self {
97        Scrollable {
98            id: None,
99            width: Length::Shrink,
100            height: Length::Shrink,
101            direction: direction.into(),
102            auto_scroll: false,
103            content: content.into(),
104            on_scroll: None,
105            class: Theme::default(),
106            last_status: None,
107        }
108        .enclose()
109    }
110
111    fn enclose(mut self) -> Self {
112        let size_hint = self.content.as_widget().size_hint();
113
114        if self.direction.horizontal().is_none() {
115            self.width = self.width.enclose(size_hint.width);
116        }
117
118        if self.direction.vertical().is_none() {
119            self.height = self.height.enclose(size_hint.height);
120        }
121
122        self
123    }
124
125    /// Makes the [`Scrollable`] scroll horizontally, with default [`Scrollbar`] settings.
126    pub fn horizontal(self) -> Self {
127        self.direction(Direction::Horizontal(Scrollbar::default()))
128    }
129
130    /// Sets the [`Direction`] of the [`Scrollable`].
131    pub fn direction(mut self, direction: impl Into<Direction>) -> Self {
132        self.direction = direction.into();
133        self.enclose()
134    }
135
136    /// Sets the [`widget::Id`] of the [`Scrollable`].
137    pub fn id(mut self, id: impl Into<widget::Id>) -> Self {
138        self.id = Some(id.into());
139        self
140    }
141
142    /// Sets the width of the [`Scrollable`].
143    pub fn width(mut self, width: impl Into<Length>) -> Self {
144        self.width = width.into();
145        self
146    }
147
148    /// Sets the height of the [`Scrollable`].
149    pub fn height(mut self, height: impl Into<Length>) -> Self {
150        self.height = height.into();
151        self
152    }
153
154    /// Sets a function to call when the [`Scrollable`] is scrolled.
155    ///
156    /// The function takes the [`Viewport`] of the [`Scrollable`]
157    pub fn on_scroll(mut self, f: impl Fn(Viewport) -> Message + 'a) -> Self {
158        self.on_scroll = Some(Box::new(f));
159        self
160    }
161
162    /// Anchors the vertical [`Scrollable`] direction to the top.
163    pub fn anchor_top(self) -> Self {
164        self.anchor_y(Anchor::Start)
165    }
166
167    /// Anchors the vertical [`Scrollable`] direction to the bottom.
168    pub fn anchor_bottom(self) -> Self {
169        self.anchor_y(Anchor::End)
170    }
171
172    /// Anchors the horizontal [`Scrollable`] direction to the left.
173    pub fn anchor_left(self) -> Self {
174        self.anchor_x(Anchor::Start)
175    }
176
177    /// Anchors the horizontal [`Scrollable`] direction to the right.
178    pub fn anchor_right(self) -> Self {
179        self.anchor_x(Anchor::End)
180    }
181
182    /// Sets the [`Anchor`] of the horizontal direction of the [`Scrollable`], if applicable.
183    pub fn anchor_x(mut self, alignment: Anchor) -> Self {
184        match &mut self.direction {
185            Direction::Horizontal(horizontal) | Direction::Both { horizontal, .. } => {
186                horizontal.alignment = alignment;
187            }
188            Direction::Vertical { .. } => {}
189        }
190
191        self
192    }
193
194    /// Sets the [`Anchor`] of the vertical direction of the [`Scrollable`], if applicable.
195    pub fn anchor_y(mut self, alignment: Anchor) -> Self {
196        match &mut self.direction {
197            Direction::Vertical(vertical) | Direction::Both { vertical, .. } => {
198                vertical.alignment = alignment;
199            }
200            Direction::Horizontal { .. } => {}
201        }
202
203        self
204    }
205
206    /// Embeds the [`Scrollbar`] into the [`Scrollable`], instead of floating on top of the
207    /// content.
208    ///
209    /// The `spacing` provided will be used as space between the [`Scrollbar`] and the contents
210    /// of the [`Scrollable`].
211    pub fn spacing(mut self, new_spacing: impl Into<Pixels>) -> Self {
212        match &mut self.direction {
213            Direction::Horizontal(scrollbar) | Direction::Vertical(scrollbar) => {
214                scrollbar.spacing = Some(new_spacing.into().0);
215            }
216            Direction::Both { .. } => {}
217        }
218
219        self
220    }
221
222    /// Sets whether the user should be allowed to auto-scroll the [`Scrollable`]
223    /// with the middle mouse button.
224    ///
225    /// By default, it is disabled.
226    pub fn auto_scroll(mut self, auto_scroll: bool) -> Self {
227        self.auto_scroll = auto_scroll;
228        self
229    }
230
231    /// Sets the style of this [`Scrollable`].
232    #[must_use]
233    pub fn style(mut self, style: impl Fn(&Theme, Status) -> Style + 'a) -> Self
234    where
235        Theme::Class<'a>: From<StyleFn<'a, Theme>>,
236    {
237        self.class = (Box::new(style) as StyleFn<'a, Theme>).into();
238        self
239    }
240
241    /// Sets the style class of the [`Scrollable`].
242    #[cfg(feature = "advanced")]
243    #[must_use]
244    pub fn class(mut self, class: impl Into<Theme::Class<'a>>) -> Self {
245        self.class = class.into();
246        self
247    }
248}
249
250/// The direction of [`Scrollable`].
251#[derive(Debug, Clone, Copy, PartialEq)]
252pub enum Direction {
253    /// Vertical scrolling
254    Vertical(Scrollbar),
255    /// Horizontal scrolling
256    Horizontal(Scrollbar),
257    /// Both vertical and horizontal scrolling
258    Both {
259        /// The properties of the vertical scrollbar.
260        vertical: Scrollbar,
261        /// The properties of the horizontal scrollbar.
262        horizontal: Scrollbar,
263    },
264}
265
266impl Direction {
267    /// Returns the horizontal [`Scrollbar`], if any.
268    pub fn horizontal(&self) -> Option<&Scrollbar> {
269        match self {
270            Self::Horizontal(scrollbar) => Some(scrollbar),
271            Self::Both { horizontal, .. } => Some(horizontal),
272            Self::Vertical(_) => None,
273        }
274    }
275
276    /// Returns the vertical [`Scrollbar`], if any.
277    pub fn vertical(&self) -> Option<&Scrollbar> {
278        match self {
279            Self::Vertical(scrollbar) => Some(scrollbar),
280            Self::Both { vertical, .. } => Some(vertical),
281            Self::Horizontal(_) => None,
282        }
283    }
284
285    fn align(&self, delta: Vector) -> Vector {
286        let horizontal_alignment = self.horizontal().map(|p| p.alignment).unwrap_or_default();
287
288        let vertical_alignment = self.vertical().map(|p| p.alignment).unwrap_or_default();
289
290        let align = |alignment: Anchor, delta: f32| match alignment {
291            Anchor::Start => delta,
292            Anchor::End => -delta,
293        };
294
295        Vector::new(
296            align(horizontal_alignment, delta.x),
297            align(vertical_alignment, delta.y),
298        )
299    }
300}
301
302impl Default for Direction {
303    fn default() -> Self {
304        Self::Vertical(Scrollbar::default())
305    }
306}
307
308/// A scrollbar within a [`Scrollable`].
309#[derive(Debug, Clone, Copy, PartialEq)]
310pub struct Scrollbar {
311    width: f32,
312    margin: f32,
313    scroller_width: f32,
314    alignment: Anchor,
315    spacing: Option<f32>,
316}
317
318impl Default for Scrollbar {
319    fn default() -> Self {
320        Self {
321            width: 10.0,
322            margin: 0.0,
323            scroller_width: 10.0,
324            alignment: Anchor::Start,
325            spacing: None,
326        }
327    }
328}
329
330impl Scrollbar {
331    /// Creates new [`Scrollbar`] for use in a [`Scrollable`].
332    pub fn new() -> Self {
333        Self::default()
334    }
335
336    /// Create a [`Scrollbar`] with zero width to allow a [`Scrollable`] to scroll without a visible
337    /// scroller.
338    pub fn hidden() -> Self {
339        Self::default().width(0).scroller_width(0)
340    }
341
342    /// Sets the scrollbar width of the [`Scrollbar`] .
343    pub fn width(mut self, width: impl Into<Pixels>) -> Self {
344        self.width = width.into().0.max(0.0);
345        self
346    }
347
348    /// Sets the scrollbar margin of the [`Scrollbar`] .
349    pub fn margin(mut self, margin: impl Into<Pixels>) -> Self {
350        self.margin = margin.into().0;
351        self
352    }
353
354    /// Sets the scroller width of the [`Scrollbar`] .
355    pub fn scroller_width(mut self, scroller_width: impl Into<Pixels>) -> Self {
356        self.scroller_width = scroller_width.into().0.max(0.0);
357        self
358    }
359
360    /// Sets the [`Anchor`] of the [`Scrollbar`] .
361    pub fn anchor(mut self, alignment: Anchor) -> Self {
362        self.alignment = alignment;
363        self
364    }
365
366    /// Sets whether the [`Scrollbar`] should be embedded in the [`Scrollable`], using
367    /// the given spacing between itself and the contents.
368    ///
369    /// An embedded [`Scrollbar`] will always be displayed, will take layout space,
370    /// and will not float over the contents.
371    pub fn spacing(mut self, spacing: impl Into<Pixels>) -> Self {
372        self.spacing = Some(spacing.into().0);
373        self
374    }
375}
376
377/// The anchor of the scroller of the [`Scrollable`] relative to its [`Viewport`]
378/// on a given axis.
379#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
380pub enum Anchor {
381    /// Scroller is anchoer to the start of the [`Viewport`].
382    #[default]
383    Start,
384    /// Content is aligned to the end of the [`Viewport`].
385    End,
386}
387
388impl<Message, Theme, Renderer> Widget<Message, Theme, Renderer>
389    for Scrollable<'_, Message, Theme, Renderer>
390where
391    Theme: Catalog,
392    Renderer: text::Renderer,
393{
394    fn tag(&self) -> tree::Tag {
395        tree::Tag::of::<State>()
396    }
397
398    fn state(&self) -> tree::State {
399        tree::State::new(State::new())
400    }
401
402    fn children(&self) -> Vec<Tree> {
403        vec![Tree::new(&self.content)]
404    }
405
406    fn diff(&self, tree: &mut Tree) {
407        tree.diff_children(std::slice::from_ref(&self.content));
408    }
409
410    fn size(&self) -> Size<Length> {
411        Size {
412            width: self.width,
413            height: self.height,
414        }
415    }
416
417    fn layout(
418        &mut self,
419        tree: &mut Tree,
420        renderer: &Renderer,
421        limits: &layout::Limits,
422    ) -> layout::Node {
423        let mut layout = |right_padding, bottom_padding| {
424            layout::padded(
425                limits,
426                self.width,
427                self.height,
428                Padding {
429                    right: right_padding,
430                    bottom: bottom_padding,
431                    ..Padding::ZERO
432                },
433                |limits| {
434                    let is_horizontal = self.direction.horizontal().is_some();
435                    let is_vertical = self.direction.vertical().is_some();
436
437                    let child_limits = layout::Limits::with_compression(
438                        limits.min(),
439                        Size::new(
440                            if is_horizontal {
441                                f32::INFINITY
442                            } else {
443                                limits.max().width
444                            },
445                            if is_vertical {
446                                f32::INFINITY
447                            } else {
448                                limits.max().height
449                            },
450                        ),
451                        Size::new(is_horizontal, is_vertical),
452                    );
453
454                    self.content.as_widget_mut().layout(
455                        &mut tree.children[0],
456                        renderer,
457                        &child_limits,
458                    )
459                },
460            )
461        };
462
463        match self.direction {
464            Direction::Vertical(Scrollbar {
465                width,
466                margin,
467                spacing: Some(spacing),
468                ..
469            })
470            | Direction::Horizontal(Scrollbar {
471                width,
472                margin,
473                spacing: Some(spacing),
474                ..
475            }) => {
476                let is_vertical = matches!(self.direction, Direction::Vertical(_));
477
478                let padding = width + margin * 2.0 + spacing;
479                let state = tree.state.downcast_mut::<State>();
480
481                let status_quo = layout(
482                    if is_vertical && state.is_scrollbar_visible {
483                        padding
484                    } else {
485                        0.0
486                    },
487                    if !is_vertical && state.is_scrollbar_visible {
488                        padding
489                    } else {
490                        0.0
491                    },
492                );
493
494                let is_scrollbar_visible = if is_vertical {
495                    status_quo.children()[0].size().height > status_quo.size().height
496                } else {
497                    status_quo.children()[0].size().width > status_quo.size().width
498                };
499
500                if state.is_scrollbar_visible == is_scrollbar_visible {
501                    status_quo
502                } else {
503                    log::trace!("Scrollbar status quo has changed");
504                    state.is_scrollbar_visible = is_scrollbar_visible;
505
506                    layout(
507                        if is_vertical && state.is_scrollbar_visible {
508                            padding
509                        } else {
510                            0.0
511                        },
512                        if !is_vertical && state.is_scrollbar_visible {
513                            padding
514                        } else {
515                            0.0
516                        },
517                    )
518                }
519            }
520            _ => layout(0.0, 0.0),
521        }
522    }
523
524    fn operate(
525        &mut self,
526        tree: &mut Tree,
527        layout: Layout<'_>,
528        renderer: &Renderer,
529        operation: &mut dyn Operation,
530    ) {
531        let state = tree.state.downcast_mut::<State>();
532
533        let bounds = layout.bounds();
534        let content_layout = layout.children().next().unwrap();
535        let content_bounds = content_layout.bounds();
536        let translation = state.translation(self.direction, bounds, content_bounds);
537
538        operation.scrollable(self.id.as_ref(), bounds, content_bounds, translation, state);
539
540        operation.traverse(&mut |operation| {
541            self.content.as_widget_mut().operate(
542                &mut tree.children[0],
543                layout.children().next().unwrap(),
544                renderer,
545                operation,
546            );
547        });
548    }
549
550    fn update(
551        &mut self,
552        tree: &mut Tree,
553        event: &Event,
554        layout: Layout<'_>,
555        cursor: mouse::Cursor,
556        renderer: &Renderer,
557        clipboard: &mut dyn Clipboard,
558        shell: &mut Shell<'_, Message>,
559        _viewport: &Rectangle,
560    ) {
561        const AUTOSCROLL_DEADZONE: f32 = 20.0;
562        const AUTOSCROLL_SMOOTHNESS: f32 = 1.5;
563
564        let state = tree.state.downcast_mut::<State>();
565        let bounds = layout.bounds();
566        let cursor_over_scrollable = cursor.position_over(bounds);
567
568        let content = layout.children().next().unwrap();
569        let content_bounds = content.bounds();
570
571        let scrollbars = Scrollbars::new(state, self.direction, bounds, content_bounds);
572
573        let (mouse_over_y_scrollbar, mouse_over_x_scrollbar) = scrollbars.is_mouse_over(cursor);
574
575        let last_offsets = (state.offset_x, state.offset_y);
576
577        if let Some(last_scrolled) = state.last_scrolled {
578            let clear_transaction = match event {
579                Event::Mouse(
580                    mouse::Event::ButtonPressed(_)
581                    | mouse::Event::ButtonReleased(_)
582                    | mouse::Event::CursorLeft,
583                ) => true,
584                Event::Mouse(mouse::Event::CursorMoved { .. }) => {
585                    last_scrolled.elapsed() > Duration::from_millis(100)
586                }
587                _ => last_scrolled.elapsed() > Duration::from_millis(1500),
588            };
589
590            if clear_transaction {
591                state.last_scrolled = None;
592            }
593        }
594
595        let mut update = || {
596            if let Some(scroller_grabbed_at) = state.y_scroller_grabbed_at() {
597                match event {
598                    Event::Mouse(mouse::Event::CursorMoved { .. })
599                    | Event::Touch(touch::Event::FingerMoved { .. }) => {
600                        if let Some(scrollbar) = scrollbars.y {
601                            let Some(cursor_position) = cursor.land().position() else {
602                                return;
603                            };
604
605                            state.scroll_y_to(
606                                scrollbar.scroll_percentage_y(scroller_grabbed_at, cursor_position),
607                                bounds,
608                                content_bounds,
609                            );
610
611                            let _ = notify_scroll(
612                                state,
613                                &self.on_scroll,
614                                bounds,
615                                content_bounds,
616                                shell,
617                            );
618
619                            shell.capture_event();
620                        }
621                    }
622                    _ => {}
623                }
624            } else if mouse_over_y_scrollbar {
625                match event {
626                    Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left))
627                    | Event::Touch(touch::Event::FingerPressed { .. }) => {
628                        let Some(cursor_position) = cursor.position() else {
629                            return;
630                        };
631
632                        if let (Some(scroller_grabbed_at), Some(scrollbar)) =
633                            (scrollbars.grab_y_scroller(cursor_position), scrollbars.y)
634                        {
635                            state.scroll_y_to(
636                                scrollbar.scroll_percentage_y(scroller_grabbed_at, cursor_position),
637                                bounds,
638                                content_bounds,
639                            );
640
641                            state.interaction = Interaction::YScrollerGrabbed(scroller_grabbed_at);
642
643                            let _ = notify_scroll(
644                                state,
645                                &self.on_scroll,
646                                bounds,
647                                content_bounds,
648                                shell,
649                            );
650                        }
651
652                        shell.capture_event();
653                    }
654                    _ => {}
655                }
656            }
657
658            if let Some(scroller_grabbed_at) = state.x_scroller_grabbed_at() {
659                match event {
660                    Event::Mouse(mouse::Event::CursorMoved { .. })
661                    | Event::Touch(touch::Event::FingerMoved { .. }) => {
662                        let Some(cursor_position) = cursor.land().position() else {
663                            return;
664                        };
665
666                        if let Some(scrollbar) = scrollbars.x {
667                            state.scroll_x_to(
668                                scrollbar.scroll_percentage_x(scroller_grabbed_at, cursor_position),
669                                bounds,
670                                content_bounds,
671                            );
672
673                            let _ = notify_scroll(
674                                state,
675                                &self.on_scroll,
676                                bounds,
677                                content_bounds,
678                                shell,
679                            );
680                        }
681
682                        shell.capture_event();
683                    }
684                    _ => {}
685                }
686            } else if mouse_over_x_scrollbar {
687                match event {
688                    Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left))
689                    | Event::Touch(touch::Event::FingerPressed { .. }) => {
690                        let Some(cursor_position) = cursor.position() else {
691                            return;
692                        };
693
694                        if let (Some(scroller_grabbed_at), Some(scrollbar)) =
695                            (scrollbars.grab_x_scroller(cursor_position), scrollbars.x)
696                        {
697                            state.scroll_x_to(
698                                scrollbar.scroll_percentage_x(scroller_grabbed_at, cursor_position),
699                                bounds,
700                                content_bounds,
701                            );
702
703                            state.interaction = Interaction::XScrollerGrabbed(scroller_grabbed_at);
704
705                            let _ = notify_scroll(
706                                state,
707                                &self.on_scroll,
708                                bounds,
709                                content_bounds,
710                                shell,
711                            );
712
713                            shell.capture_event();
714                        }
715                    }
716                    _ => {}
717                }
718            }
719
720            if matches!(state.interaction, Interaction::AutoScrolling { .. })
721                && matches!(
722                    event,
723                    Event::Mouse(
724                        mouse::Event::ButtonPressed(_) | mouse::Event::WheelScrolled { .. }
725                    ) | Event::Touch(_)
726                        | Event::Keyboard(_)
727                )
728            {
729                state.interaction = Interaction::None;
730                shell.capture_event();
731                shell.invalidate_layout();
732                shell.request_redraw();
733                return;
734            }
735
736            if state.last_scrolled.is_none()
737                || !matches!(event, Event::Mouse(mouse::Event::WheelScrolled { .. }))
738            {
739                let translation = state.translation(self.direction, bounds, content_bounds);
740
741                let cursor = match cursor_over_scrollable {
742                    Some(cursor_position)
743                        if !(mouse_over_x_scrollbar || mouse_over_y_scrollbar) =>
744                    {
745                        mouse::Cursor::Available(cursor_position + translation)
746                    }
747                    _ => cursor.levitate() + translation,
748                };
749
750                let had_input_method = shell.input_method().is_enabled();
751
752                self.content.as_widget_mut().update(
753                    &mut tree.children[0],
754                    event,
755                    content,
756                    cursor,
757                    renderer,
758                    clipboard,
759                    shell,
760                    &Rectangle {
761                        y: bounds.y + translation.y,
762                        x: bounds.x + translation.x,
763                        ..bounds
764                    },
765                );
766
767                if !had_input_method
768                    && let InputMethod::Enabled { cursor, .. } = shell.input_method_mut()
769                {
770                    *cursor = *cursor - translation;
771                }
772            };
773
774            if matches!(
775                event,
776                Event::Mouse(mouse::Event::ButtonReleased(mouse::Button::Left))
777                    | Event::Touch(
778                        touch::Event::FingerLifted { .. } | touch::Event::FingerLost { .. }
779                    )
780            ) {
781                state.interaction = Interaction::None;
782                return;
783            }
784
785            if shell.is_event_captured() {
786                return;
787            }
788
789            match event {
790                Event::Mouse(mouse::Event::WheelScrolled { delta }) => {
791                    if cursor_over_scrollable.is_none() {
792                        return;
793                    }
794
795                    let delta = match *delta {
796                        mouse::ScrollDelta::Lines { x, y } => {
797                            let is_shift_pressed = state.keyboard_modifiers.shift();
798
799                            // macOS automatically inverts the axes when Shift is pressed
800                            let (x, y) = if cfg!(target_os = "macos") && is_shift_pressed {
801                                (y, x)
802                            } else {
803                                (x, y)
804                            };
805
806                            let movement = if !is_shift_pressed {
807                                Vector::new(x, y)
808                            } else {
809                                Vector::new(y, x)
810                            };
811
812                            // TODO: Configurable speed/friction (?)
813                            -movement * 60.0
814                        }
815                        mouse::ScrollDelta::Pixels { x, y } => -Vector::new(x, y),
816                    };
817
818                    state.scroll(self.direction.align(delta), bounds, content_bounds);
819
820                    let has_scrolled =
821                        notify_scroll(state, &self.on_scroll, bounds, content_bounds, shell);
822
823                    let in_transaction = state.last_scrolled.is_some();
824
825                    if has_scrolled || in_transaction {
826                        shell.capture_event();
827                    }
828                }
829                Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Middle))
830                    if self.auto_scroll && matches!(state.interaction, Interaction::None) =>
831                {
832                    let Some(origin) = cursor_over_scrollable else {
833                        return;
834                    };
835
836                    state.interaction = Interaction::AutoScrolling {
837                        origin,
838                        current: origin,
839                        last_frame: None,
840                    };
841
842                    shell.capture_event();
843                    shell.invalidate_layout();
844                    shell.request_redraw();
845                }
846                Event::Touch(event)
847                    if matches!(state.interaction, Interaction::TouchScrolling(_))
848                        || (!mouse_over_y_scrollbar && !mouse_over_x_scrollbar) =>
849                {
850                    match event {
851                        touch::Event::FingerPressed { .. } => {
852                            let Some(position) = cursor_over_scrollable else {
853                                return;
854                            };
855
856                            state.interaction = Interaction::TouchScrolling(position);
857                        }
858                        touch::Event::FingerMoved { .. } => {
859                            let Interaction::TouchScrolling(scroll_box_touched_at) =
860                                state.interaction
861                            else {
862                                return;
863                            };
864
865                            let Some(cursor_position) = cursor.position() else {
866                                return;
867                            };
868
869                            let delta = Vector::new(
870                                scroll_box_touched_at.x - cursor_position.x,
871                                scroll_box_touched_at.y - cursor_position.y,
872                            );
873
874                            state.scroll(self.direction.align(delta), bounds, content_bounds);
875
876                            state.interaction = Interaction::TouchScrolling(cursor_position);
877
878                            // TODO: bubble up touch movements if not consumed.
879                            let _ = notify_scroll(
880                                state,
881                                &self.on_scroll,
882                                bounds,
883                                content_bounds,
884                                shell,
885                            );
886                        }
887                        _ => {}
888                    }
889
890                    shell.capture_event();
891                }
892                Event::Mouse(mouse::Event::CursorMoved { position }) => {
893                    if let Interaction::AutoScrolling {
894                        origin, last_frame, ..
895                    } = state.interaction
896                    {
897                        let delta = *position - origin;
898
899                        state.interaction = Interaction::AutoScrolling {
900                            origin,
901                            current: *position,
902                            last_frame,
903                        };
904
905                        if (delta.x.abs() >= AUTOSCROLL_DEADZONE
906                            || delta.y.abs() >= AUTOSCROLL_DEADZONE)
907                            && last_frame.is_none()
908                        {
909                            shell.request_redraw();
910                        }
911                    }
912                }
913                Event::Keyboard(keyboard::Event::ModifiersChanged(modifiers)) => {
914                    state.keyboard_modifiers = *modifiers;
915                }
916                Event::Window(window::Event::RedrawRequested(now)) => {
917                    if let Interaction::AutoScrolling {
918                        origin,
919                        current,
920                        last_frame,
921                    } = state.interaction
922                    {
923                        if last_frame == Some(*now) {
924                            shell.request_redraw();
925                            return;
926                        }
927
928                        state.interaction = Interaction::AutoScrolling {
929                            origin,
930                            current,
931                            last_frame: None,
932                        };
933
934                        let mut delta = current - origin;
935
936                        if delta.x.abs() < AUTOSCROLL_DEADZONE {
937                            delta.x = 0.0;
938                        }
939
940                        if delta.y.abs() < AUTOSCROLL_DEADZONE {
941                            delta.y = 0.0;
942                        }
943
944                        if delta.x != 0.0 || delta.y != 0.0 {
945                            let time_delta = if let Some(last_frame) = last_frame {
946                                *now - last_frame
947                            } else {
948                                Duration::ZERO
949                            };
950
951                            let scroll_factor = time_delta.as_secs_f32();
952
953                            state.scroll(
954                                self.direction.align(Vector::new(
955                                    delta.x.signum()
956                                        * delta.x.abs().powf(AUTOSCROLL_SMOOTHNESS)
957                                        * scroll_factor,
958                                    delta.y.signum()
959                                        * delta.y.abs().powf(AUTOSCROLL_SMOOTHNESS)
960                                        * scroll_factor,
961                                )),
962                                bounds,
963                                content_bounds,
964                            );
965
966                            let has_scrolled = notify_scroll(
967                                state,
968                                &self.on_scroll,
969                                bounds,
970                                content_bounds,
971                                shell,
972                            );
973
974                            if has_scrolled || time_delta.is_zero() {
975                                state.interaction = Interaction::AutoScrolling {
976                                    origin,
977                                    current,
978                                    last_frame: Some(*now),
979                                };
980
981                                shell.request_redraw();
982                            }
983
984                            return;
985                        }
986                    }
987
988                    let _ = notify_viewport(state, &self.on_scroll, bounds, content_bounds, shell);
989                }
990                _ => {}
991            }
992        };
993
994        update();
995
996        let status = if state.scrollers_grabbed() {
997            Status::Dragged {
998                is_horizontal_scrollbar_dragged: state.x_scroller_grabbed_at().is_some(),
999                is_vertical_scrollbar_dragged: state.y_scroller_grabbed_at().is_some(),
1000                is_horizontal_scrollbar_disabled: scrollbars.is_x_disabled(),
1001                is_vertical_scrollbar_disabled: scrollbars.is_y_disabled(),
1002            }
1003        } else if cursor_over_scrollable.is_some() {
1004            Status::Hovered {
1005                is_horizontal_scrollbar_hovered: mouse_over_x_scrollbar,
1006                is_vertical_scrollbar_hovered: mouse_over_y_scrollbar,
1007                is_horizontal_scrollbar_disabled: scrollbars.is_x_disabled(),
1008                is_vertical_scrollbar_disabled: scrollbars.is_y_disabled(),
1009            }
1010        } else {
1011            Status::Active {
1012                is_horizontal_scrollbar_disabled: scrollbars.is_x_disabled(),
1013                is_vertical_scrollbar_disabled: scrollbars.is_y_disabled(),
1014            }
1015        };
1016
1017        if let Event::Window(window::Event::RedrawRequested(_now)) = event {
1018            self.last_status = Some(status);
1019        }
1020
1021        if last_offsets != (state.offset_x, state.offset_y)
1022            || self
1023                .last_status
1024                .is_some_and(|last_status| last_status != status)
1025        {
1026            shell.request_redraw();
1027        }
1028    }
1029
1030    fn draw(
1031        &self,
1032        tree: &Tree,
1033        renderer: &mut Renderer,
1034        theme: &Theme,
1035        defaults: &renderer::Style,
1036        layout: Layout<'_>,
1037        cursor: mouse::Cursor,
1038        viewport: &Rectangle,
1039    ) {
1040        let state = tree.state.downcast_ref::<State>();
1041
1042        let bounds = layout.bounds();
1043        let content_layout = layout.children().next().unwrap();
1044        let content_bounds = content_layout.bounds();
1045
1046        let Some(visible_bounds) = bounds.intersection(viewport) else {
1047            return;
1048        };
1049
1050        let scrollbars = Scrollbars::new(state, self.direction, bounds, content_bounds);
1051
1052        let cursor_over_scrollable = cursor.position_over(bounds);
1053        let (mouse_over_y_scrollbar, mouse_over_x_scrollbar) = scrollbars.is_mouse_over(cursor);
1054
1055        let translation = state.translation(self.direction, bounds, content_bounds);
1056
1057        let cursor = match cursor_over_scrollable {
1058            Some(cursor_position) if !(mouse_over_x_scrollbar || mouse_over_y_scrollbar) => {
1059                mouse::Cursor::Available(cursor_position + translation)
1060            }
1061            _ => mouse::Cursor::Unavailable,
1062        };
1063
1064        let style = theme.style(
1065            &self.class,
1066            self.last_status.unwrap_or(Status::Active {
1067                is_horizontal_scrollbar_disabled: false,
1068                is_vertical_scrollbar_disabled: false,
1069            }),
1070        );
1071
1072        container::draw_background(renderer, &style.container, layout.bounds());
1073
1074        // Draw inner content
1075        if scrollbars.active() {
1076            renderer.with_layer(visible_bounds, |renderer| {
1077                renderer.with_translation(
1078                    Vector::new(-translation.x, -translation.y),
1079                    |renderer| {
1080                        self.content.as_widget().draw(
1081                            &tree.children[0],
1082                            renderer,
1083                            theme,
1084                            defaults,
1085                            content_layout,
1086                            cursor,
1087                            &Rectangle {
1088                                y: visible_bounds.y + translation.y,
1089                                x: visible_bounds.x + translation.x,
1090                                ..visible_bounds
1091                            },
1092                        );
1093                    },
1094                );
1095            });
1096
1097            let draw_scrollbar =
1098                |renderer: &mut Renderer, style: Rail, scrollbar: &internals::Scrollbar| {
1099                    if scrollbar.bounds.width > 0.0
1100                        && scrollbar.bounds.height > 0.0
1101                        && (style.background.is_some()
1102                            || (style.border.color != Color::TRANSPARENT
1103                                && style.border.width > 0.0))
1104                    {
1105                        renderer.fill_quad(
1106                            renderer::Quad {
1107                                bounds: scrollbar.bounds,
1108                                border: style.border,
1109                                ..renderer::Quad::default()
1110                            },
1111                            style
1112                                .background
1113                                .unwrap_or(Background::Color(Color::TRANSPARENT)),
1114                        );
1115                    }
1116
1117                    if let Some(scroller) = scrollbar.scroller
1118                        && scroller.bounds.width > 0.0
1119                        && scroller.bounds.height > 0.0
1120                        && (style.scroller.background != Background::Color(Color::TRANSPARENT)
1121                            || (style.scroller.border.color != Color::TRANSPARENT
1122                                && style.scroller.border.width > 0.0))
1123                    {
1124                        renderer.fill_quad(
1125                            renderer::Quad {
1126                                bounds: scroller.bounds,
1127                                border: style.scroller.border,
1128                                ..renderer::Quad::default()
1129                            },
1130                            style.scroller.background,
1131                        );
1132                    }
1133                };
1134
1135            renderer.with_layer(
1136                Rectangle {
1137                    width: (visible_bounds.width + 2.0).min(viewport.width),
1138                    height: (visible_bounds.height + 2.0).min(viewport.height),
1139                    ..visible_bounds
1140                },
1141                |renderer| {
1142                    if let Some(scrollbar) = scrollbars.y {
1143                        draw_scrollbar(renderer, style.vertical_rail, &scrollbar);
1144                    }
1145
1146                    if let Some(scrollbar) = scrollbars.x {
1147                        draw_scrollbar(renderer, style.horizontal_rail, &scrollbar);
1148                    }
1149
1150                    if let (Some(x), Some(y)) = (scrollbars.x, scrollbars.y) {
1151                        let background = style.gap.or(style.container.background);
1152
1153                        if let Some(background) = background {
1154                            renderer.fill_quad(
1155                                renderer::Quad {
1156                                    bounds: Rectangle {
1157                                        x: y.bounds.x,
1158                                        y: x.bounds.y,
1159                                        width: y.bounds.width,
1160                                        height: x.bounds.height,
1161                                    },
1162                                    ..renderer::Quad::default()
1163                                },
1164                                background,
1165                            );
1166                        }
1167                    }
1168                },
1169            );
1170        } else {
1171            self.content.as_widget().draw(
1172                &tree.children[0],
1173                renderer,
1174                theme,
1175                defaults,
1176                content_layout,
1177                cursor,
1178                &Rectangle {
1179                    x: visible_bounds.x + translation.x,
1180                    y: visible_bounds.y + translation.y,
1181                    ..visible_bounds
1182                },
1183            );
1184        }
1185    }
1186
1187    fn mouse_interaction(
1188        &self,
1189        tree: &Tree,
1190        layout: Layout<'_>,
1191        cursor: mouse::Cursor,
1192        _viewport: &Rectangle,
1193        renderer: &Renderer,
1194    ) -> mouse::Interaction {
1195        let state = tree.state.downcast_ref::<State>();
1196        let bounds = layout.bounds();
1197        let cursor_over_scrollable = cursor.position_over(bounds);
1198
1199        let content_layout = layout.children().next().unwrap();
1200        let content_bounds = content_layout.bounds();
1201
1202        let scrollbars = Scrollbars::new(state, self.direction, bounds, content_bounds);
1203
1204        let (mouse_over_y_scrollbar, mouse_over_x_scrollbar) = scrollbars.is_mouse_over(cursor);
1205
1206        if state.scrollers_grabbed() {
1207            return mouse::Interaction::None;
1208        }
1209
1210        let translation = state.translation(self.direction, bounds, content_bounds);
1211
1212        let cursor = match cursor_over_scrollable {
1213            Some(cursor_position) if !(mouse_over_x_scrollbar || mouse_over_y_scrollbar) => {
1214                mouse::Cursor::Available(cursor_position + translation)
1215            }
1216            _ => cursor.levitate() + translation,
1217        };
1218
1219        self.content.as_widget().mouse_interaction(
1220            &tree.children[0],
1221            content_layout,
1222            cursor,
1223            &Rectangle {
1224                y: bounds.y + translation.y,
1225                x: bounds.x + translation.x,
1226                ..bounds
1227            },
1228            renderer,
1229        )
1230    }
1231
1232    fn overlay<'b>(
1233        &'b mut self,
1234        tree: &'b mut Tree,
1235        layout: Layout<'b>,
1236        renderer: &Renderer,
1237        viewport: &Rectangle,
1238        translation: Vector,
1239    ) -> Option<overlay::Element<'b, Message, Theme, Renderer>> {
1240        let state = tree.state.downcast_ref::<State>();
1241        let bounds = layout.bounds();
1242        let content_layout = layout.children().next().unwrap();
1243        let content_bounds = content_layout.bounds();
1244        let visible_bounds = bounds.intersection(viewport).unwrap_or(*viewport);
1245        let offset = state.translation(self.direction, bounds, content_bounds);
1246
1247        let overlay = self.content.as_widget_mut().overlay(
1248            &mut tree.children[0],
1249            layout.children().next().unwrap(),
1250            renderer,
1251            &visible_bounds,
1252            translation - offset,
1253        );
1254
1255        let icon = if let Interaction::AutoScrolling { origin, .. } = state.interaction {
1256            let scrollbars = Scrollbars::new(state, self.direction, bounds, content_bounds);
1257
1258            Some(overlay::Element::new(Box::new(AutoScrollIcon {
1259                origin,
1260                vertical: scrollbars.y.is_some(),
1261                horizontal: scrollbars.x.is_some(),
1262                class: &self.class,
1263            })))
1264        } else {
1265            None
1266        };
1267
1268        match (overlay, icon) {
1269            (None, None) => None,
1270            (None, Some(icon)) => Some(icon),
1271            (Some(overlay), None) => Some(overlay),
1272            (Some(overlay), Some(icon)) => Some(overlay::Element::new(Box::new(
1273                overlay::Group::with_children(vec![overlay, icon]),
1274            ))),
1275        }
1276    }
1277}
1278
1279struct AutoScrollIcon<'a, Class> {
1280    origin: Point,
1281    vertical: bool,
1282    horizontal: bool,
1283    class: &'a Class,
1284}
1285
1286impl<Class> AutoScrollIcon<'_, Class> {
1287    const SIZE: f32 = 40.0;
1288    const DOT: f32 = Self::SIZE / 10.0;
1289    const PADDING: f32 = Self::SIZE / 10.0;
1290}
1291
1292impl<Message, Theme, Renderer> core::Overlay<Message, Theme, Renderer>
1293    for AutoScrollIcon<'_, Theme::Class<'_>>
1294where
1295    Renderer: text::Renderer,
1296    Theme: Catalog,
1297{
1298    fn layout(&mut self, _renderer: &Renderer, _bounds: Size) -> layout::Node {
1299        layout::Node::new(Size::new(Self::SIZE, Self::SIZE))
1300            .move_to(self.origin - Vector::new(Self::SIZE, Self::SIZE) / 2.0)
1301    }
1302
1303    fn draw(
1304        &self,
1305        renderer: &mut Renderer,
1306        theme: &Theme,
1307        _style: &renderer::Style,
1308        layout: Layout<'_>,
1309        _cursor: mouse::Cursor,
1310    ) {
1311        let bounds = layout.bounds();
1312        let style = theme
1313            .style(
1314                self.class,
1315                Status::Active {
1316                    is_horizontal_scrollbar_disabled: false,
1317                    is_vertical_scrollbar_disabled: false,
1318                },
1319            )
1320            .auto_scroll;
1321
1322        renderer.with_layer(Rectangle::INFINITE, |renderer| {
1323            renderer.fill_quad(
1324                renderer::Quad {
1325                    bounds,
1326                    border: style.border,
1327                    shadow: style.shadow,
1328                    snap: false,
1329                },
1330                style.background,
1331            );
1332
1333            renderer.fill_quad(
1334                renderer::Quad {
1335                    bounds: Rectangle::new(
1336                        bounds.center() - Vector::new(Self::DOT, Self::DOT) / 2.0,
1337                        Size::new(Self::DOT, Self::DOT),
1338                    ),
1339                    border: border::rounded(bounds.width),
1340                    snap: false,
1341                    ..renderer::Quad::default()
1342                },
1343                style.icon,
1344            );
1345
1346            let arrow = core::Text {
1347                content: String::new(),
1348                bounds: bounds.size(),
1349                size: Pixels::from(12),
1350                line_height: text::LineHeight::Relative(1.0),
1351                font: Renderer::ICON_FONT,
1352                align_x: text::Alignment::Center,
1353                align_y: alignment::Vertical::Center,
1354                shaping: text::Shaping::Basic,
1355                wrapping: text::Wrapping::None,
1356            };
1357
1358            if self.vertical {
1359                renderer.fill_text(
1360                    core::Text {
1361                        content: Renderer::SCROLL_UP_ICON.to_string(),
1362                        align_y: alignment::Vertical::Top,
1363                        ..arrow
1364                    },
1365                    Point::new(bounds.center_x(), bounds.y + Self::PADDING),
1366                    style.icon,
1367                    bounds,
1368                );
1369
1370                renderer.fill_text(
1371                    core::Text {
1372                        content: Renderer::SCROLL_DOWN_ICON.to_string(),
1373                        align_y: alignment::Vertical::Bottom,
1374                        ..arrow
1375                    },
1376                    Point::new(
1377                        bounds.center_x(),
1378                        bounds.y + bounds.height - Self::PADDING - 0.5,
1379                    ),
1380                    style.icon,
1381                    bounds,
1382                );
1383            }
1384
1385            if self.horizontal {
1386                renderer.fill_text(
1387                    core::Text {
1388                        content: Renderer::SCROLL_LEFT_ICON.to_string(),
1389                        align_x: text::Alignment::Left,
1390                        ..arrow
1391                    },
1392                    Point::new(bounds.x + Self::PADDING + 1.0, bounds.center_y() + 1.0),
1393                    style.icon,
1394                    bounds,
1395                );
1396
1397                renderer.fill_text(
1398                    core::Text {
1399                        content: Renderer::SCROLL_RIGHT_ICON.to_string(),
1400                        align_x: text::Alignment::Right,
1401                        ..arrow
1402                    },
1403                    Point::new(
1404                        bounds.x + bounds.width - Self::PADDING - 1.0,
1405                        bounds.center_y() + 1.0,
1406                    ),
1407                    style.icon,
1408                    bounds,
1409                );
1410            }
1411        });
1412    }
1413
1414    fn index(&self) -> f32 {
1415        f32::MAX
1416    }
1417}
1418
1419impl<'a, Message, Theme, Renderer> From<Scrollable<'a, Message, Theme, Renderer>>
1420    for Element<'a, Message, Theme, Renderer>
1421where
1422    Message: 'a,
1423    Theme: 'a + Catalog,
1424    Renderer: 'a + text::Renderer,
1425{
1426    fn from(
1427        text_input: Scrollable<'a, Message, Theme, Renderer>,
1428    ) -> Element<'a, Message, Theme, Renderer> {
1429        Element::new(text_input)
1430    }
1431}
1432
1433fn notify_scroll<Message>(
1434    state: &mut State,
1435    on_scroll: &Option<Box<dyn Fn(Viewport) -> Message + '_>>,
1436    bounds: Rectangle,
1437    content_bounds: Rectangle,
1438    shell: &mut Shell<'_, Message>,
1439) -> bool {
1440    if notify_viewport(state, on_scroll, bounds, content_bounds, shell) {
1441        state.last_scrolled = Some(Instant::now());
1442
1443        true
1444    } else {
1445        false
1446    }
1447}
1448
1449fn notify_viewport<Message>(
1450    state: &mut State,
1451    on_scroll: &Option<Box<dyn Fn(Viewport) -> Message + '_>>,
1452    bounds: Rectangle,
1453    content_bounds: Rectangle,
1454    shell: &mut Shell<'_, Message>,
1455) -> bool {
1456    if content_bounds.width <= bounds.width && content_bounds.height <= bounds.height {
1457        return false;
1458    }
1459
1460    let viewport = Viewport {
1461        offset_x: state.offset_x,
1462        offset_y: state.offset_y,
1463        bounds,
1464        content_bounds,
1465    };
1466
1467    // Don't publish redundant viewports to shell
1468    if let Some(last_notified) = state.last_notified {
1469        let last_relative_offset = last_notified.relative_offset();
1470        let current_relative_offset = viewport.relative_offset();
1471
1472        let last_absolute_offset = last_notified.absolute_offset();
1473        let current_absolute_offset = viewport.absolute_offset();
1474
1475        let unchanged =
1476            |a: f32, b: f32| (a - b).abs() <= f32::EPSILON || (a.is_nan() && b.is_nan());
1477
1478        if last_notified.bounds == bounds
1479            && last_notified.content_bounds == content_bounds
1480            && unchanged(last_relative_offset.x, current_relative_offset.x)
1481            && unchanged(last_relative_offset.y, current_relative_offset.y)
1482            && unchanged(last_absolute_offset.x, current_absolute_offset.x)
1483            && unchanged(last_absolute_offset.y, current_absolute_offset.y)
1484        {
1485            return false;
1486        }
1487    }
1488
1489    state.last_notified = Some(viewport);
1490
1491    if let Some(on_scroll) = on_scroll {
1492        shell.publish(on_scroll(viewport));
1493    }
1494
1495    true
1496}
1497
1498#[derive(Debug, Clone, Copy)]
1499struct State {
1500    offset_y: Offset,
1501    offset_x: Offset,
1502    interaction: Interaction,
1503    keyboard_modifiers: keyboard::Modifiers,
1504    last_notified: Option<Viewport>,
1505    last_scrolled: Option<Instant>,
1506    is_scrollbar_visible: bool,
1507}
1508
1509#[derive(Debug, Clone, Copy)]
1510enum Interaction {
1511    None,
1512    YScrollerGrabbed(f32),
1513    XScrollerGrabbed(f32),
1514    TouchScrolling(Point),
1515    AutoScrolling {
1516        origin: Point,
1517        current: Point,
1518        last_frame: Option<Instant>,
1519    },
1520}
1521
1522impl Default for State {
1523    fn default() -> Self {
1524        Self {
1525            offset_y: Offset::Absolute(0.0),
1526            offset_x: Offset::Absolute(0.0),
1527            interaction: Interaction::None,
1528            keyboard_modifiers: keyboard::Modifiers::default(),
1529            last_notified: None,
1530            last_scrolled: None,
1531            is_scrollbar_visible: true,
1532        }
1533    }
1534}
1535
1536impl operation::Scrollable for State {
1537    fn snap_to(&mut self, offset: RelativeOffset<Option<f32>>) {
1538        State::snap_to(self, offset);
1539    }
1540
1541    fn scroll_to(&mut self, offset: AbsoluteOffset<Option<f32>>) {
1542        State::scroll_to(self, offset);
1543    }
1544
1545    fn scroll_by(&mut self, offset: AbsoluteOffset, bounds: Rectangle, content_bounds: Rectangle) {
1546        State::scroll_by(self, offset, bounds, content_bounds);
1547    }
1548}
1549
1550#[derive(Debug, Clone, Copy, PartialEq)]
1551enum Offset {
1552    Absolute(f32),
1553    Relative(f32),
1554}
1555
1556impl Offset {
1557    fn absolute(self, viewport: f32, content: f32) -> f32 {
1558        match self {
1559            Offset::Absolute(absolute) => absolute.min((content - viewport).max(0.0)),
1560            Offset::Relative(percentage) => ((content - viewport) * percentage).max(0.0),
1561        }
1562    }
1563
1564    fn translation(self, viewport: f32, content: f32, alignment: Anchor) -> f32 {
1565        let offset = self.absolute(viewport, content);
1566
1567        match alignment {
1568            Anchor::Start => offset,
1569            Anchor::End => ((content - viewport).max(0.0) - offset).max(0.0),
1570        }
1571    }
1572}
1573
1574/// The current [`Viewport`] of the [`Scrollable`].
1575#[derive(Debug, Clone, Copy)]
1576pub struct Viewport {
1577    offset_x: Offset,
1578    offset_y: Offset,
1579    bounds: Rectangle,
1580    content_bounds: Rectangle,
1581}
1582
1583impl Viewport {
1584    /// Returns the [`AbsoluteOffset`] of the current [`Viewport`].
1585    pub fn absolute_offset(&self) -> AbsoluteOffset {
1586        let x = self
1587            .offset_x
1588            .absolute(self.bounds.width, self.content_bounds.width);
1589        let y = self
1590            .offset_y
1591            .absolute(self.bounds.height, self.content_bounds.height);
1592
1593        AbsoluteOffset { x, y }
1594    }
1595
1596    /// Returns the [`AbsoluteOffset`] of the current [`Viewport`], but with its
1597    /// alignment reversed.
1598    ///
1599    /// This method can be useful to switch the alignment of a [`Scrollable`]
1600    /// while maintaining its scrolling position.
1601    pub fn absolute_offset_reversed(&self) -> AbsoluteOffset {
1602        let AbsoluteOffset { x, y } = self.absolute_offset();
1603
1604        AbsoluteOffset {
1605            x: (self.content_bounds.width - self.bounds.width).max(0.0) - x,
1606            y: (self.content_bounds.height - self.bounds.height).max(0.0) - y,
1607        }
1608    }
1609
1610    /// Returns the [`RelativeOffset`] of the current [`Viewport`].
1611    pub fn relative_offset(&self) -> RelativeOffset {
1612        let AbsoluteOffset { x, y } = self.absolute_offset();
1613
1614        let x = x / (self.content_bounds.width - self.bounds.width);
1615        let y = y / (self.content_bounds.height - self.bounds.height);
1616
1617        RelativeOffset { x, y }
1618    }
1619
1620    /// Returns the bounds of the current [`Viewport`].
1621    pub fn bounds(&self) -> Rectangle {
1622        self.bounds
1623    }
1624
1625    /// Returns the content bounds of the current [`Viewport`].
1626    pub fn content_bounds(&self) -> Rectangle {
1627        self.content_bounds
1628    }
1629}
1630
1631impl State {
1632    fn new() -> Self {
1633        State::default()
1634    }
1635
1636    fn scroll(&mut self, delta: Vector<f32>, bounds: Rectangle, content_bounds: Rectangle) {
1637        if bounds.height < content_bounds.height {
1638            self.offset_y = Offset::Absolute(
1639                (self.offset_y.absolute(bounds.height, content_bounds.height) + delta.y)
1640                    .clamp(0.0, content_bounds.height - bounds.height),
1641            );
1642        }
1643
1644        if bounds.width < content_bounds.width {
1645            self.offset_x = Offset::Absolute(
1646                (self.offset_x.absolute(bounds.width, content_bounds.width) + delta.x)
1647                    .clamp(0.0, content_bounds.width - bounds.width),
1648            );
1649        }
1650    }
1651
1652    fn scroll_y_to(&mut self, percentage: f32, bounds: Rectangle, content_bounds: Rectangle) {
1653        self.offset_y = Offset::Relative(percentage.clamp(0.0, 1.0));
1654        self.unsnap(bounds, content_bounds);
1655    }
1656
1657    fn scroll_x_to(&mut self, percentage: f32, bounds: Rectangle, content_bounds: Rectangle) {
1658        self.offset_x = Offset::Relative(percentage.clamp(0.0, 1.0));
1659        self.unsnap(bounds, content_bounds);
1660    }
1661
1662    fn snap_to(&mut self, offset: RelativeOffset<Option<f32>>) {
1663        if let Some(x) = offset.x {
1664            self.offset_x = Offset::Relative(x.clamp(0.0, 1.0));
1665        }
1666
1667        if let Some(y) = offset.y {
1668            self.offset_y = Offset::Relative(y.clamp(0.0, 1.0));
1669        }
1670    }
1671
1672    fn scroll_to(&mut self, offset: AbsoluteOffset<Option<f32>>) {
1673        if let Some(x) = offset.x {
1674            self.offset_x = Offset::Absolute(x.max(0.0));
1675        }
1676
1677        if let Some(y) = offset.y {
1678            self.offset_y = Offset::Absolute(y.max(0.0));
1679        }
1680    }
1681
1682    /// Scroll by the provided [`AbsoluteOffset`].
1683    fn scroll_by(&mut self, offset: AbsoluteOffset, bounds: Rectangle, content_bounds: Rectangle) {
1684        self.scroll(Vector::new(offset.x, offset.y), bounds, content_bounds);
1685    }
1686
1687    /// Unsnaps the current scroll position, if snapped, given the bounds of the
1688    /// [`Scrollable`] and its contents.
1689    fn unsnap(&mut self, bounds: Rectangle, content_bounds: Rectangle) {
1690        self.offset_x =
1691            Offset::Absolute(self.offset_x.absolute(bounds.width, content_bounds.width));
1692        self.offset_y =
1693            Offset::Absolute(self.offset_y.absolute(bounds.height, content_bounds.height));
1694    }
1695
1696    /// Returns the scrolling translation of the [`State`], given a [`Direction`],
1697    /// the bounds of the [`Scrollable`] and its contents.
1698    fn translation(
1699        &self,
1700        direction: Direction,
1701        bounds: Rectangle,
1702        content_bounds: Rectangle,
1703    ) -> Vector {
1704        Vector::new(
1705            if let Some(horizontal) = direction.horizontal() {
1706                self.offset_x
1707                    .translation(bounds.width, content_bounds.width, horizontal.alignment)
1708                    .round()
1709            } else {
1710                0.0
1711            },
1712            if let Some(vertical) = direction.vertical() {
1713                self.offset_y
1714                    .translation(bounds.height, content_bounds.height, vertical.alignment)
1715                    .round()
1716            } else {
1717                0.0
1718            },
1719        )
1720    }
1721
1722    fn scrollers_grabbed(&self) -> bool {
1723        matches!(
1724            self.interaction,
1725            Interaction::YScrollerGrabbed(_) | Interaction::XScrollerGrabbed(_),
1726        )
1727    }
1728
1729    pub fn y_scroller_grabbed_at(&self) -> Option<f32> {
1730        let Interaction::YScrollerGrabbed(at) = self.interaction else {
1731            return None;
1732        };
1733
1734        Some(at)
1735    }
1736
1737    pub fn x_scroller_grabbed_at(&self) -> Option<f32> {
1738        let Interaction::XScrollerGrabbed(at) = self.interaction else {
1739            return None;
1740        };
1741
1742        Some(at)
1743    }
1744}
1745
1746#[derive(Debug)]
1747/// State of both [`Scrollbar`]s.
1748struct Scrollbars {
1749    y: Option<internals::Scrollbar>,
1750    x: Option<internals::Scrollbar>,
1751}
1752
1753impl Scrollbars {
1754    /// Create y and/or x scrollbar(s) if content is overflowing the [`Scrollable`] bounds.
1755    fn new(
1756        state: &State,
1757        direction: Direction,
1758        bounds: Rectangle,
1759        content_bounds: Rectangle,
1760    ) -> Self {
1761        let translation = state.translation(direction, bounds, content_bounds);
1762
1763        let show_scrollbar_x = direction
1764            .horizontal()
1765            .filter(|_scrollbar| content_bounds.width > bounds.width);
1766
1767        let show_scrollbar_y = direction
1768            .vertical()
1769            .filter(|_scrollbar| content_bounds.height > bounds.height);
1770
1771        let y_scrollbar = if let Some(vertical) = show_scrollbar_y {
1772            let Scrollbar {
1773                width,
1774                margin,
1775                scroller_width,
1776                ..
1777            } = *vertical;
1778
1779            // Adjust the height of the vertical scrollbar if the horizontal scrollbar
1780            // is present
1781            let x_scrollbar_height =
1782                show_scrollbar_x.map_or(0.0, |h| h.width.max(h.scroller_width) + h.margin);
1783
1784            let total_scrollbar_width = width.max(scroller_width) + 2.0 * margin;
1785
1786            // Total bounds of the scrollbar + margin + scroller width
1787            let total_scrollbar_bounds = Rectangle {
1788                x: bounds.x + bounds.width - total_scrollbar_width,
1789                y: bounds.y,
1790                width: total_scrollbar_width,
1791                height: (bounds.height - x_scrollbar_height).max(0.0),
1792            };
1793
1794            // Bounds of just the scrollbar
1795            let scrollbar_bounds = Rectangle {
1796                x: bounds.x + bounds.width - total_scrollbar_width / 2.0 - width / 2.0,
1797                y: bounds.y,
1798                width,
1799                height: (bounds.height - x_scrollbar_height).max(0.0),
1800            };
1801
1802            let ratio = bounds.height / content_bounds.height;
1803
1804            let scroller = if ratio >= 1.0 {
1805                None
1806            } else {
1807                // min height for easier grabbing with super tall content
1808                let scroller_height = (scrollbar_bounds.height * ratio).max(2.0);
1809                let scroller_offset =
1810                    translation.y * ratio * scrollbar_bounds.height / bounds.height;
1811
1812                let scroller_bounds = Rectangle {
1813                    x: bounds.x + bounds.width - total_scrollbar_width / 2.0 - scroller_width / 2.0,
1814                    y: (scrollbar_bounds.y + scroller_offset).max(0.0),
1815                    width: scroller_width,
1816                    height: scroller_height,
1817                };
1818
1819                Some(internals::Scroller {
1820                    bounds: scroller_bounds,
1821                })
1822            };
1823
1824            Some(internals::Scrollbar {
1825                total_bounds: total_scrollbar_bounds,
1826                bounds: scrollbar_bounds,
1827                scroller,
1828                alignment: vertical.alignment,
1829                disabled: content_bounds.height <= bounds.height,
1830            })
1831        } else {
1832            None
1833        };
1834
1835        let x_scrollbar = if let Some(horizontal) = show_scrollbar_x {
1836            let Scrollbar {
1837                width,
1838                margin,
1839                scroller_width,
1840                ..
1841            } = *horizontal;
1842
1843            // Need to adjust the width of the horizontal scrollbar if the vertical scrollbar
1844            // is present
1845            let scrollbar_y_width =
1846                y_scrollbar.map_or(0.0, |scrollbar| scrollbar.total_bounds.width);
1847
1848            let total_scrollbar_height = width.max(scroller_width) + 2.0 * margin;
1849
1850            // Total bounds of the scrollbar + margin + scroller width
1851            let total_scrollbar_bounds = Rectangle {
1852                x: bounds.x,
1853                y: bounds.y + bounds.height - total_scrollbar_height,
1854                width: (bounds.width - scrollbar_y_width).max(0.0),
1855                height: total_scrollbar_height,
1856            };
1857
1858            // Bounds of just the scrollbar
1859            let scrollbar_bounds = Rectangle {
1860                x: bounds.x,
1861                y: bounds.y + bounds.height - total_scrollbar_height / 2.0 - width / 2.0,
1862                width: (bounds.width - scrollbar_y_width).max(0.0),
1863                height: width,
1864            };
1865
1866            let ratio = bounds.width / content_bounds.width;
1867
1868            let scroller = if ratio >= 1.0 {
1869                None
1870            } else {
1871                // min width for easier grabbing with extra wide content
1872                let scroller_length = (scrollbar_bounds.width * ratio).max(2.0);
1873                let scroller_offset = translation.x * ratio * scrollbar_bounds.width / bounds.width;
1874
1875                let scroller_bounds = Rectangle {
1876                    x: (scrollbar_bounds.x + scroller_offset).max(0.0),
1877                    y: bounds.y + bounds.height
1878                        - total_scrollbar_height / 2.0
1879                        - scroller_width / 2.0,
1880                    width: scroller_length,
1881                    height: scroller_width,
1882                };
1883
1884                Some(internals::Scroller {
1885                    bounds: scroller_bounds,
1886                })
1887            };
1888
1889            Some(internals::Scrollbar {
1890                total_bounds: total_scrollbar_bounds,
1891                bounds: scrollbar_bounds,
1892                scroller,
1893                alignment: horizontal.alignment,
1894                disabled: content_bounds.width <= bounds.width,
1895            })
1896        } else {
1897            None
1898        };
1899
1900        Self {
1901            y: y_scrollbar,
1902            x: x_scrollbar,
1903        }
1904    }
1905
1906    fn is_mouse_over(&self, cursor: mouse::Cursor) -> (bool, bool) {
1907        if let Some(cursor_position) = cursor.position() {
1908            (
1909                self.y
1910                    .as_ref()
1911                    .map(|scrollbar| scrollbar.is_mouse_over(cursor_position))
1912                    .unwrap_or(false),
1913                self.x
1914                    .as_ref()
1915                    .map(|scrollbar| scrollbar.is_mouse_over(cursor_position))
1916                    .unwrap_or(false),
1917            )
1918        } else {
1919            (false, false)
1920        }
1921    }
1922
1923    fn is_y_disabled(&self) -> bool {
1924        self.y.map(|y| y.disabled).unwrap_or(false)
1925    }
1926
1927    fn is_x_disabled(&self) -> bool {
1928        self.x.map(|x| x.disabled).unwrap_or(false)
1929    }
1930
1931    fn grab_y_scroller(&self, cursor_position: Point) -> Option<f32> {
1932        let scrollbar = self.y?;
1933        let scroller = scrollbar.scroller?;
1934
1935        if scrollbar.total_bounds.contains(cursor_position) {
1936            Some(if scroller.bounds.contains(cursor_position) {
1937                (cursor_position.y - scroller.bounds.y) / scroller.bounds.height
1938            } else {
1939                0.5
1940            })
1941        } else {
1942            None
1943        }
1944    }
1945
1946    fn grab_x_scroller(&self, cursor_position: Point) -> Option<f32> {
1947        let scrollbar = self.x?;
1948        let scroller = scrollbar.scroller?;
1949
1950        if scrollbar.total_bounds.contains(cursor_position) {
1951            Some(if scroller.bounds.contains(cursor_position) {
1952                (cursor_position.x - scroller.bounds.x) / scroller.bounds.width
1953            } else {
1954                0.5
1955            })
1956        } else {
1957            None
1958        }
1959    }
1960
1961    fn active(&self) -> bool {
1962        self.y.is_some() || self.x.is_some()
1963    }
1964}
1965
1966pub(super) mod internals {
1967    use crate::core::{Point, Rectangle};
1968
1969    use super::Anchor;
1970
1971    #[derive(Debug, Copy, Clone)]
1972    pub struct Scrollbar {
1973        pub total_bounds: Rectangle,
1974        pub bounds: Rectangle,
1975        pub scroller: Option<Scroller>,
1976        pub alignment: Anchor,
1977        pub disabled: bool,
1978    }
1979
1980    impl Scrollbar {
1981        /// Returns whether the mouse is over the scrollbar or not.
1982        pub fn is_mouse_over(&self, cursor_position: Point) -> bool {
1983            self.total_bounds.contains(cursor_position)
1984        }
1985
1986        /// Returns the y-axis scrolled percentage from the cursor position.
1987        pub fn scroll_percentage_y(&self, grabbed_at: f32, cursor_position: Point) -> f32 {
1988            if let Some(scroller) = self.scroller {
1989                let percentage =
1990                    (cursor_position.y - self.bounds.y - scroller.bounds.height * grabbed_at)
1991                        / (self.bounds.height - scroller.bounds.height);
1992
1993                match self.alignment {
1994                    Anchor::Start => percentage,
1995                    Anchor::End => 1.0 - percentage,
1996                }
1997            } else {
1998                0.0
1999            }
2000        }
2001
2002        /// Returns the x-axis scrolled percentage from the cursor position.
2003        pub fn scroll_percentage_x(&self, grabbed_at: f32, cursor_position: Point) -> f32 {
2004            if let Some(scroller) = self.scroller {
2005                let percentage =
2006                    (cursor_position.x - self.bounds.x - scroller.bounds.width * grabbed_at)
2007                        / (self.bounds.width - scroller.bounds.width);
2008
2009                match self.alignment {
2010                    Anchor::Start => percentage,
2011                    Anchor::End => 1.0 - percentage,
2012                }
2013            } else {
2014                0.0
2015            }
2016        }
2017    }
2018
2019    /// The handle of a [`Scrollbar`].
2020    #[derive(Debug, Clone, Copy)]
2021    pub struct Scroller {
2022        /// The bounds of the [`Scroller`].
2023        pub bounds: Rectangle,
2024    }
2025}
2026
2027/// The possible status of a [`Scrollable`].
2028#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2029pub enum Status {
2030    /// The [`Scrollable`] can be interacted with.
2031    Active {
2032        /// Whether or not the horizontal scrollbar is disabled meaning the content isn't overflowing.
2033        is_horizontal_scrollbar_disabled: bool,
2034        /// Whether or not the vertical scrollbar is disabled meaning the content isn't overflowing.
2035        is_vertical_scrollbar_disabled: bool,
2036    },
2037    /// The [`Scrollable`] is being hovered.
2038    Hovered {
2039        /// Indicates if the horizontal scrollbar is being hovered.
2040        is_horizontal_scrollbar_hovered: bool,
2041        /// Indicates if the vertical scrollbar is being hovered.
2042        is_vertical_scrollbar_hovered: bool,
2043        /// Whether or not the horizontal scrollbar is disabled meaning the content isn't overflowing.
2044        is_horizontal_scrollbar_disabled: bool,
2045        /// Whether or not the vertical scrollbar is disabled meaning the content isn't overflowing.
2046        is_vertical_scrollbar_disabled: bool,
2047    },
2048    /// The [`Scrollable`] is being dragged.
2049    Dragged {
2050        /// Indicates if the horizontal scrollbar is being dragged.
2051        is_horizontal_scrollbar_dragged: bool,
2052        /// Indicates if the vertical scrollbar is being dragged.
2053        is_vertical_scrollbar_dragged: bool,
2054        /// Whether or not the horizontal scrollbar is disabled meaning the content isn't overflowing.
2055        is_horizontal_scrollbar_disabled: bool,
2056        /// Whether or not the vertical scrollbar is disabled meaning the content isn't overflowing.
2057        is_vertical_scrollbar_disabled: bool,
2058    },
2059}
2060
2061/// The appearance of a scrollable.
2062#[derive(Debug, Clone, Copy, PartialEq)]
2063pub struct Style {
2064    /// The [`container::Style`] of a scrollable.
2065    pub container: container::Style,
2066    /// The vertical [`Rail`] appearance.
2067    pub vertical_rail: Rail,
2068    /// The horizontal [`Rail`] appearance.
2069    pub horizontal_rail: Rail,
2070    /// The [`Background`] of the gap between a horizontal and vertical scrollbar.
2071    pub gap: Option<Background>,
2072    /// The appearance of the [`AutoScroll`] overlay.
2073    pub auto_scroll: AutoScroll,
2074}
2075
2076/// The appearance of the scrollbar of a scrollable.
2077#[derive(Debug, Clone, Copy, PartialEq)]
2078pub struct Rail {
2079    /// The [`Background`] of a scrollbar.
2080    pub background: Option<Background>,
2081    /// The [`Border`] of a scrollbar.
2082    pub border: Border,
2083    /// The appearance of the [`Scroller`] of a scrollbar.
2084    pub scroller: Scroller,
2085}
2086
2087/// The appearance of the scroller of a scrollable.
2088#[derive(Debug, Clone, Copy, PartialEq)]
2089pub struct Scroller {
2090    /// The [`Background`] of the scroller.
2091    pub background: Background,
2092    /// The [`Border`] of the scroller.
2093    pub border: Border,
2094}
2095
2096/// The appearance of the autoscroll overlay of a scrollable.
2097#[derive(Debug, Clone, Copy, PartialEq)]
2098pub struct AutoScroll {
2099    /// The [`Background`] of the [`AutoScroll`] overlay.
2100    pub background: Background,
2101    /// The [`Border`] of the [`AutoScroll`] overlay.
2102    pub border: Border,
2103    /// Thje [`Shadow`] of the [`AutoScroll`] overlay.
2104    pub shadow: Shadow,
2105    /// The [`Color`] for the arrow icons of the [`AutoScroll`] overlay.
2106    pub icon: Color,
2107}
2108
2109/// The theme catalog of a [`Scrollable`].
2110pub trait Catalog {
2111    /// The item class of the [`Catalog`].
2112    type Class<'a>;
2113
2114    /// The default class produced by the [`Catalog`].
2115    fn default<'a>() -> Self::Class<'a>;
2116
2117    /// The [`Style`] of a class with the given status.
2118    fn style(&self, class: &Self::Class<'_>, status: Status) -> Style;
2119}
2120
2121/// A styling function for a [`Scrollable`].
2122pub type StyleFn<'a, Theme> = Box<dyn Fn(&Theme, Status) -> Style + 'a>;
2123
2124impl Catalog for Theme {
2125    type Class<'a> = StyleFn<'a, Self>;
2126
2127    fn default<'a>() -> Self::Class<'a> {
2128        Box::new(default)
2129    }
2130
2131    fn style(&self, class: &Self::Class<'_>, status: Status) -> Style {
2132        class(self, status)
2133    }
2134}
2135
2136/// The default style of a [`Scrollable`].
2137pub fn default(theme: &Theme, status: Status) -> Style {
2138    let palette = theme.extended_palette();
2139
2140    let scrollbar = Rail {
2141        background: Some(palette.background.weak.color.into()),
2142        border: border::rounded(2),
2143        scroller: Scroller {
2144            background: palette.background.strongest.color.into(),
2145            border: border::rounded(2),
2146        },
2147    };
2148
2149    let auto_scroll = AutoScroll {
2150        background: palette.background.base.color.scale_alpha(0.9).into(),
2151        border: border::rounded(u32::MAX)
2152            .width(1)
2153            .color(palette.background.base.text.scale_alpha(0.8)),
2154        shadow: Shadow {
2155            color: Color::BLACK.scale_alpha(0.7),
2156            offset: Vector::ZERO,
2157            blur_radius: 2.0,
2158        },
2159        icon: palette.background.base.text.scale_alpha(0.8),
2160    };
2161
2162    match status {
2163        Status::Active { .. } => Style {
2164            container: container::Style::default(),
2165            vertical_rail: scrollbar,
2166            horizontal_rail: scrollbar,
2167            gap: None,
2168            auto_scroll,
2169        },
2170        Status::Hovered {
2171            is_horizontal_scrollbar_hovered,
2172            is_vertical_scrollbar_hovered,
2173            ..
2174        } => {
2175            let hovered_scrollbar = Rail {
2176                scroller: Scroller {
2177                    background: palette.primary.strong.color.into(),
2178                    ..scrollbar.scroller
2179                },
2180                ..scrollbar
2181            };
2182
2183            Style {
2184                container: container::Style::default(),
2185                vertical_rail: if is_vertical_scrollbar_hovered {
2186                    hovered_scrollbar
2187                } else {
2188                    scrollbar
2189                },
2190                horizontal_rail: if is_horizontal_scrollbar_hovered {
2191                    hovered_scrollbar
2192                } else {
2193                    scrollbar
2194                },
2195                gap: None,
2196                auto_scroll,
2197            }
2198        }
2199        Status::Dragged {
2200            is_horizontal_scrollbar_dragged,
2201            is_vertical_scrollbar_dragged,
2202            ..
2203        } => {
2204            let dragged_scrollbar = Rail {
2205                scroller: Scroller {
2206                    background: palette.primary.base.color.into(),
2207                    ..scrollbar.scroller
2208                },
2209                ..scrollbar
2210            };
2211
2212            Style {
2213                container: container::Style::default(),
2214                vertical_rail: if is_vertical_scrollbar_dragged {
2215                    dragged_scrollbar
2216                } else {
2217                    scrollbar
2218                },
2219                horizontal_rail: if is_horizontal_scrollbar_dragged {
2220                    dragged_scrollbar
2221                } else {
2222                    scrollbar
2223                },
2224                gap: None,
2225                auto_scroll,
2226            }
2227        }
2228    }
2229}