Skip to main content

gpui_material_extras/toolbar/bar/
scroll.rs

1use std::time::Duration;
2
3use gpui::{Context, Pixels, px};
4use gpui_material_theme::{MotionKind, MotionScheme, MotionSpec, MotionSpeed};
5
6/// Logical edge toward which the toolbar exits. Start and End mirror in RTL.
7#[derive(Clone, Copy, Debug, PartialEq, Eq)]
8pub enum ToolbarExitDirection {
9    /// Slides toward the leading horizontal edge (mirrored in RTL).
10    Start,
11    /// Slides toward the trailing horizontal edge (mirrored in RTL).
12    End,
13    /// Slides upward toward the top edge.
14    Top,
15    /// Slides downward toward the bottom edge.
16    Bottom,
17}
18
19/// Projects release velocity before choosing a toolbar endpoint.
20#[derive(Clone, Copy, Debug, PartialEq)]
21pub struct ToolbarFling {
22    /// Time window over which release velocity is projected. Defaults to `150ms`.
23    pub projection: Duration,
24    /// Uses the snap motion when omitted.
25    pub motion: Option<MotionSpec>,
26}
27
28impl Default for ToolbarFling {
29    fn default() -> Self {
30        Self {
31            projection: Duration::from_millis(150),
32            motion: None,
33        }
34    }
35}
36
37/// Controls the toolbar's expansion thresholds and optional slide away from its resting edge.
38#[derive(Clone, Copy, Debug, PartialEq)]
39pub struct ToolbarScrollBehavior {
40    /// Edge toward which the toolbar slides as it collapses, or `None` to collapse in place.
41    pub exit_direction: Option<ToolbarExitDirection>,
42    /// Upward scroll distance required to expand a collapsed toolbar. Defaults to `40px`.
43    pub expand_threshold: Pixels,
44    /// Downward scroll distance required to collapse an expanded toolbar. Defaults to `40px`.
45    pub collapse_threshold: Pixels,
46    /// Motion spec used when snapping to an endpoint without fling velocity.
47    pub snap_motion: Option<MotionSpec>,
48    /// Fling velocity projection and motion settings.
49    pub fling: ToolbarFling,
50}
51
52impl Default for ToolbarScrollBehavior {
53    fn default() -> Self {
54        Self {
55            exit_direction: None,
56            expand_threshold: px(40.),
57            collapse_threshold: px(40.),
58            snap_motion: None,
59            fling: ToolbarFling::default(),
60        }
61    }
62}
63
64#[derive(Clone, Copy, PartialEq)]
65enum Request {
66    Position(f32),
67    Settle(f32),
68}
69
70#[derive(Clone, Copy, Default)]
71pub(super) enum SettleMotion {
72    #[default]
73    Direct,
74    Snap,
75    Fling,
76}
77
78impl SettleMotion {
79    pub(super) fn spec(
80        self,
81        behavior: ToolbarScrollBehavior,
82        scheme: MotionScheme,
83        reduced: bool,
84    ) -> MotionSpec {
85        let snap = || {
86            behavior
87                .snap_motion
88                .unwrap_or_else(|| scheme.spec(MotionKind::Effects, MotionSpeed::Default, false))
89        };
90        match self {
91            _ if reduced => MotionSpec::Instant,
92            Self::Direct => MotionSpec::Instant,
93            Self::Snap => snap(),
94            Self::Fling => behavior.fling.motion.unwrap_or_else(snap),
95        }
96    }
97}
98
99#[derive(Clone, Copy, Default, PartialEq)]
100struct Metrics {
101    content: f32,
102    offset: f32,
103    limit: f32,
104    fraction: f32,
105}
106
107/// Retained toolbar scroll state. Use one entity per toolbar.
108#[derive(Default)]
109pub struct ToolbarScrollState {
110    supplied_offset: f32,
111    last: Option<f32>,
112    origin: f32,
113    direction: i8,
114    collapsed: bool,
115    target: f32,
116    motion: SettleMotion,
117    request: Option<Request>,
118    metrics: Metrics,
119}
120
121#[derive(Clone, Copy)]
122pub(super) struct ScrollPosition {
123    pub(super) target: f32,
124    pub(super) motion: SettleMotion,
125    pub(super) expanded: bool,
126    content: f32,
127}
128
129impl ToolbarScrollState {
130    /// Creates a toolbar scroll state starting expanded at offset `0`.
131    pub fn new() -> Self {
132        Self::default()
133    }
134
135    /// Supplies nonnegative logical pixels from the top of externally scrolled content.
136    pub fn set_content_offset(&mut self, offset: Pixels, cx: &mut Context<Self>) {
137        let offset = length(offset).unwrap_or(0.);
138        if self.supplied_offset != offset {
139            self.supplied_offset = offset;
140            cx.notify();
141        }
142    }
143
144    /// Sets the target collapsed fraction directly (`0.0` expanded to `1.0` collapsed).
145    pub fn set_collapsed_fraction(&mut self, fraction: f32, cx: &mut Context<Self>) {
146        if fraction.is_finite() {
147            let clamped = fraction.clamp(0., 1.);
148            let next = Some(Request::Position(clamped));
149            if self.request == next
150                || (self.request.is_none()
151                    && matches!(self.motion, SettleMotion::Direct)
152                    && self.target == clamped
153                    && self.collapsed_fraction() == clamped)
154            {
155                return;
156            }
157            self.request = next;
158            cx.notify();
159        }
160    }
161
162    /// Releases an application-owned gesture. Positive logical pixels per second exit the strip.
163    pub fn settle(&mut self, velocity: f32, cx: &mut Context<Self>) {
164        let next = Some(Request::Settle(if velocity.is_finite() {
165            velocity
166        } else {
167            0.
168        }));
169        if self.request != next {
170            self.request = next;
171            cx.notify();
172        }
173    }
174
175    /// Returns the most recently observed content scroll offset in logical pixels.
176    pub fn content_offset(&self) -> Pixels {
177        px(self.metrics.content)
178    }
179
180    /// The displayed nonnegative travel toward the configured logical edge.
181    pub fn offset(&self) -> Pixels {
182        px(self.metrics.offset)
183    }
184
185    /// Returns the maximum slide travel distance in logical pixels for the current toolbar footprint.
186    pub fn offset_limit(&self) -> Pixels {
187        px(self.metrics.limit)
188    }
189
190    /// Returns the current displayed collapsed fraction in `0.0..=1.0`.
191    pub fn collapsed_fraction(&self) -> f32 {
192        self.metrics.fraction
193    }
194
195    pub(super) fn prepare(
196        &mut self,
197        linked_offset: Option<Pixels>,
198        limit: f32,
199        behavior: ToolbarScrollBehavior,
200    ) -> ScrollPosition {
201        let content =
202            linked_offset.map_or(self.supplied_offset, |offset| length(offset).unwrap_or(0.));
203        let previous = self.last.replace(content).unwrap_or(content);
204        let delta = content - previous;
205        if delta != 0. {
206            let direction = if delta > 0. { 1 } else { -1 };
207            if direction != self.direction {
208                self.direction = direction;
209                self.origin = previous;
210            }
211            if content == 0.
212                || direction < 0
213                    && self.origin - content >= length(behavior.expand_threshold).unwrap_or(40.)
214            {
215                self.collapsed = false;
216            } else if direction > 0
217                && content - self.origin >= length(behavior.collapse_threshold).unwrap_or(40.)
218            {
219                self.collapsed = true;
220            }
221            self.motion = SettleMotion::Direct;
222            self.target = if behavior.exit_direction.is_none() {
223                f32::from(self.collapsed)
224            } else if content == 0. {
225                0.
226            } else {
227                ((self.metrics.offset + delta) / limit.max(1.)).clamp(0., 1.)
228            };
229        }
230        if let Some(request) = self.request.take() {
231            match request {
232                Request::Position(fraction) => {
233                    self.target = fraction;
234                    self.motion = SettleMotion::Direct;
235                }
236                Request::Settle(velocity) => {
237                    let fraction = if delta != 0. {
238                        self.target
239                    } else {
240                        self.metrics.fraction
241                    };
242                    let projection = velocity as f64 * behavior.fling.projection.as_secs_f64();
243                    let projected = f64::from(fraction) + projection / f64::from(limit.max(1.));
244                    self.target = f32::from(projected >= 0.5);
245                    self.motion = if projection == 0. {
246                        SettleMotion::Snap
247                    } else {
248                        SettleMotion::Fling
249                    };
250                }
251            }
252            self.collapsed = self.target >= 0.5;
253        }
254        ScrollPosition {
255            target: self.target,
256            motion: self.motion,
257            expanded: !self.collapsed,
258            content,
259        }
260    }
261
262    pub(super) fn display(
263        &mut self,
264        position: ScrollPosition,
265        fraction: f32,
266        limit: f32,
267        exposed: bool,
268    ) -> bool {
269        let metrics = Metrics {
270            content: position.content,
271            offset: if exposed { 0. } else { fraction * limit },
272            limit,
273            fraction,
274        };
275        let changed = self.metrics != metrics;
276        self.metrics = metrics;
277        changed
278    }
279}
280
281pub(super) fn length(value: Pixels) -> Option<f32> {
282    let value = f32::from(value);
283    (value.is_finite() && value >= 0.).then_some(value)
284}
285
286#[cfg(test)]
287mod tests {
288    use super::*;
289
290    #[test]
291    fn directional_thresholds_accumulate_short_deltas() {
292        let mut state = ToolbarScrollState::new();
293        let behavior = ToolbarScrollBehavior::default();
294        for (offset, expanded) in [
295            (0., true),
296            (39., true),
297            (40., false),
298            (110., false),
299            (72., false),
300            (70., true),
301        ] {
302            assert_eq!(
303                state.prepare(Some(px(offset)), 0., behavior).expanded,
304                expanded
305            );
306        }
307    }
308
309    #[test]
310    fn new_input_interrupts_a_fling_from_painted_position() {
311        let mut state = ToolbarScrollState::new();
312        let behavior = ToolbarScrollBehavior {
313            exit_direction: Some(ToolbarExitDirection::Bottom),
314            ..Default::default()
315        };
316        state.prepare(Some(px(0.)), 100., behavior);
317        let partial = state.prepare(Some(px(30.)), 100., behavior);
318        assert_eq!(partial.target, 0.3);
319        state.display(partial, 0.3, 100., false);
320        state.request = Some(Request::Settle(300.));
321        let settling = state.prepare(Some(px(30.)), 100., behavior);
322        assert_eq!(settling.target, 1.);
323        assert!(matches!(settling.motion, SettleMotion::Fling));
324        state.display(settling, 0.5, 100., false);
325        let interrupted = state.prepare(Some(px(25.)), 100., behavior);
326        assert_eq!(interrupted.target, 0.45);
327        assert!(matches!(interrupted.motion, SettleMotion::Direct));
328    }
329}