Skip to main content

iced_cube/primitives/
scroll_area.rs

1//! Scrollable regions with a thin, rounded scrollbar.
2
3use iced::widget::scrollable::{self, AutoScroll, Rail, Scrollbar, Scroller, Status};
4use iced::widget::{Id, container};
5use iced::{Background, Border, Color, Element, Length, Shadow, Vector};
6
7use crate::theme::{Tokens, fade, mix, radius, space};
8
9/// Width of the scrollbar rail in logical pixels.
10pub const THICKNESS: f32 = 6.0;
11
12/// Which way the content scrolls.
13#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
14pub enum Direction {
15    #[default]
16    Vertical,
17    Horizontal,
18    Both,
19}
20
21impl Direction {
22    pub const ALL: [Direction; 3] = [Direction::Vertical, Direction::Horizontal, Direction::Both];
23
24    fn scrollable(self) -> scrollable::Direction {
25        match self {
26            Direction::Vertical => scrollable::Direction::Vertical(scrollbar()),
27            Direction::Horizontal => scrollable::Direction::Horizontal(scrollbar()),
28            Direction::Both => scrollable::Direction::Both {
29                vertical: floating_scrollbar(),
30                horizontal: floating_scrollbar(),
31            },
32        }
33    }
34}
35
36/// The thin scrollbar used by single-direction scroll areas. It sits beside
37/// the content rather than over it.
38pub fn scrollbar() -> Scrollbar {
39    floating_scrollbar().spacing(space::XS)
40}
41
42/// The thin scrollbar used when scrolling both ways. iced cannot reserve
43/// space for two scrollbars, so these float over the content's edges.
44pub fn floating_scrollbar() -> Scrollbar {
45    Scrollbar::new()
46        .width(THICKNESS)
47        .scroller_width(THICKNESS)
48        .margin(2)
49}
50
51/// A scroll area builder. Convert it into an [`Element`] to render.
52pub struct ScrollArea<'a, Message> {
53    content: Element<'a, Message>,
54    direction: Direction,
55    width: Length,
56    height: Length,
57    id: Option<Id>,
58}
59
60impl<Message> std::fmt::Debug for ScrollArea<'_, Message> {
61    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
62        f.debug_struct("ScrollArea")
63            .field("direction", &self.direction)
64            .field("width", &self.width)
65            .field("height", &self.height)
66            .finish_non_exhaustive()
67    }
68}
69
70/// Creates a vertically scrolling area around `content`.
71pub fn scroll_area<'a, Message>(
72    content: impl Into<Element<'a, Message>>,
73) -> ScrollArea<'a, Message> {
74    ScrollArea {
75        content: content.into(),
76        direction: Direction::default(),
77        width: Length::Shrink,
78        height: Length::Shrink,
79        id: None,
80    }
81}
82
83impl<'a, Message> ScrollArea<'a, Message> {
84    pub fn direction(mut self, direction: Direction) -> Self {
85        self.direction = direction;
86        self
87    }
88
89    pub fn width(mut self, width: impl Into<Length>) -> Self {
90        self.width = width.into();
91        self
92    }
93
94    pub fn height(mut self, height: impl Into<Length>) -> Self {
95        self.height = height.into();
96        self
97    }
98
99    /// Sets the widget id, for scrolling programmatically.
100    pub fn id(mut self, id: impl Into<Id>) -> Self {
101        self.id = Some(id.into());
102        self
103    }
104}
105
106impl<'a, Message: 'a> From<ScrollArea<'a, Message>> for Element<'a, Message> {
107    fn from(area: ScrollArea<'a, Message>) -> Self {
108        let mut scrollable =
109            scrollable::Scrollable::with_direction(area.content, area.direction.scrollable())
110                .width(area.width)
111                .height(area.height)
112                .style(|theme, status| style(&Tokens::of(theme), status));
113        if let Some(id) = area.id {
114            scrollable = scrollable.id(id);
115        }
116        let element: Element<'a, Message> = scrollable.into();
117        #[cfg(feature = "icedwright")]
118        let element = icedwright_probe::semantic(element)
119            .role(icedwright_probe::role::ScrollView)
120            .component("iced_cube::scroll_area")
121            .into();
122        element
123    }
124}
125
126/// How the pointer is interacting with one scrollbar.
127#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
128pub enum Interaction {
129    Idle,
130    Hovered,
131    Dragged,
132}
133
134/// Scroller colour for an interaction.
135pub fn scroller_colour(tokens: &Tokens, interaction: Interaction) -> Color {
136    match interaction {
137        Interaction::Idle => tokens.border,
138        Interaction::Hovered => mix(tokens.border, tokens.foreground, 0.25),
139        Interaction::Dragged => mix(tokens.border, tokens.foreground, 0.45),
140    }
141}
142
143/// Splits a scrollable status into vertical and horizontal interactions.
144pub fn interactions(status: Status) -> (Interaction, Interaction) {
145    let pick = |dragged: bool, hovered: bool| {
146        if dragged {
147            Interaction::Dragged
148        } else if hovered {
149            Interaction::Hovered
150        } else {
151            Interaction::Idle
152        }
153    };
154    match status {
155        Status::Active { .. } => (Interaction::Idle, Interaction::Idle),
156        Status::Hovered {
157            is_vertical_scrollbar_hovered,
158            is_horizontal_scrollbar_hovered,
159            ..
160        } => (
161            pick(false, is_vertical_scrollbar_hovered),
162            pick(false, is_horizontal_scrollbar_hovered),
163        ),
164        Status::Dragged {
165            is_vertical_scrollbar_dragged,
166            is_horizontal_scrollbar_dragged,
167            ..
168        } => (
169            pick(is_vertical_scrollbar_dragged, false),
170            pick(is_horizontal_scrollbar_dragged, false),
171        ),
172    }
173}
174
175/// The iced scrollable style for a status.
176pub fn style(tokens: &Tokens, status: Status) -> scrollable::Style {
177    let (vertical, horizontal) = interactions(status);
178    let rail = |interaction| Rail {
179        background: None,
180        border: Border::default(),
181        scroller: Scroller {
182            background: Background::Color(scroller_colour(tokens, interaction)),
183            border: Border {
184                radius: radius::FULL.into(),
185                ..Border::default()
186            },
187        },
188    };
189
190    scrollable::Style {
191        container: container::Style::default(),
192        vertical_rail: rail(vertical),
193        horizontal_rail: rail(horizontal),
194        gap: None,
195        auto_scroll: AutoScroll {
196            background: Background::Color(fade(tokens.background, 0.9)),
197            border: Border {
198                color: tokens.border,
199                width: 1.0,
200                radius: radius::FULL.into(),
201            },
202            shadow: Shadow {
203                color: fade(tokens.foreground, 0.1),
204                offset: Vector::new(0.0, 1.0),
205                blur_radius: 3.0,
206            },
207            icon: tokens.muted_foreground,
208        },
209    }
210}
211
212#[cfg(test)]
213mod tests {
214    use super::*;
215    use crate::theme::{dark, light};
216
217    const ACTIVE: Status = Status::Active {
218        is_horizontal_scrollbar_disabled: false,
219        is_vertical_scrollbar_disabled: false,
220    };
221
222    fn hovered(vertical: bool, horizontal: bool) -> Status {
223        Status::Hovered {
224            is_horizontal_scrollbar_hovered: horizontal,
225            is_vertical_scrollbar_hovered: vertical,
226            is_horizontal_scrollbar_disabled: false,
227            is_vertical_scrollbar_disabled: false,
228        }
229    }
230
231    fn dragged(vertical: bool, horizontal: bool) -> Status {
232        Status::Dragged {
233            is_horizontal_scrollbar_dragged: horizontal,
234            is_vertical_scrollbar_dragged: vertical,
235            is_horizontal_scrollbar_disabled: false,
236            is_vertical_scrollbar_disabled: false,
237        }
238    }
239
240    fn scroller(rail: Rail) -> Background {
241        rail.scroller.background
242    }
243
244    #[test]
245    fn default_builder_is_vertical_and_shrinks() {
246        let area: ScrollArea<'_, ()> = scroll_area("content");
247        assert_eq!(area.direction, Direction::Vertical);
248        assert_eq!(area.width, Length::Shrink);
249        assert!(area.id.is_none());
250    }
251
252    #[test]
253    fn directions_map_to_the_right_scrollbars() {
254        let vertical = Direction::Vertical.scrollable();
255        assert!(vertical.vertical().is_some() && vertical.horizontal().is_none());
256        let horizontal = Direction::Horizontal.scrollable();
257        assert!(horizontal.vertical().is_none() && horizontal.horizontal().is_some());
258        let both = Direction::Both.scrollable();
259        assert!(both.vertical().is_some() && both.horizontal().is_some());
260    }
261
262    #[test]
263    fn scrollbars_are_thin() {
264        let floating = Scrollbar::new().width(6).scroller_width(6).margin(2);
265        assert_eq!(floating_scrollbar(), floating);
266        assert_eq!(scrollbar(), floating.spacing(4));
267    }
268
269    #[test]
270    fn only_both_directions_float() {
271        assert_eq!(
272            Direction::Vertical.scrollable().vertical(),
273            Some(&scrollbar())
274        );
275        assert_eq!(
276            Direction::Both.scrollable().horizontal(),
277            Some(&floating_scrollbar())
278        );
279    }
280
281    #[test]
282    fn interactions_track_each_axis() {
283        assert_eq!(interactions(ACTIVE), (Interaction::Idle, Interaction::Idle));
284        assert_eq!(
285            interactions(hovered(true, false)),
286            (Interaction::Hovered, Interaction::Idle)
287        );
288        assert_eq!(
289            interactions(dragged(false, true)),
290            (Interaction::Idle, Interaction::Dragged)
291        );
292    }
293
294    #[test]
295    fn scroller_strengthens_with_interaction() {
296        for theme in [light(), dark()] {
297            let tokens = Tokens::of(&theme);
298            let idle = style(&tokens, ACTIVE);
299            let hover = style(&tokens, hovered(true, true));
300            let drag = style(&tokens, dragged(true, true));
301            assert_ne!(scroller(idle.vertical_rail), scroller(hover.vertical_rail));
302            assert_ne!(scroller(hover.vertical_rail), scroller(drag.vertical_rail));
303            assert_ne!(
304                scroller(idle.horizontal_rail),
305                scroller(drag.horizontal_rail)
306            );
307        }
308    }
309
310    #[test]
311    fn rails_are_transparent_and_scrollers_rounded() {
312        for theme in [light(), dark()] {
313            let tokens = Tokens::of(&theme);
314            for status in [ACTIVE, hovered(true, false), dragged(false, true)] {
315                let style = style(&tokens, status);
316                for rail in [style.vertical_rail, style.horizontal_rail] {
317                    assert!(rail.background.is_none());
318                    assert_eq!(rail.scroller.border.radius, radius::FULL.into());
319                }
320            }
321        }
322    }
323
324    #[test]
325    fn idle_scroller_uses_border_token() {
326        let tokens = Tokens::of(&dark());
327        assert_eq!(scroller_colour(&tokens, Interaction::Idle), tokens.border);
328    }
329}