Skip to main content

rust_glass/widgets/
scroll.rs

1//! Scroll areas: vertical, horizontal, both, and long lists that lay out
2//! only the visible rows.
3
4use std::ops::Range;
5
6use crate::animation::{Spring, Tuning};
7use crate::color::Color;
8use crate::context::{Id, Sense};
9use crate::geometry::{Rect, Vec2, vec2};
10use crate::material::Corner;
11use crate::paint::Feather;
12use crate::ui::Ui;
13use crate::widgets::press::rubber_band;
14
15/// Scrolling with smooth wheel steps, elastic ends and overlay scroll bars.
16/// Vertical by default; [`Self::horizontal`] lays the content out in a row
17/// and [`Self::both`] scrolls on two axes. `fade` dissolves content at the
18/// edges, which keeps floating glass legible without a solid bar behind it.
19///
20/// Long lists draw only what is visible with [`Self::show_rows`].
21pub struct ScrollArea {
22    height: Option<f32>,
23    width: Option<f32>,
24    x: bool,
25    y: bool,
26    content_width: Option<f32>,
27    fade: Feather,
28    inset_top: f32,
29    inset_bottom: f32,
30    id: &'static str,
31}
32
33#[derive(Clone, Copy, Default)]
34struct Axis {
35    offset: Spring,
36    target: f32,
37    content: f32,
38    grab: f32,
39}
40
41#[derive(Clone, Copy, Default)]
42struct State {
43    axes: [Axis; 2],
44    bar: Spring,
45    last_move: f64,
46}
47
48impl Default for ScrollArea {
49    fn default() -> Self {
50        Self::new()
51    }
52}
53
54impl ScrollArea {
55    /// Vertical scrolling.
56    pub fn new() -> Self {
57        Self {
58            height: None,
59            width: None,
60            x: false,
61            y: true,
62            content_width: None,
63            fade: Feather::default(),
64            inset_top: 0.0,
65            inset_bottom: 0.0,
66            id: "scroll",
67        }
68    }
69    /// Horizontal scrolling. Children are placed side by side and centered
70    /// on the height of the area. Vertical wheel movement passes to the area
71    /// around it; shift with the wheel or a sideways swipe scrolls this one.
72    pub fn horizontal() -> Self {
73        Self { x: true, y: false, ..Self::new() }
74    }
75    /// Scrolling on both axes, for content larger than the view both ways.
76    /// Children are stacked vertically in a column [`Self::content_width`]
77    /// wide, or as wide as they need when that is not set.
78    pub fn both() -> Self {
79        Self { x: true, ..Self::new() }
80    }
81    /// Names the area. Needed when one `Ui` holds more than one scroll area.
82    pub fn id(mut self, id: &'static str) -> Self {
83        self.id = id;
84        self
85    }
86    /// Sets the height. The default is the height left in the layout.
87    pub fn height(mut self, height: f32) -> Self {
88        self.height = Some(height);
89        self
90    }
91    /// Sets the width. The default is the width left in the layout.
92    pub fn width(mut self, width: f32) -> Self {
93        self.width = Some(width);
94        self
95    }
96    /// Width of the column the content is laid out in, for [`Self::both`].
97    pub fn content_width(mut self, w: f32) -> Self {
98        self.content_width = Some(w);
99        self
100    }
101    /// Dissolve content over this distance at the top and bottom.
102    pub fn fade(mut self, top: f32, bottom: f32) -> Self {
103        self.fade.top = top;
104        self.fade.bottom = bottom;
105        self
106    }
107    /// Dissolve content over this distance at the left and right.
108    pub fn fade_sides(mut self, left: f32, right: f32) -> Self {
109        self.fade.left = left;
110        self.fade.right = right;
111        self
112    }
113    /// Space kept free for floating bars. Content scrolls below them.
114    pub fn insets(mut self, top: f32, bottom: f32) -> Self {
115        self.inset_top = top;
116        self.inset_bottom = bottom;
117        self
118    }
119
120    /// Shows the area with the content drawn by `f`.
121    pub fn show<R>(self, ui: &mut Ui, f: impl FnOnce(&mut Ui) -> R) -> R {
122        self.show_inner(ui, |ui, _| f(ui))
123    }
124
125    /// A vertical list of `count` rows, each `row_height` tall, of which only
126    /// the visible ones are laid out. `f` gets the range of rows to draw and
127    /// must give each row exactly `row_height`.
128    ///
129    /// ```
130    /// # use rust_glass::prelude::*;
131    /// # fn f(ui: &mut Ui, names: &[String]) {
132    /// ScrollArea::new().height(300.0).show_rows(ui, 28.0, names.len(), |ui, rows| {
133    ///     for i in rows {
134    ///         ui.label(&names[i]);
135    ///     }
136    /// });
137    /// # }
138    /// ```
139    pub fn show_rows<R>(
140        self,
141        ui: &mut Ui,
142        row_height: f32,
143        count: usize,
144        f: impl FnOnce(&mut Ui, Range<usize>) -> R,
145    ) -> R {
146        let inset = self.inset_top;
147        self.show_inner(ui, |ui, visible| {
148            let stride = row_height + ui.spacing;
149            let top = (visible.min.y - inset).max(0.0);
150            let first = ((top / stride).floor() as usize).min(count);
151            let n = (visible.height() / stride).ceil() as usize + 2;
152            let last = (first + n).min(count);
153            ui.space(first as f32 * stride);
154            let out = f(ui, first..last);
155            let total = (count as f32 * stride - ui.spacing).max(0.0);
156            ui.reserve(vec2(0.0, total));
157            out
158        })
159    }
160
161    /// `f` gets the visible part of the content, relative to its top left.
162    fn show_inner<R>(self, ui: &mut Ui, f: impl FnOnce(&mut Ui, Rect) -> R) -> R {
163        let id = ui.make_id(self.id);
164        let h = self.height.unwrap_or_else(|| ui.available_height());
165        let w = self.width.unwrap_or_else(|| ui.available_width());
166        let view = ui.allocate(vec2(w, h));
167        let mut s: State = ui.ctx.get(id);
168        let dt = ui.ctx.dt;
169        let on = [self.x, self.y];
170        let size = [w, h];
171        let max = [0, 1].map(|a| (s.axes[a].content - size[a]).max(0.0));
172        let wheel = ui.ctx.scroll_area_axes(id, view.intersect(ui.clip), ui.layer, self.x, self.y);
173        let wheel = [wheel.x, wheel.y];
174        let limit = if ui.ctx.theme.reduce_motion { 0.5 } else { 46.0 };
175        let mut shown = [0.0; 2];
176        for a in 0..2 {
177            let ax = &mut s.axes[a];
178            if !on[a] {
179                *ax = Axis::default();
180                continue;
181            }
182            if wheel[a] != 0.0 {
183                ax.target -= wheel[a];
184                s.last_move = ui.ctx.time;
185                ui.ctx.add_scroll_energy(wheel[a] * 0.004);
186            }
187            // Past the ends the target is pulled back, so it gives and returns.
188            let over = ax.target - ax.target.clamp(0.0, max[a]);
189            if over != 0.0 {
190                ax.target = ax.target.clamp(0.0, max[a]) + rubber_band(over, limit);
191                let back = (-dt * 11.0).exp();
192                let o = ax.target - ax.target.clamp(0.0, max[a]);
193                ax.target = ax.target.clamp(0.0, max[a]) + if o.abs() < 0.4 { 0.0 } else { o * back };
194                ui.ctx.request_repaint();
195            }
196            if ax.offset.step(ax.target, Tuning::new(0.17, 1.0), dt) {
197                s.last_move = ui.ctx.time;
198                ui.ctx.request_repaint();
199            }
200            shown[a] = (ax.offset.value * ui.ctx.pixels_per_point).round() / ui.ctx.pixels_per_point;
201        }
202        let off = [s.axes[0].offset.value, s.axes[1].offset.value];
203
204        let (old_clip, old_mask) = (ui.clip, ui.mask);
205        // Room for shadows and for glass that swells under a press, on the
206        // sides that do not scroll.
207        let room = vec2(if self.x { 0.0 } else { 30.0 }, if self.y { 0.0 } else { 30.0 });
208        let sides = view.expand2(room);
209        ui.clip = ui.clip.intersect(sides);
210        let edge = |o: f32, m: f32| (o / 24.0).clamp(0.0, 1.0) * (m > 0.5) as u32 as f32;
211        let feather = Feather {
212            left: self.fade.left * edge(off[0], max[0]),
213            right: self.fade.right * edge(max[0] - off[0], max[0]),
214            top: self.fade.top * edge(off[1], max[1]),
215            bottom: self.fade.bottom * edge(max[1] - off[1], max[1]),
216        };
217        if self.fade.left + self.fade.right + self.fade.top + self.fade.bottom > 0.0 {
218            ui.mask = ui.painter().add_mask(sides, 0.0, false, feather);
219        }
220        let min = vec2(view.min.x - shown[0], view.min.y - shown[1] + self.inset_top);
221        let visible = Rect::from_min_size(vec2(off[0], off[1]), view.size());
222        let revealing = ui.ctx.reveal.is_some() && ui.ctx.reveal_rect.is_none();
223        let (out, used) = if self.x && !self.y {
224            let body = Rect { min, max: vec2(min.x + 1.0e5, view.max.y - self.inset_bottom) };
225            ui.row_sized(id, body, |ui| f(ui, visible))
226        } else {
227            let width = if self.x { self.content_width.unwrap_or(1.0e5) } else { view.width() };
228            let body = Rect { min, max: vec2(min.x + width, min.y + 1.0e5) };
229            ui.in_rect_sized(id, body, |ui| f(ui, visible))
230        };
231        ui.clip = old_clip;
232        ui.mask = old_mask;
233        // A widget inside got focus from the keyboard or a screen reader:
234        // scroll just far enough to show it.
235        if revealing && let Some(target) = ui.ctx.reveal_rect {
236            const MARGIN: f32 = 12.0;
237            let shown = [
238                (view.min.x + MARGIN, view.max.x - MARGIN),
239                (view.min.y + self.inset_top + MARGIN, view.max.y - self.inset_bottom - MARGIN),
240            ];
241            let wanted = [(target.min.x, target.max.x), (target.min.y, target.max.y)];
242            for a in 0..2 {
243                let ((start, end), (low, high)) = (shown[a], wanted[a]);
244                let shift = if low < start {
245                    low - start
246                } else if high > end {
247                    (high - end).min(low - start)
248                } else {
249                    0.0
250                };
251                if on[a] && shift != 0.0 {
252                    s.axes[a].target = (s.axes[a].target + shift).clamp(0.0, max[a]);
253                    s.last_move = ui.ctx.time;
254                    ui.ctx.request_repaint();
255                }
256            }
257        }
258        let content = [used.x, used.y + self.inset_top + self.inset_bottom];
259        for a in 0..2 {
260            if on[a] && (content[a] - s.axes[a].content).abs() > 0.5 {
261                s.axes[a].content = content[a];
262                ui.ctx.request_repaint();
263            }
264        }
265
266        // Scroll bars.
267        let recent = ui.ctx.time - s.last_move < 0.9;
268        let mut engaged = false;
269        let mut bars = Vec::new();
270        for a in 0..2 {
271            if !on[a] || max[a] <= 1.0 {
272                continue;
273            }
274            let (t0, t1) = if a == 1 {
275                (view.min.y + self.inset_top.max(6.0), view.max.y - self.inset_bottom.max(6.0))
276            } else {
277                (view.min.x + 6.0, view.max.x - if on[1] && max[1] > 1.0 { 14.0 } else { 6.0 })
278            };
279            let ax = &mut s.axes[a];
280            let track = t1 - t0;
281            let len = (size[a] / ax.content * track).clamp(28.0, track);
282            let over = (off[a] - off[a].clamp(0.0, max[a])).abs();
283            let len = (len - over * 0.6).max(12.0);
284            let start = t0 + (track - len) * (off[a] / max[a]).clamp(0.0, 1.0);
285            let hit = if a == 1 {
286                Rect { min: vec2(view.max.x - 14.0, start), max: vec2(view.max.x, start + len) }
287            } else {
288                Rect { min: vec2(start, view.max.y - 14.0), max: vec2(start + len, view.max.y) }
289            };
290            let r = ui.interact(id.with(("bar", a)), hit, Sense::Drag);
291            let p0 = if a == 1 { ui.ctx.input.press_origin.y } else { ui.ctx.input.press_origin.x };
292            if r.pressed {
293                ax.grab = p0 - start;
294            }
295            if r.held
296                && let Some(p) = r.pointer
297            {
298                let p = if a == 1 { p.y } else { p.x };
299                ax.target = ((p - ax.grab - t0) / (track - len).max(1.0)).clamp(0.0, 1.0) * max[a];
300                ax.offset.set(ax.target);
301            }
302            engaged |= r.hovered || r.held;
303            bars.push((a, r.id, r.hovered || r.held, start, len));
304        }
305        if s.bar.step((recent || engaged) as u32 as f32, Tuning::new(0.3, 1.0), dt) || recent {
306            ui.ctx.request_repaint();
307        }
308        let c = Color::black(0.38).lerp(Color::white(0.45), ui.surface.darkness());
309        let alpha = s.bar.value;
310        for (a, bar_id, hot, start, len) in bars {
311            let wide = ui.ctx.animate_bool(bar_id.with("wide"), hot, Tuning::SNAP);
312            let bw = 4.0 + 3.0 * wide;
313            let r = if a == 1 {
314                Rect { min: vec2(view.max.x - 4.0 - bw, start), max: vec2(view.max.x - 4.0, start + len) }
315            } else {
316                Rect { min: vec2(start, view.max.y - 4.0 - bw), max: vec2(start + len, view.max.y - 4.0) }
317            };
318            ui.painter().fill(r, Corner::Capsule, c.fade(alpha));
319        }
320        ui.ctx.set(id, s);
321        out
322    }
323}
324
325/// Scroll position of the area `id` inside `ui`, for saving and restoring.
326pub fn scroll_offset(ui: &mut Ui, id: &'static str) -> Vec2 {
327    let id: Id = ui.make_id(id);
328    let s: State = ui.ctx.get(id);
329    vec2(s.axes[0].target, s.axes[1].target)
330}
331
332/// Jump the area `id` inside `ui` to `offset`. Call before the area is shown.
333pub fn set_scroll_offset(ui: &mut Ui, id: &'static str, offset: Vec2) {
334    let id: Id = ui.make_id(id);
335    let mut s: State = ui.ctx.get(id);
336    for (a, v) in [offset.x, offset.y].into_iter().enumerate() {
337        s.axes[a].target = v.max(0.0);
338        s.axes[a].offset.set(v.max(0.0));
339    }
340    ui.ctx.set(id, s);
341}
342
343#[cfg(test)]
344mod tests {
345    use super::*;
346    use crate::context::Context;
347    use crate::geometry::rect;
348    use crate::widgets::panel::region;
349
350    #[test]
351    fn masks_inside_a_fading_area_keep_its_fade() {
352        let mut ctx = Context::new();
353        let mut selected = 0;
354        ctx.begin_frame(vec2(400.0, 300.0), 1.0, 0.0, &[]);
355        region(&mut ctx, "page", rect(0.0, 0.0, 400.0, 300.0), |ui| {
356            ScrollArea::new().fade(20.0, 20.0).height(100.0).show(ui, |ui| {
357                for _ in 0..10 {
358                    ui.segmented(&mut selected, &["One", "Two"]);
359                }
360            });
361        });
362        ctx.end_frame();
363        let masks = &ctx.paint.data.masks;
364        // The first mask is the fade of the area, the rest belong to the
365        // segmented controls and must be combined with it.
366        assert!(masks.len() > 1);
367        assert_eq!(masks[0].parent, 0);
368        assert!(masks[1..].iter().all(|m| m.parent == 1));
369    }
370}