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