Skip to main content

gpui_material_components/navigation/app_bar/
scroll.rs

1use gpui::{Context, Pixels, px};
2
3/// How changes in the linked content offset affect the app bar's height.
4#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
5pub enum AppBarScrollBehavior {
6    /// Keeps the bar at its expanded height while tracking the scrolled color.
7    #[default]
8    Pinned,
9    /// Collapses on forward scrolling and expands as soon as scrolling reverses.
10    EnterAlways,
11    /// Collapses on forward scrolling and expands when the content reaches the top.
12    ExitUntilCollapsed,
13}
14
15#[derive(Clone, Copy, PartialEq)]
16enum Request {
17    Fraction(f32),
18    Settle(f32),
19}
20
21/// Retained app bar presentation state. Use a distinct entity per app bar.
22#[derive(Default)]
23pub struct AppBarScrollState {
24    supplied_offset: f32,
25    last_offset: Option<f32>,
26    last_strategy: Option<AppBarScrollBehavior>,
27    target: f32,
28    settle: bool,
29    request: Option<Request>,
30    metrics: Metrics,
31}
32
33#[derive(Clone, Copy, Default, PartialEq)]
34struct Metrics {
35    content: f32,
36    height: f32,
37    limit: f32,
38    overlapped: f32,
39}
40
41#[derive(Clone, Copy)]
42pub(in crate::navigation) struct ScrollPosition {
43    pub target: f32,
44    pub settling: bool,
45    pub overlap: f32,
46    content: f32,
47    limit: f32,
48}
49
50impl AppBarScrollState {
51    /// Creates an app bar scroll state initialized at zero scroll offset.
52    pub fn new() -> Self {
53        Self::default()
54    }
55
56    /// Supplies a nonnegative distance from the top for an externally scrolled view.
57    /// A linked GPUI ScrollHandle takes precedence when present.
58    pub fn set_content_offset(&mut self, offset: Pixels, cx: &mut Context<Self>) {
59        let offset = length(offset).unwrap_or(0.);
60        if self.supplied_offset != offset {
61            self.supplied_offset = offset;
62            cx.notify();
63        }
64    }
65
66    /// Sets the presentation fraction immediately, provided the bar can collapse.
67    pub fn set_collapsed_fraction(&mut self, fraction: f32, cx: &mut Context<Self>) {
68        if fraction.is_finite() {
69            let clamped = fraction.clamp(0., 1.);
70            let next = Some(Request::Fraction(clamped));
71            if self.request == next
72                || (self.request.is_none()
73                    && !self.settle
74                    && self.target == clamped
75                    && self.collapsed_fraction() == clamped)
76            {
77                return;
78            }
79            self.request = next;
80            cx.notify();
81        }
82    }
83
84    /// Settles at an endpoint of the current range. Velocity is in logical pixels
85    /// per second, positive away from the top. A zero velocity uses the nearest endpoint.
86    pub fn settle(&mut self, velocity: f32, cx: &mut Context<Self>) {
87        let next = Some(Request::Settle(if velocity.is_finite() {
88            velocity
89        } else {
90            0.
91        }));
92        if self.request != next {
93            self.request = next;
94            cx.notify();
95        }
96    }
97
98    /// Returns the last observed content scroll distance from the top.
99    pub fn content_offset(&self) -> Pixels {
100        px(self.metrics.content)
101    }
102
103    /// Current displayed height offset. Expanded is zero, and collapse is negative.
104    pub fn height_offset(&self) -> Pixels {
105        px(self.metrics.height)
106    }
107
108    /// Returns the maximum negative height offset (zero when the bar cannot collapse).
109    pub fn height_offset_limit(&self) -> Pixels {
110        px(self.metrics.limit)
111    }
112
113    /// Returns the current collapse progress in `0.0..=1.0`.
114    pub fn collapsed_fraction(&self) -> f32 {
115        if self.metrics.limit < 0. {
116            self.metrics.height / self.metrics.limit
117        } else {
118            0.
119        }
120    }
121
122    /// Returns the fraction of scrolled-under overlap in `0.0..=1.0`, used for scrolled container color.
123    pub fn overlapped_fraction(&self) -> f32 {
124        self.metrics.overlapped
125    }
126
127    pub(in crate::navigation) fn prepare(
128        &mut self,
129        handle_offset: Option<f32>,
130        limit: f32,
131        strategy: Option<AppBarScrollBehavior>,
132        enabled: bool,
133    ) -> ScrollPosition {
134        let content = handle_offset.unwrap_or(self.supplied_offset);
135        let previous = self.last_offset.replace(content);
136        let change = content - previous.unwrap_or(0.);
137        let strategy_changed = self.last_strategy != strategy;
138        self.last_strategy = strategy;
139        let pinned = strategy == Some(AppBarScrollBehavior::Pinned) || limit == 0.;
140        if pinned {
141            self.target = 0.;
142            self.settle = false;
143        } else if enabled && (change != 0. || previous.is_none() || strategy_changed) {
144            let fraction = if self.settle {
145                self.collapsed_fraction()
146            } else {
147                self.target
148            };
149            let distance = fraction * limit;
150            let next = match strategy {
151                None => content,
152                Some(AppBarScrollBehavior::EnterAlways) => distance + change,
153                Some(AppBarScrollBehavior::ExitUntilCollapsed) => {
154                    if content == 0. {
155                        0.
156                    } else {
157                        distance + change.max(0.)
158                    }
159                }
160                Some(AppBarScrollBehavior::Pinned) => 0.,
161            };
162            self.target = (next / limit).clamp(0., 1.);
163            self.settle = false;
164        }
165        if let Some(request) = self.request.take().filter(|_| !pinned) {
166            match request {
167                Request::Fraction(fraction) => {
168                    self.target = fraction;
169                    self.settle = false;
170                }
171                Request::Settle(velocity) => {
172                    let fraction = if self.settle {
173                        self.collapsed_fraction()
174                    } else {
175                        self.target
176                    };
177                    let keep_closed = strategy == Some(AppBarScrollBehavior::ExitUntilCollapsed)
178                        && content > 0.
179                        && fraction > 0.;
180                    let collapse =
181                        keep_closed || velocity > 0. || velocity == 0. && fraction >= 0.5;
182                    self.target = f32::from(collapse);
183                    self.settle = true;
184                }
185            }
186        }
187        let content = if enabled {
188            content
189        } else {
190            self.metrics.content
191        };
192        ScrollPosition {
193            target: self.target,
194            settling: self.settle,
195            overlap: (content / limit.max(24.)).clamp(0., 1.),
196            content,
197            limit,
198        }
199    }
200
201    pub(in crate::navigation) fn display(
202        &mut self,
203        position: ScrollPosition,
204        fraction: f32,
205    ) -> bool {
206        let next = Metrics {
207            content: position.content,
208            height: -position.limit * fraction,
209            limit: -position.limit,
210            overlapped: position.overlap,
211        };
212        let changed = self.metrics != next;
213        self.metrics = next;
214        changed
215    }
216}
217
218pub(in crate::navigation) fn length(value: Pixels) -> Option<f32> {
219    let value = f32::from(value);
220    (value.is_finite() && value >= 0.).then_some(value)
221}
222
223#[cfg(test)]
224mod tests {
225    use super::*;
226
227    #[test]
228    fn enter_always_resumes_from_the_displayed_height_when_scroll_interrupts_settling() {
229        let mut state = AppBarScrollState::new();
230        let strategy = Some(AppBarScrollBehavior::EnterAlways);
231        let partial = state.prepare(Some(30.), 100., strategy, true);
232        assert_eq!(partial.target, 0.3);
233        state.display(partial, 0.3);
234
235        state.request = Some(Request::Settle(200.));
236        let settling = state.prepare(Some(30.), 100., strategy, true);
237        assert!(settling.settling);
238        assert_eq!(settling.target, 1.);
239        state.display(settling, 0.5);
240
241        let resumed = state.prepare(Some(35.), 100., strategy, true);
242        assert!(!resumed.settling);
243        assert_eq!(resumed.target, 0.55);
244    }
245}