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    pub fn new() -> Self {
52        Self::default()
53    }
54
55    /// Supplies a nonnegative distance from the top for an externally scrolled view.
56    /// A linked GPUI ScrollHandle takes precedence when present.
57    pub fn set_content_offset(&mut self, offset: Pixels, cx: &mut Context<Self>) {
58        let offset = length(offset).unwrap_or(0.);
59        if self.supplied_offset != offset {
60            self.supplied_offset = offset;
61            cx.notify();
62        }
63    }
64
65    /// Sets the presentation fraction immediately, provided the bar can collapse.
66    pub fn set_collapsed_fraction(&mut self, fraction: f32, cx: &mut Context<Self>) {
67        if fraction.is_finite() {
68            let clamped = fraction.clamp(0., 1.);
69            let next = Some(Request::Fraction(clamped));
70            if self.request == next
71                || (self.request.is_none()
72                    && !self.settle
73                    && self.target == clamped
74                    && self.collapsed_fraction() == clamped)
75            {
76                return;
77            }
78            self.request = next;
79            cx.notify();
80        }
81    }
82
83    /// Settles at an endpoint of the current range. Velocity is in logical pixels
84    /// per second, positive away from the top. A zero velocity uses the nearest endpoint.
85    pub fn settle(&mut self, velocity: f32, cx: &mut Context<Self>) {
86        let next = Some(Request::Settle(if velocity.is_finite() {
87            velocity
88        } else {
89            0.
90        }));
91        if self.request != next {
92            self.request = next;
93            cx.notify();
94        }
95    }
96
97    pub fn content_offset(&self) -> Pixels {
98        px(self.metrics.content)
99    }
100
101    /// Current displayed height offset. Expanded is zero, and collapse is negative.
102    pub fn height_offset(&self) -> Pixels {
103        px(self.metrics.height)
104    }
105
106    pub fn height_offset_limit(&self) -> Pixels {
107        px(self.metrics.limit)
108    }
109
110    pub fn collapsed_fraction(&self) -> f32 {
111        if self.metrics.limit < 0. {
112            self.metrics.height / self.metrics.limit
113        } else {
114            0.
115        }
116    }
117
118    pub fn overlapped_fraction(&self) -> f32 {
119        self.metrics.overlapped
120    }
121
122    pub(in crate::navigation) fn prepare(
123        &mut self,
124        handle_offset: Option<f32>,
125        limit: f32,
126        strategy: Option<AppBarScrollBehavior>,
127        enabled: bool,
128    ) -> ScrollPosition {
129        let content = handle_offset.unwrap_or(self.supplied_offset);
130        let previous = self.last_offset.replace(content);
131        let change = content - previous.unwrap_or(0.);
132        let strategy_changed = self.last_strategy != strategy;
133        self.last_strategy = strategy;
134        let pinned = strategy == Some(AppBarScrollBehavior::Pinned) || limit == 0.;
135        if pinned {
136            self.target = 0.;
137            self.settle = false;
138        } else if enabled && (change != 0. || previous.is_none() || strategy_changed) {
139            let fraction = if self.settle {
140                self.collapsed_fraction()
141            } else {
142                self.target
143            };
144            let distance = fraction * limit;
145            let next = match strategy {
146                None => content,
147                Some(AppBarScrollBehavior::EnterAlways) => distance + change,
148                Some(AppBarScrollBehavior::ExitUntilCollapsed) => {
149                    if content == 0. {
150                        0.
151                    } else {
152                        distance + change.max(0.)
153                    }
154                }
155                Some(AppBarScrollBehavior::Pinned) => 0.,
156            };
157            self.target = (next / limit).clamp(0., 1.);
158            self.settle = false;
159        }
160        if let Some(request) = self.request.take().filter(|_| !pinned) {
161            match request {
162                Request::Fraction(fraction) => {
163                    self.target = fraction;
164                    self.settle = false;
165                }
166                Request::Settle(velocity) => {
167                    let fraction = if self.settle {
168                        self.collapsed_fraction()
169                    } else {
170                        self.target
171                    };
172                    let keep_closed = strategy == Some(AppBarScrollBehavior::ExitUntilCollapsed)
173                        && content > 0.
174                        && fraction > 0.;
175                    let collapse =
176                        keep_closed || velocity > 0. || velocity == 0. && fraction >= 0.5;
177                    self.target = f32::from(collapse);
178                    self.settle = true;
179                }
180            }
181        }
182        let content = if enabled {
183            content
184        } else {
185            self.metrics.content
186        };
187        ScrollPosition {
188            target: self.target,
189            settling: self.settle,
190            overlap: (content / limit.max(24.)).clamp(0., 1.),
191            content,
192            limit,
193        }
194    }
195
196    pub(in crate::navigation) fn display(
197        &mut self,
198        position: ScrollPosition,
199        fraction: f32,
200    ) -> bool {
201        let next = Metrics {
202            content: position.content,
203            height: -position.limit * fraction,
204            limit: -position.limit,
205            overlapped: position.overlap,
206        };
207        let changed = self.metrics != next;
208        self.metrics = next;
209        changed
210    }
211}
212
213pub(in crate::navigation) fn length(value: Pixels) -> Option<f32> {
214    let value = f32::from(value);
215    (value.is_finite() && value >= 0.).then_some(value)
216}
217
218#[cfg(test)]
219mod tests {
220    use super::*;
221
222    #[test]
223    fn enter_always_resumes_from_the_displayed_height_when_scroll_interrupts_settling() {
224        let mut state = AppBarScrollState::new();
225        let strategy = Some(AppBarScrollBehavior::EnterAlways);
226        let partial = state.prepare(Some(30.), 100., strategy, true);
227        assert_eq!(partial.target, 0.3);
228        state.display(partial, 0.3);
229
230        state.request = Some(Request::Settle(200.));
231        let settling = state.prepare(Some(30.), 100., strategy, true);
232        assert!(settling.settling);
233        assert_eq!(settling.target, 1.);
234        state.display(settling, 0.5);
235
236        let resumed = state.prepare(Some(35.), 100., strategy, true);
237        assert!(!resumed.settling);
238        assert_eq!(resumed.target, 0.55);
239    }
240}