Skip to main content

orbital_motion/
scroll_trigger.rs

1//! Pure scroll-direction trigger used by hide-on-scroll chrome.
2
3/// Options for [`resolve_scroll_trigger`] / [`crate::use_scroll_trigger`].
4#[derive(Clone, Copy, Debug, PartialEq)]
5pub struct ScrollTriggerOptions {
6    /// Scroll position (px) below which the trigger is always inactive (bar visible).
7    pub threshold: f64,
8    /// Minimum |delta| (px) required to flip hidden state — dampens 1px flicker.
9    pub hysteresis: f64,
10}
11
12impl Default for ScrollTriggerOptions {
13    fn default() -> Self {
14        Self {
15            // ~compact AppBar height
16            threshold: 48.0,
17            hysteresis: 8.0,
18        }
19    }
20}
21
22/// Compute the next hidden flag from scroll positions.
23///
24/// - `y < threshold` → always shown (`false`)
25/// - scroll down by at least `hysteresis` while past threshold → hidden (`true`)
26/// - scroll up by at least `hysteresis` → shown (`false`)
27/// - smaller deltas keep the previous `hidden` value
28pub fn resolve_scroll_trigger(
29    last_y: f64,
30    y: f64,
31    hidden: bool,
32    opts: ScrollTriggerOptions,
33) -> bool {
34    let threshold = opts.threshold.max(0.0);
35    let hysteresis = opts.hysteresis.max(0.0);
36
37    if y < threshold {
38        return false;
39    }
40
41    let delta = y - last_y;
42    if delta >= hysteresis {
43        true
44    } else if delta <= -hysteresis {
45        false
46    } else {
47        hidden
48    }
49}
50
51#[cfg(test)]
52mod tests {
53    use super::*;
54
55    fn opts() -> ScrollTriggerOptions {
56        ScrollTriggerOptions {
57            threshold: 48.0,
58            hysteresis: 8.0,
59        }
60    }
61
62    #[test]
63    fn resolve_hides_on_scroll_down_past_threshold() {
64        assert!(resolve_scroll_trigger(50.0, 80.0, false, opts()));
65    }
66
67    #[test]
68    fn resolve_shows_on_scroll_up() {
69        assert!(!resolve_scroll_trigger(200.0, 160.0, true, opts()));
70    }
71
72    #[test]
73    fn resolve_stays_visible_below_threshold() {
74        assert!(!resolve_scroll_trigger(10.0, 20.0, true, opts()));
75        assert!(!resolve_scroll_trigger(40.0, 47.0, true, opts()));
76    }
77
78    #[test]
79    fn resolve_hysteresis_ignores_small_delta() {
80        assert!(!resolve_scroll_trigger(100.0, 104.0, false, opts()));
81        assert!(resolve_scroll_trigger(100.0, 96.0, true, opts()));
82    }
83}