Skip to main content

nativeview_scroll_physics/
behavior.rs

1//! Composable Flutter-style [`ScrollBehavior`] decorators backed by `nativeview-physics`:
2//!
3//! - **Boundary ([`BoundaryPhysics`])**: [`ClampBoundary`], [`RubberBandBoundary`],
4//!   [`ExplicitRubberBandBoundary`]
5//! - **Fling ([`FlingPhysics`])**: [`ExponentialDecayFling`], [`NoFling`]
6//! - **Snap & Return ([`SnapPhysics`] + [`SpringReturn`])**: [`FreeScroll`], [`PageSnap`],
7//!   [`FixedExtentSnap`], [`DetentSnap`]
8//! - **Wheel ([`WheelPhysics`])**: [`SmoothWheel`], [`InstantWheel`]
9//! - **Combinator**: [`ComposedScrollBehavior`]
10
11use nativeview_layout::default_px_per_line;
12use nativeview_physics::{DecaySpec, RubberBandSpec, SmoothWheelSpec, SpringSpec};
13
14use crate::axis::{MIN_FLING_VELOCITY_PX_S, SPRING_POS_EPS_PX, SPRING_VEL_EPS_PX_S};
15use crate::pool::PooledScrollPhysics;
16use crate::profile::ScrollPhysicsProfile;
17
18/// Maximum inline snap detents supported by [`DetentSnap`] with zero heap allocation.
19pub const MAX_DETENT_STOPS: usize = 8;
20
21/// Boundary overscroll resistance policy.
22pub trait BoundaryPhysics: Send {
23    /// Whether rubber-band stretch is active by default even when `Scroll::bounce` is `false`.
24    fn bounce_by_default(&self) -> bool;
25
26    /// Returns the asymptotic rubber-band resistance spec, or `None` for hard clamping.
27    fn rubber_band_spec(&self) -> Option<RubberBandSpec>;
28}
29
30/// Hard-clamped scroll boundary: stops at `[0..=max]` with zero rubber-band overscroll.
31#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
32pub struct ClampBoundary;
33
34impl BoundaryPhysics for ClampBoundary {
35    #[inline]
36    fn bounce_by_default(&self) -> bool {
37        false
38    }
39
40    #[inline]
41    fn rubber_band_spec(&self) -> Option<RubberBandSpec> {
42        None
43    }
44}
45
46/// Elastic Apple/Android-style rubber-band overscroll boundary enabled by default.
47#[derive(Debug, Clone, Copy, PartialEq)]
48pub struct RubberBandBoundary(pub RubberBandSpec);
49
50impl Default for RubberBandBoundary {
51    #[inline]
52    fn default() -> Self {
53        Self(RubberBandSpec::APPLE)
54    }
55}
56
57impl BoundaryPhysics for RubberBandBoundary {
58    #[inline]
59    fn bounce_by_default(&self) -> bool {
60        true
61    }
62
63    #[inline]
64    fn rubber_band_spec(&self) -> Option<RubberBandSpec> {
65        Some(self.0)
66    }
67}
68
69/// Explicit-request (opt-in) rubber-band boundary (Windows/Linux desktop default): hard-clamps plain containers
70/// while honoring `Scroll::bounce(true)` and `ScrollBoundaryMode::Bounce`.
71#[derive(Debug, Clone, Copy, PartialEq)]
72pub struct ExplicitRubberBandBoundary(pub RubberBandSpec);
73
74impl Default for ExplicitRubberBandBoundary {
75    #[inline]
76    fn default() -> Self {
77        Self(RubberBandSpec::APPLE)
78    }
79}
80
81impl BoundaryPhysics for ExplicitRubberBandBoundary {
82    #[inline]
83    fn bounce_by_default(&self) -> bool {
84        false
85    }
86
87    #[inline]
88    fn rubber_band_spec(&self) -> Option<RubberBandSpec> {
89        Some(self.0)
90    }
91}
92
93/// Inertial fling momentum policy after trackpad/touch release.
94pub trait FlingPhysics: Send {
95    /// Exponential deceleration spec for inertial flings, or `None` to disable fling momentum.
96    fn decay_spec(&self) -> Option<DecaySpec>;
97
98    /// Minimum release speed (px/s) required to launch momentum.
99    #[inline]
100    fn min_fling_velocity(&self) -> f32 {
101        MIN_FLING_VELOCITY_PX_S
102    }
103}
104
105/// Exponentially decelerating inertial fling backed by [`DecaySpec`].
106#[derive(Debug, Clone, Copy, PartialEq)]
107pub struct ExponentialDecayFling(pub DecaySpec);
108
109impl Default for ExponentialDecayFling {
110    #[inline]
111    fn default() -> Self {
112        Self(DecaySpec::apple())
113    }
114}
115
116impl FlingPhysics for ExponentialDecayFling {
117    #[inline]
118    fn decay_spec(&self) -> Option<DecaySpec> {
119        Some(self.0)
120    }
121}
122
123/// Disables post-release inertial fling momentum.
124#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
125pub struct NoFling;
126
127impl FlingPhysics for NoFling {
128    #[inline]
129    fn decay_spec(&self) -> Option<DecaySpec> {
130        None
131    }
132}
133
134/// Return & snap spring specification wrapping [`SpringSpec`].
135#[derive(Debug, Clone, Copy, PartialEq)]
136pub struct SpringReturn(pub SpringSpec);
137
138impl SpringReturn {
139    /// Critically damped return spring from natural angular frequency `omega` (rad/s) with
140    /// scroll-tuned rest thresholds (`0.25 px`, `5.0 px/s`).
141    #[inline]
142    pub fn from_omega(omega: f32) -> Self {
143        Self(
144            SpringSpec::from_omega(omega)
145                .with_rest_thresholds(SPRING_POS_EPS_PX, SPRING_VEL_EPS_PX_S),
146        )
147    }
148
149    /// Apple UIScrollView-tuned return spring (`omega = 18.0 rad/s`).
150    #[inline]
151    pub fn apple() -> Self {
152        Self::from_omega(ScrollPhysicsProfile::Apple.spring_omega())
153    }
154
155    /// Android/Windows/Linux-tuned return spring (`omega = 20.0 rad/s`).
156    #[inline]
157    pub fn standard() -> Self {
158        Self::from_omega(ScrollPhysicsProfile::Android.spring_omega())
159    }
160}
161
162impl Default for SpringReturn {
163    #[inline]
164    fn default() -> Self {
165        Self::apple()
166    }
167}
168
169/// Read-only release kinematics passed to [`SnapPhysics::snap_target`].
170#[derive(Debug, Clone, Copy, PartialEq)]
171pub struct SnapQuery {
172    pub position: f32,
173    pub velocity: f32,
174    pub projected_position: f32,
175    pub viewport: f32,
176    pub max_offset: f32,
177}
178
179#[inline]
180fn sanitize_projected_position(query: SnapQuery) -> Option<f32> {
181    if query.projected_position.is_finite() {
182        Some(query.projected_position.clamp(0.0, query.max_offset))
183    } else if query.position.is_finite() {
184        Some(query.position.clamp(0.0, query.max_offset))
185    } else {
186        None
187    }
188}
189
190/// Post-release snap-point targeting policy.
191pub trait SnapPhysics: Send {
192    /// Returns the snap landing offset in `[0.0, query.max_offset]`, or `None` for free scrolling.
193    fn snap_target(&self, query: SnapQuery) -> Option<f32>;
194}
195
196/// Free scrolling with no snap points.
197#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
198pub struct FreeScroll;
199
200impl SnapPhysics for FreeScroll {
201    #[inline]
202    fn snap_target(&self, _query: SnapQuery) -> Option<f32> {
203        None
204    }
205}
206
207/// Snaps to integer multiples of the container's viewport extent (carousel / pager semantics).
208#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
209pub struct PageSnap;
210
211impl SnapPhysics for PageSnap {
212    #[inline]
213    fn snap_target(&self, query: SnapQuery) -> Option<f32> {
214        if !query.viewport.is_finite()
215            || query.viewport <= 1e-4
216            || !query.max_offset.is_finite()
217            || query.max_offset <= 0.0
218        {
219            return None;
220        }
221        let projected = sanitize_projected_position(query)?;
222        let page = (projected / query.viewport).round().max(0.0);
223        Some((page * query.viewport).clamp(0.0, query.max_offset))
224    }
225}
226
227/// Snaps to regular fixed-extent item offsets (`leading_offset + k * item_extent`).
228#[derive(Debug, Clone, Copy, PartialEq)]
229pub struct FixedExtentSnap {
230    pub item_extent: f32,
231    pub leading_offset: f32,
232}
233
234impl FixedExtentSnap {
235    #[inline]
236    pub const fn new(item_extent: f32, leading_offset: f32) -> Self {
237        Self {
238            item_extent,
239            leading_offset,
240        }
241    }
242}
243
244impl SnapPhysics for FixedExtentSnap {
245    #[inline]
246    fn snap_target(&self, query: SnapQuery) -> Option<f32> {
247        if !self.item_extent.is_finite()
248            || self.item_extent <= 1e-4
249            || !query.max_offset.is_finite()
250            || query.max_offset <= 0.0
251        {
252            return None;
253        }
254        let lead = if self.leading_offset.is_finite() {
255            self.leading_offset
256        } else {
257            0.0
258        };
259        let projected = sanitize_projected_position(query)?;
260        let idx = ((projected - lead) / self.item_extent).round().max(0.0);
261        Some((lead + idx * self.item_extent).clamp(0.0, query.max_offset))
262    }
263}
264
265/// Zero-allocation inline snap detents (`[f32; 8]` + `len: u8`) for bottom sheets, drawers, and
266/// irregular card carousels.
267#[derive(Debug, Clone, Copy, PartialEq)]
268pub struct DetentSnap {
269    stops: [f32; MAX_DETENT_STOPS],
270    len: u8,
271}
272
273impl Default for DetentSnap {
274    #[inline]
275    fn default() -> Self {
276        Self {
277            stops: [0.0; MAX_DETENT_STOPS],
278            len: 0,
279        }
280    }
281}
282
283impl DetentSnap {
284    /// Builds a sorted, finite inline detent list (truncating beyond [`MAX_DETENT_STOPS`] entries).
285    pub fn new(raw_stops: &[f32]) -> Self {
286        let mut stops = [0.0f32; MAX_DETENT_STOPS];
287        let mut len = 0usize;
288        for &s in raw_stops {
289            if len >= MAX_DETENT_STOPS {
290                break;
291            }
292            if s.is_finite() && s >= 0.0 {
293                stops[len] = s;
294                len += 1;
295            }
296        }
297        // Insertion sort over <= 8 floats (zero heap, const-friendly simplicity).
298        for i in 1..len {
299            let key = stops[i];
300            let mut j = i;
301            while j > 0 && stops[j - 1] > key {
302                stops[j] = stops[j - 1];
303                j -= 1;
304            }
305            stops[j] = key;
306        }
307        Self {
308            stops,
309            len: len as u8,
310        }
311    }
312
313    #[inline]
314    pub fn stops(&self) -> &[f32] {
315        &self.stops[..usize::from(self.len)]
316    }
317
318    #[inline]
319    pub const fn len(&self) -> usize {
320        self.len as usize
321    }
322
323    #[inline]
324    pub const fn is_empty(&self) -> bool {
325        self.len == 0
326    }
327}
328
329impl SnapPhysics for DetentSnap {
330    #[inline]
331    fn snap_target(&self, query: SnapQuery) -> Option<f32> {
332        if self.len == 0 || !query.max_offset.is_finite() || query.max_offset <= 0.0 {
333            return None;
334        }
335        let projected = sanitize_projected_position(query)?;
336        let mut best = self.stops[0].clamp(0.0, query.max_offset);
337        let mut best_dist = (best - projected).abs();
338        for &stop in &self.stops[1..usize::from(self.len)] {
339            let clamped = stop.clamp(0.0, query.max_offset);
340            let dist = (clamped - projected).abs();
341            if dist < best_dist {
342                best = clamped;
343                best_dist = dist;
344            }
345        }
346        Some(best)
347    }
348}
349
350/// Discrete mouse-wheel easing policy.
351pub trait WheelPhysics: Send {
352    /// Returns exponential smooth-wheel parameters, or `None` for immediate wheel jumps.
353    fn smooth_wheel_spec(&self) -> Option<SmoothWheelSpec>;
354}
355
356/// Exponentially smoothed discrete wheel detents backed by [`SmoothWheelSpec`].
357#[derive(Debug, Clone, Copy, PartialEq)]
358pub struct SmoothWheel(pub SmoothWheelSpec);
359
360impl Default for SmoothWheel {
361    #[inline]
362    fn default() -> Self {
363        Self(SmoothWheelSpec::apple())
364    }
365}
366
367impl WheelPhysics for SmoothWheel {
368    #[inline]
369    fn smooth_wheel_spec(&self) -> Option<SmoothWheelSpec> {
370        if self.0.tau_s.is_finite() && self.0.tau_s > 0.0 {
371            Some(self.0)
372        } else {
373            None
374        }
375    }
376}
377
378/// Immediate deterministic discrete wheel detents with zero smoothing animation.
379#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
380pub struct InstantWheel;
381
382impl WheelPhysics for InstantWheel {
383    #[inline]
384    fn smooth_wheel_spec(&self) -> Option<SmoothWheelSpec> {
385        None
386    }
387}
388
389/// Unified scroll behavior contract consumed by [`PooledScrollPhysics`].
390pub trait ScrollBehavior: Send {
391    fn bounce_by_default(&self) -> bool;
392    fn rubber_band_spec(&self) -> Option<RubberBandSpec>;
393    fn decay_spec(&self) -> Option<DecaySpec>;
394    #[inline]
395    fn min_fling_velocity(&self) -> f32 {
396        MIN_FLING_VELOCITY_PX_S
397    }
398    fn snap_target(&self, query: SnapQuery) -> Option<f32>;
399    fn return_spring(&self) -> SpringSpec;
400    fn smooth_wheel_spec(&self) -> Option<SmoothWheelSpec>;
401    #[inline]
402    fn px_per_line(&self) -> f32 {
403        default_px_per_line()
404    }
405}
406
407/// Zero-overhead static combinator stacking independent boundary, fling, snap, wheel, and spring
408/// return decorators.
409#[derive(Debug, Clone, Copy, PartialEq)]
410pub struct ComposedScrollBehavior<B, F, S, W> {
411    pub boundary: B,
412    pub fling: F,
413    pub snap: S,
414    pub wheel: W,
415    pub return_spring: SpringReturn,
416    pub px_per_line: f32,
417}
418
419impl Default
420    for ComposedScrollBehavior<RubberBandBoundary, ExponentialDecayFling, FreeScroll, SmoothWheel>
421{
422    #[inline]
423    fn default() -> Self {
424        Self::new()
425    }
426}
427
428impl ComposedScrollBehavior<RubberBandBoundary, ExponentialDecayFling, FreeScroll, SmoothWheel> {
429    /// Starts a composable scroll behavior builder with Apple-tuned defaults
430    /// (`RubberBandBoundary + ExponentialDecayFling + FreeScroll + SmoothWheel`).
431    #[inline]
432    pub fn new() -> Self {
433        Self {
434            boundary: RubberBandBoundary(RubberBandSpec::APPLE),
435            fling: ExponentialDecayFling(DecaySpec::apple()),
436            snap: FreeScroll,
437            wheel: SmoothWheel(SmoothWheelSpec::apple()),
438            return_spring: SpringReturn::apple(),
439            px_per_line: default_px_per_line(),
440        }
441    }
442}
443
444impl<B, F, S, W> ComposedScrollBehavior<B, F, S, W> {
445    #[inline]
446    pub fn with_boundary<B2: BoundaryPhysics>(
447        self,
448        boundary: B2,
449    ) -> ComposedScrollBehavior<B2, F, S, W> {
450        ComposedScrollBehavior {
451            boundary,
452            fling: self.fling,
453            snap: self.snap,
454            wheel: self.wheel,
455            return_spring: self.return_spring,
456            px_per_line: self.px_per_line,
457        }
458    }
459
460    #[inline]
461    pub fn with_fling<F2: FlingPhysics>(self, fling: F2) -> ComposedScrollBehavior<B, F2, S, W> {
462        ComposedScrollBehavior {
463            boundary: self.boundary,
464            fling,
465            snap: self.snap,
466            wheel: self.wheel,
467            return_spring: self.return_spring,
468            px_per_line: self.px_per_line,
469        }
470    }
471
472    #[inline]
473    pub fn with_snap<S2: SnapPhysics>(self, snap: S2) -> ComposedScrollBehavior<B, F, S2, W> {
474        ComposedScrollBehavior {
475            boundary: self.boundary,
476            fling: self.fling,
477            snap,
478            wheel: self.wheel,
479            return_spring: self.return_spring,
480            px_per_line: self.px_per_line,
481        }
482    }
483
484    #[inline]
485    pub fn with_wheel<W2: WheelPhysics>(self, wheel: W2) -> ComposedScrollBehavior<B, F, S, W2> {
486        ComposedScrollBehavior {
487            boundary: self.boundary,
488            fling: self.fling,
489            snap: self.snap,
490            wheel,
491            return_spring: self.return_spring,
492            px_per_line: self.px_per_line,
493        }
494    }
495
496    #[inline]
497    pub const fn with_spring(mut self, return_spring: SpringReturn) -> Self {
498        self.return_spring = return_spring;
499        self
500    }
501
502    #[inline]
503    pub const fn with_px_per_line(mut self, px_per_line: f32) -> Self {
504        self.px_per_line = px_per_line;
505        self
506    }
507}
508
509impl<B: BoundaryPhysics, F: FlingPhysics, S: SnapPhysics, W: WheelPhysics>
510    ComposedScrollBehavior<B, F, S, W>
511{
512    /// Wraps this composed behavior in a zero-allocation [`PooledScrollPhysics`] engine.
513    #[inline]
514    pub fn into_engine(self) -> PooledScrollPhysics<Self> {
515        PooledScrollPhysics::new(self)
516    }
517}
518
519impl<B: BoundaryPhysics, F: FlingPhysics, S: SnapPhysics, W: WheelPhysics> ScrollBehavior
520    for ComposedScrollBehavior<B, F, S, W>
521{
522    #[inline]
523    fn bounce_by_default(&self) -> bool {
524        self.boundary.bounce_by_default()
525    }
526
527    #[inline]
528    fn rubber_band_spec(&self) -> Option<RubberBandSpec> {
529        self.boundary.rubber_band_spec()
530    }
531
532    #[inline]
533    fn decay_spec(&self) -> Option<DecaySpec> {
534        self.fling.decay_spec()
535    }
536
537    #[inline]
538    fn min_fling_velocity(&self) -> f32 {
539        self.fling.min_fling_velocity()
540    }
541
542    #[inline]
543    fn snap_target(&self, query: SnapQuery) -> Option<f32> {
544        self.snap.snap_target(query)
545    }
546
547    #[inline]
548    fn return_spring(&self) -> SpringSpec {
549        self.return_spring.0
550    }
551
552    #[inline]
553    fn smooth_wheel_spec(&self) -> Option<SmoothWheelSpec> {
554        self.wheel.smooth_wheel_spec()
555    }
556
557    #[inline]
558    fn px_per_line(&self) -> f32 {
559        if self.px_per_line.is_finite() && self.px_per_line > 0.0 {
560            self.px_per_line
561        } else {
562            default_px_per_line()
563        }
564    }
565}