Skip to main content

bhoo/systems/material/
scrollbar.rs

1use crate::*;
2
3/// Pointer drag state for a scrollbar thumb.
4#[derive(Default)]
5pub struct ScrollbarDragState {
6    anchor: Option<(f32, f32)>,
7}
8
9/// Direction of a non-interactive scroll position indicator.
10#[derive(Clone, Copy, Debug, PartialEq, Eq)]
11pub enum ScrollbarOrientation { Vertical, Horizontal }
12
13/// Caller-owned fade state for a scroll indicator.
14#[derive(Default)]
15pub struct ScrollbarIndicatorState {
16    last_offset: Option<f32>,
17    last_scroll: Option<f64>,
18}
19
20impl Frame<'_> {
21    /// Draw the default Compose Material 3 non-interactive scrollbar indicator.
22    /// Geometry and timing informed by AndroidX Scrollbar.kt (Apache-2.0),
23    /// revision 1448d64974931a04c9fba96ac630cbd6b96cda36.
24    /// Returns its painted bounds when visible. Scroll offsets are clamped to the content range.
25    #[allow(clippy::too_many_arguments)]
26    pub fn scroll_indicator(
27        &mut self, viewport: Rect, content_size: f32, offset: f32,
28        orientation: ScrollbarOrientation, rtl: bool, fade: bool,
29        state: &mut ScrollbarIndicatorState,
30    ) -> Option<Rect> {
31        let size = if orientation == ScrollbarOrientation::Vertical { viewport.height } else { viewport.width };
32        if !size.is_finite() || !content_size.is_finite() || !offset.is_finite() || size <= 0.0 || content_size <= size {
33            state.last_offset = None; state.last_scroll = None; return None;
34        }
35        let track = size - 4.0;
36        if track < 24.0 { return None; }
37        let value = offset.clamp(0.0, content_size - size);
38        let now = self.time();
39        if state.last_offset.is_some_and(|last| (last - value).abs() > 0.001) {
40            state.last_scroll = Some(now);
41        }
42        state.last_offset = Some(value);
43        let alpha = if !fade { 1.0 } else if let Some(last) = state.last_scroll {
44            let elapsed = (now - last).max(0.0);
45            if elapsed < 0.4 {
46                if viewport.intersect(self.clip).width > 0.0 && viewport.intersect(self.clip).height > 0.0 { self.wake_at(last + 0.4); }
47                1.0
48            } else if self.reduced_motion() { 0.0 }
49            else if elapsed < 0.65 {
50                self.continuous(viewport);
51                1.0 - crate::timing::Easing::Cubic([0.4, 0.0, 0.2, 1.0]).sample(((elapsed - 0.4) / 0.25) as f32)
52            } else { 0.0 }
53        } else { 0.0 };
54        if alpha <= 0.001 { return None; }
55        let length = (track * size / content_size).max(24.0).min((track * 0.9).max(24.0));
56        let distance = value / (content_size - size) * (track - length);
57        let bounds = match orientation {
58            ScrollbarOrientation::Vertical => Rect { x: if rtl { viewport.x } else { viewport.x + viewport.width - 4.0 }, y: viewport.y + 2.0 + distance, width: 4.0, height: length },
59            ScrollbarOrientation::Horizontal => Rect { x: if rtl { viewport.x + viewport.width - 2.0 - length - distance } else { viewport.x + 2.0 + distance }, y: viewport.y + viewport.height - 4.0, width: length, height: 4.0 },
60        };
61        self.paint_rect(bounds, 2.0, self.theme().outline.opacity(0.7 * alpha));
62        Some(bounds)
63    }
64    /// Vertical scrollbar with an anchored thumb drag and page-sized track clicks.
65    /// `content_height` and `viewport_height` are measured in the same units as `offset`.
66    pub fn vertical_scrollbar(
67        &mut self,
68        id: u64,
69        track: Rect,
70        label: &str,
71        content_height: f32,
72        viewport_height: f32,
73        offset: &mut f32,
74        state: &mut ScrollbarDragState,
75    ) -> (Response, Rect) {
76        let content = if content_height.is_finite() { content_height.max(0.0) } else { 0.0 };
77        let viewport = if viewport_height.is_finite() { viewport_height.max(0.0) } else { 0.0 };
78        let maximum = (content - viewport).max(0.0);
79        *offset = if offset.is_finite() { offset.clamp(0.0, maximum) } else { 0.0 };
80        let height = track.height.max(0.0);
81        let thumb_height = if content > 0.0 { (height * viewport / content).max(32.0).min(height) } else { height };
82        let travel = (height - thumb_height).max(0.0);
83        let thumb_at = |value: f32| Rect { y: track.y + if maximum > 0.0 { value / maximum * travel } else { 0.0 }, height: thumb_height, ..track };
84        let before = *offset;
85        let mut response = self.interact(id, track, maximum > 0.0 && travel > 0.0);
86        if response.enabled && self.input.pressed && response.pressed {
87            if let Some(point) = self.input.pointer {
88                let thumb = thumb_at(*offset);
89                if thumb.contains(point) { state.anchor = Some((point[1], *offset)); }
90                else {
91                    state.anchor = None;
92                    let amount = if point[1] < thumb.y { -viewport } else { viewport };
93                    *offset = (*offset + amount).clamp(0.0, maximum);
94                }
95            }
96        }
97        if response.pressed && let (Some((start, initial)), Some(point)) = (state.anchor, self.input.pointer) {
98            *offset = (initial + (point[1] - start) * maximum / travel).clamp(0.0, maximum);
99        }
100        if self.input.released || self.input.cancelled || self.input.blurred || !response.enabled { state.anchor = None; }
101        if let Some(key) = self.key_for(response) {
102            *offset = match key {
103                Key::Up | Key::Left => (*offset - 40.0).max(0.0),
104                Key::Down | Key::Right => (*offset + 40.0).min(maximum),
105                Key::PageUp => (*offset - viewport).max(0.0),
106                Key::PageDown => (*offset + viewport).min(maximum),
107                Key::Home => 0.0,
108                Key::End => maximum,
109                _ => *offset,
110            };
111        }
112        response.changed = before != *offset;
113        self.semantic(response, Role::Slider, label, false, None, Some(*offset), Some([0.0, maximum]));
114        self.focus_ring(response);
115        (response, thumb_at(*offset))
116    }
117    /// Drag a vertical scrollbar thumb without changing its appearance.
118    pub fn scrollbar_thumb_drag(
119        &mut self,
120        id: u64,
121        thumb: Rect,
122        track: Rect,
123        max_offset: f32,
124        offset: &mut f32,
125        state: &mut ScrollbarDragState,
126    ) {
127        let travel = (track.height - thumb.height).max(0.0);
128        if !max_offset.is_finite() || max_offset <= 0.0 || travel <= 0.0 {
129            state.anchor = None;
130            return;
131        }
132        let response = self.interact(id, thumb, true);
133        if self.input.pressed && response.pressed {
134            state.anchor = self.input.pointer.map(|p| (p[1], *offset));
135        }
136        if response.pressed && let (Some((start, initial)), Some(point)) = (state.anchor, self.input.pointer) {
137            *offset = (initial + (point[1] - start) * max_offset / travel).clamp(0.0, max_offset);
138            self.ui.continuous = true;
139        }
140        if self.input.released || self.input.cancelled || self.input.blurred || !response.enabled {
141            state.anchor = None;
142        }
143    }
144
145    /// Self-painting interactive vertical scrollbar (computes drag/keyboard state, cancels
146    /// scroll inertia on grab, and paints track + rounded thumb).
147    pub fn vertical_scrollbar_painted(
148        &mut self,
149        id: u64,
150        track: Rect,
151        offset: &mut f32,
152        viewport: f32,
153        content: f32,
154        state: &mut ScrollbarDragState,
155    ) -> Response {
156        let (r, thumb) = self.vertical_scrollbar(id, track, "Scroll", content, viewport, offset, state);
157        if content <= viewport + 0.5 || track.width <= 0.0 || track.height <= 0.0 {
158            return r;
159        }
160        if r.pressed || r.changed {
161            self.cancel_scroll(id);
162        }
163        let t = self.theme();
164        self.paint_rect(track, track.width * 0.5, t.surface_variant.opacity(0.45));
165        let thumb_color = if r.pressed {
166            t.primary
167        } else if r.hovered {
168            t.on_surface_variant.opacity(0.8)
169        } else {
170            t.on_surface_variant.opacity(0.55)
171        };
172        self.paint_rect(thumb, thumb.width * 0.5, thumb_color);
173        r
174    }
175}
176
177#[cfg(test)]
178#[path = "scrollbar.spec.rs"]
179mod tests;