Skip to main content

repose_core/
scroll.rs

1use std::cell::{Cell, RefCell};
2use std::rc::Rc;
3
4use web_time::Instant;
5
6use crate::input::ScrollSource;
7use crate::nested_scroll::{NestedScrollConnection, NestedScrollSource};
8use crate::{ControlVisualSet, Dp, Signal, Vec2, request_frame, signal};
9
10thread_local! {
11    static TOUCH_GESTURE_ACTIVE: Cell<bool> = const { Cell::new(false) };
12    static TOUCH_GESTURE_GENERATION: Cell<u64> = const { Cell::new(0) };
13}
14
15/// Mark the start/end of a touch drag so scroll surfaces stop flinging while
16/// the finger is down. Compose holds the surface still mid-drag and only
17/// starts a fling when the drag stops.
18pub fn set_touch_gesture_active(active: bool) {
19    TOUCH_GESTURE_ACTIVE.with(|slot| slot.set(active));
20}
21
22/// Pre-empt in-flight flings when a touch gesture commits to scrolling.
23/// Compose does this through `scroll(MutatePriority.UserInput)` on the
24/// scrollable that receives the drag, not on unrelated surfaces.
25pub fn cancel_flings() {
26    TOUCH_GESTURE_GENERATION.with(|slot| slot.set(slot.get().wrapping_add(1)));
27}
28
29pub fn touch_gesture_active() -> bool {
30    TOUCH_GESTURE_ACTIVE.with(Cell::get)
31}
32
33fn touch_gesture_generation() -> u64 {
34    TOUCH_GESTURE_GENERATION.with(Cell::get)
35}
36
37/// Axis (or axes) a scroll modifier operates on.
38#[derive(Clone, Copy, Debug, PartialEq, Eq)]
39pub enum ScrollAxis {
40    Vertical,
41    Horizontal,
42    Both,
43}
44
45// Holds all callbacks that the layout engine needs from a scroll state.
46// Stored in `Modifier.scroll`.
47
48#[derive(Clone, Debug, PartialEq)]
49pub struct ScrollbarStyle {
50    pub thickness: Dp,
51    pub track_inset: Dp,
52    /// Cross-axis inset of the track (M3 `crossAxisTrackInset`, default 0).
53    /// The vertical bar sits this far from the end edge; the horizontal bar
54    /// this far from the bottom edge.
55    pub track_cross_inset: Dp,
56    pub min_thumb_length: Dp,
57    /// Maximum thumb length as a fraction of the track (M3
58    /// `thumbMaxLengthFraction`, default 0.9).
59    pub thumb_max_length_fraction: f32,
60    pub fixed_thumb_length: Option<Dp>,
61    pub radius: Option<Dp>,
62    pub track_visuals: ControlVisualSet,
63    pub thumb_visuals: ControlVisualSet,
64    /// M3 `isFadeEnabled`: the bar shows while scrolling (or while hovered /
65    /// pressed) and fades out after `fade_delay_ms`. When false the bar is
66    /// always fully visible.
67    pub fade_enabled: bool,
68    /// M3 `fadeDelayMillis`: idle time before the fade starts.
69    pub fade_delay_ms: u64,
70    /// M3 `fadeDurationMillis`: length of the fade animation.
71    pub fade_duration_ms: u64,
72}
73
74impl Default for ScrollbarStyle {
75    fn default() -> Self {
76        Self {
77            thickness: Dp(4.0),
78            track_inset: Dp(2.0),
79            track_cross_inset: Dp(0.0),
80            min_thumb_length: Dp(24.0),
81            thumb_max_length_fraction: 0.9,
82            fixed_thumb_length: None,
83            radius: None,
84            track_visuals: ControlVisualSet::default(),
85            thumb_visuals: ControlVisualSet::default(),
86            fade_enabled: true,
87            fade_delay_ms: 400,
88            fade_duration_ms: 250,
89        }
90    }
91}
92
93impl ScrollbarStyle {
94    pub fn with_thickness(mut self, thickness: Dp) -> Self {
95        self.thickness = thickness;
96        self
97    }
98
99    pub fn with_track_inset(mut self, track_inset: Dp) -> Self {
100        self.track_inset = track_inset;
101        self
102    }
103
104    pub fn with_track_cross_inset(mut self, track_cross_inset: Dp) -> Self {
105        self.track_cross_inset = track_cross_inset;
106        self
107    }
108
109    pub fn with_thumb_max_length_fraction(mut self, fraction: f32) -> Self {
110        self.thumb_max_length_fraction = fraction;
111        self
112    }
113
114    pub fn with_fade_enabled(mut self, fade_enabled: bool) -> Self {
115        self.fade_enabled = fade_enabled;
116        self
117    }
118
119    pub fn with_fade_delay_ms(mut self, fade_delay_ms: u64) -> Self {
120        self.fade_delay_ms = fade_delay_ms;
121        self
122    }
123
124    pub fn with_fade_duration_ms(mut self, fade_duration_ms: u64) -> Self {
125        self.fade_duration_ms = fade_duration_ms;
126        self
127    }
128
129    pub fn with_min_thumb_length(mut self, min_thumb_length: Dp) -> Self {
130        self.min_thumb_length = min_thumb_length;
131        self
132    }
133
134    pub fn with_fixed_thumb_length(mut self, length: Option<Dp>) -> Self {
135        self.fixed_thumb_length = length;
136        self
137    }
138
139    pub fn with_radius(mut self, radius: Option<Dp>) -> Self {
140        self.radius = radius;
141        self
142    }
143
144    pub fn with_track_visuals(mut self, visuals: ControlVisualSet) -> Self {
145        self.track_visuals = visuals;
146        self
147    }
148
149    pub fn with_thumb_visuals(mut self, visuals: ControlVisualSet) -> Self {
150        self.thumb_visuals = visuals;
151        self
152    }
153}
154
155/// Callbacks for a single-axis (vertical or horizontal) scroll container.
156#[derive(Clone, Default)]
157pub struct ScrollAxisBinding {
158    pub on_scroll: Option<Rc<dyn Fn(Vec2) -> Vec2>>,
159    /// Source-aware scroll handler. Takes precedence over `on_scroll` in the
160    /// input pipeline; wheel deltas intentionally do not seed a fling.
161    pub on_scroll_with_source: Option<Rc<dyn Fn(Vec2, ScrollSource) -> Vec2>>,
162    /// Set viewport size along the scroll axis (height for V, width for H).
163    pub set_viewport_main: Option<Rc<dyn Fn(f32)>>,
164    /// Set content size along the scroll axis.
165    pub set_content_main: Option<Rc<dyn Fn(f32)>>,
166    pub get_offset_main: Option<Rc<dyn Fn() -> f32>>,
167    pub set_offset_main: Option<Rc<dyn Fn(f32)>>,
168    /// Reverse layout (Compose `reverseLayout`): offset 0 sits at the end of
169    /// the track and the thumb mapping runs backwards.
170    pub reversed: bool,
171    pub show_scrollbar: bool,
172    pub tick: Option<Rc<dyn Fn()>>,
173    pub set_nested_scroll_parent: Option<Rc<dyn Fn(NestedScrollConnection)>>,
174}
175
176impl std::fmt::Debug for ScrollAxisBinding {
177    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
178        f.debug_struct("ScrollAxisBinding")
179            .field("has_on_scroll", &self.on_scroll.is_some())
180            .field(
181                "has_on_scroll_with_source",
182                &self.on_scroll_with_source.is_some(),
183            )
184            .field("set_viewport_main", &self.set_viewport_main.is_some())
185            .field("set_content_main", &self.set_content_main.is_some())
186            .field("get_offset_main", &self.get_offset_main.is_some())
187            .field("set_offset_main", &self.set_offset_main.is_some())
188            .field("show_scrollbar", &self.show_scrollbar)
189            .field("tick", &self.tick.is_some())
190            .field(
191                "set_nested_scroll_parent",
192                &self.set_nested_scroll_parent.is_some(),
193            )
194            .finish()
195    }
196}
197
198/// Callbacks for a 2D (both-axis) scroll container.
199#[derive(Clone, Default)]
200pub struct ScrollBothBinding {
201    pub on_scroll: Option<Rc<dyn Fn(Vec2) -> Vec2>>,
202    /// Source-aware scroll handler; see `ScrollAxisBinding::on_scroll_with_source`.
203    pub on_scroll_with_source: Option<Rc<dyn Fn(Vec2, ScrollSource) -> Vec2>>,
204    pub set_viewport_width: Option<Rc<dyn Fn(f32)>>,
205    pub set_viewport_height: Option<Rc<dyn Fn(f32)>>,
206    pub set_content_width: Option<Rc<dyn Fn(f32)>>,
207    pub set_content_height: Option<Rc<dyn Fn(f32)>>,
208    pub get_offset_xy: Option<Rc<dyn Fn() -> (f32, f32)>>,
209    pub set_offset_xy: Option<Rc<dyn Fn(f32, f32)>>,
210    /// Per-axis reverse layout; see `ScrollAxisBinding::reversed`.
211    pub reversed_x: bool,
212    pub reversed_y: bool,
213    pub show_scrollbar: bool,
214    pub tick: Option<Rc<dyn Fn()>>,
215    pub set_nested_scroll_parent: Option<Rc<dyn Fn(NestedScrollConnection)>>,
216}
217
218impl std::fmt::Debug for ScrollBothBinding {
219    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
220        f.debug_struct("ScrollBothBinding")
221            .field("has_on_scroll", &self.on_scroll.is_some())
222            .field(
223                "has_on_scroll_with_source",
224                &self.on_scroll_with_source.is_some(),
225            )
226            .field("set_viewport_width", &self.set_viewport_width.is_some())
227            .field("set_viewport_height", &self.set_viewport_height.is_some())
228            .field("set_content_width", &self.set_content_width.is_some())
229            .field("set_content_height", &self.set_content_height.is_some())
230            .field("get_offset_xy", &self.get_offset_xy.is_some())
231            .field("set_offset_xy", &self.set_offset_xy.is_some())
232            .field("show_scrollbar", &self.show_scrollbar)
233            .field("tick", &self.tick.is_some())
234            .field(
235                "set_nested_scroll_parent",
236                &self.set_nested_scroll_parent.is_some(),
237            )
238            .finish()
239    }
240}
241
242#[derive(Clone, Debug)]
243pub enum ScrollBinding {
244    Vertical(ScrollAxisBinding),
245    Horizontal(ScrollAxisBinding),
246    Both(ScrollBothBinding),
247}
248
249impl ScrollBinding {
250    pub fn axis(&self) -> ScrollAxis {
251        match self {
252            ScrollBinding::Vertical(_) => ScrollAxis::Vertical,
253            ScrollBinding::Horizontal(_) => ScrollAxis::Horizontal,
254            ScrollBinding::Both(_) => ScrollAxis::Both,
255        }
256    }
257}
258
259const OVERSHOOT_DECAY_PER_60HZ: f32 = 0.78;
260const MAX_SCROLL_VELOCITY: f32 = 8000.0;
261
262/// Per-60Hz-frame velocity decay at low speed. Higher stops the fling sooner.
263pub const SCROLL_DECAY_PER_60HZ: f32 = 0.85;
264/// Fling is abandoned once speed falls below this (px/s).
265pub const SCROLL_STOP_VELOCITY: f32 = 15.0;
266/// A gesture must exceed this speed (px/s) to leave a fling behind.
267pub const SCROLL_FLING_ACTIVATE_VELOCITY: f32 = 50.0;
268/// How recently the finger must have moved for its velocity to seed a fling.
269/// Compose's `VelocityTracker` computes from samples inside a 100ms horizon,
270/// so a short pause before lifting still coasts. A tighter cutoff drops the
271/// fling on any dropped frame on a busy screen.
272pub const SCROLL_RELEASE_VELOCITY_HORIZON_MS: u128 = 100;
273/// Rubber-band asymptote: overscroll never stretches past this many px.
274pub const SCROLL_OVERSROLL_BAND_MAX: f32 = 150.0;
275
276/// Clamp a scroll offset into `[0, max]` with NaN/inf sanitization.
277/// `f32::clamp` propagates NaN, so one bad write would poison the offset
278/// signal permanently (every later frame reads NaN). Central helper so all
279/// `set_offset`/`scroll_immediate` paths stay sanitized long-term.
280fn clamp_offset(off: f32, max: f32) -> f32 {
281    let max = if max.is_finite() { max.max(0.0) } else { 0.0 };
282    if off.is_finite() {
283        off.clamp(0.0, max)
284    } else {
285        0.0
286    }
287}
288
289/// Asymptotic rubber band: never reaches `max`, so pulling harder always
290/// moves a little more without ever running away.
291pub fn rubber_band(amount: f32, max: f32) -> f32 {
292    let abs_val = amount.abs();
293    if abs_val <= 0.0 {
294        return 0.0;
295    }
296    (1.0 - 1.0 / (1.0 + abs_val / max)) * max * amount.signum()
297}
298
299/// Scroll delta that brings `target` inside `viewport` on the given axes.
300///
301/// The returned `Vec2` is in the same coordinate space as the rects (physical
302/// pixels) and has the sign expected by `on_scroll`: a positive `y` moves
303/// content up, revealing targets below the viewport. Each axis contributes
304/// only when the target is actually outside the viewport on that axis, so a
305/// vertical-only scroller simply ignores the `x` component.
306pub fn scroll_delta_to_reveal(
307    target: crate::Rect,
308    viewport: crate::Rect,
309    axis: ScrollAxis,
310) -> Vec2 {
311    let mut delta = Vec2::ZERO;
312    if matches!(axis, ScrollAxis::Horizontal | ScrollAxis::Both) {
313        let target_right = target.x + target.w;
314        let viewport_right = viewport.x + viewport.w;
315        delta.x = if target_right > viewport_right {
316            (target_right - viewport_right).min((target.x - viewport.x).max(0.0))
317        } else if target.x < viewport.x {
318            (target.x - viewport.x).max(-(viewport_right - target_right).max(0.0))
319        } else {
320            0.0
321        };
322    }
323    if matches!(axis, ScrollAxis::Vertical | ScrollAxis::Both) {
324        let target_bottom = target.y + target.h;
325        let viewport_bottom = viewport.y + viewport.h;
326        delta.y = if target_bottom > viewport_bottom {
327            (target_bottom - viewport_bottom).min((target.y - viewport.y).max(0.0))
328        } else if target.y < viewport.y {
329            (target.y - viewport.y).max(-(viewport_bottom - target_bottom).max(0.0))
330        } else {
331            0.0
332        };
333    }
334    delta
335}
336
337/// Fold `leftover` into one axis's rubber band after the nested parent chain
338/// has declined it. Returns whatever is still unconsumed.
339pub fn os_scroll_axis(
340    off: &Signal<f32>,
341    os: &Signal<f32>,
342    overscroll_enabled: bool,
343    max_off: f32,
344    before: f32,
345    leftover: f32,
346    physics: &RefCell<ScrollPhysics>,
347) -> f32 {
348    if !overscroll_enabled || leftover.abs() < 0.001 {
349        return leftover;
350    }
351    let os_val = os.get();
352    // Recovering from an active rubber band: absorb the reverse delta first.
353    if os_val.abs() > 0.5 && os_val.signum() * leftover < 0.0 {
354        let reduction = leftover.abs().min(os_val.abs());
355        os.set(os_val - os_val.signum() * reduction);
356        let remainder = leftover - leftover.signum() * reduction;
357        if remainder.abs() > 0.5 {
358            let new_off = clamp_offset(before + remainder, max_off);
359            off.set(new_off);
360            let consumed = new_off - before;
361            physics.borrow_mut().record_nested_input(consumed);
362            return remainder - consumed;
363        }
364        return 0.0;
365    }
366
367    // At the edge, pushing further: stretch the rubber band.
368    let at_edge = (before <= 0.0 && leftover < 0.0) || (before >= max_off && leftover > 0.0);
369    if max_off > 5.0 && at_edge && leftover.abs() > 0.5 {
370        os.set(os_val + rubber_band(leftover, SCROLL_OVERSROLL_BAND_MAX));
371        physics.borrow_mut().record_nested_input(0.0);
372        return 0.0;
373    }
374    leftover
375}
376
377/// Decay one axis's rubber band back to rest. Returns true while it is active.
378pub fn tick_os_axis(os: &Signal<f32>, enabled: bool, dt: f32) -> bool {
379    if !enabled {
380        return false;
381    }
382    let v = os.get();
383    if v.abs() > 0.5 {
384        let decayed = v * OVERSHOOT_DECAY_PER_60HZ.powf(dt * 60.0);
385        if decayed.abs() < 0.5 {
386            os.set(0.0);
387        } else {
388            os.set(decayed);
389        }
390        request_frame();
391        true
392    } else {
393        false
394    }
395}
396
397#[derive(Clone, Copy)]
398enum DeltaVelocity {
399    User,
400    Nested,
401    Wheel,
402}
403
404/// Handles velocity estimation from input deltas, frame-rate-independent
405/// exponential decay, edge snapping, and animation state tracking.
406#[derive(Clone)]
407pub struct ScrollPhysics {
408    pub(crate) vel: f32,
409    last_t: Instant,
410    last_input_t: Instant,
411    pub(crate) animating: bool,
412    /// Set when a delta arrived since the last integration.
413    input_pending: bool,
414    last_dt: f32,
415    decay_per_60hz: f32,
416    stop_velocity: f32,
417    input_activate_velocity: f32,
418    generation: u64,
419    touch_active: bool,
420    /// Velocity the last integration step could not spend because it clamped
421    /// at a boundary. Taken once by the post-fling chaining dispatch.
422    clamped_velocity: Option<f32>,
423}
424
425impl Default for ScrollPhysics {
426    fn default() -> Self {
427        Self::new()
428    }
429}
430
431impl ScrollPhysics {
432    pub fn new() -> Self {
433        Self::with_tuning(
434            SCROLL_DECAY_PER_60HZ,
435            SCROLL_STOP_VELOCITY,
436            SCROLL_FLING_ACTIVATE_VELOCITY,
437        )
438    }
439
440    pub fn with_tuning(
441        decay_per_60hz: f32,
442        stop_velocity: f32,
443        input_activate_velocity: f32,
444    ) -> Self {
445        let now = Instant::now();
446        Self {
447            vel: 0.0,
448            last_t: now,
449            last_input_t: now,
450            animating: false,
451            input_pending: false,
452            last_dt: 1.0 / 60.0,
453            decay_per_60hz,
454            stop_velocity,
455            input_activate_velocity,
456            generation: touch_gesture_generation(),
457            touch_active: touch_gesture_active(),
458            clamped_velocity: None,
459        }
460    }
461
462    fn sync_generation(&mut self) {
463        let generation = touch_gesture_generation();
464        if generation != self.generation {
465            self.generation = generation;
466            self.vel = 0.0;
467            self.animating = false;
468            self.input_pending = false;
469            self.clamped_velocity = None;
470        }
471    }
472
473    /// A finger held still before lift must not leave a fling behind. The cutoff
474    /// is Compose's velocity horizon, not the inter-sample gap: a short pause
475    /// or a dropped frame on a busy screen still coasts.
476    pub(crate) fn settle_after_touch(&mut self) {
477        let active = touch_gesture_active();
478        if self.touch_active
479            && !active
480            && self.last_input_t.elapsed().as_millis() > SCROLL_RELEASE_VELOCITY_HORIZON_MS
481        {
482            self.vel = 0.0;
483            self.animating = false;
484            self.input_pending = false;
485            self.clamped_velocity = None;
486        }
487        self.touch_active = active;
488    }
489
490    /// Apply a delta from a source that must not start a fling (mouse wheel /
491    /// trackpad wheel). The offset still moves; only velocity is discarded.
492    pub(crate) fn clear_velocity(&mut self) {
493        self.sync_generation();
494        self.vel = 0.0;
495        self.animating = false;
496        self.input_pending = false;
497        self.clamped_velocity = None;
498    }
499
500    /// Seed a fling directly, used when a parent continues a child's clamped
501    /// fling through post-fling dispatch.
502    pub(crate) fn set_fling_velocity(&mut self, vel: f32) {
503        self.sync_generation();
504        self.vel = vel.clamp(-MAX_SCROLL_VELOCITY, MAX_SCROLL_VELOCITY);
505        self.animating = self.vel.abs() > self.input_activate_velocity;
506        self.input_pending = false;
507        self.clamped_velocity = None;
508        let now = Instant::now();
509        self.last_t = now;
510        self.last_input_t = now;
511    }
512
513    /// Consume the velocity the last integration step left at a boundary.
514    pub(crate) fn take_clamped_velocity(&mut self) -> Option<f32> {
515        self.clamped_velocity.take()
516    }
517
518    /// Feed a delta that arrived from real user input.
519    ///
520    /// A first sample adopts its velocity outright, and a delta opposing an
521    /// in-flight fling takes over from it. Both mirror Compose, where a new
522    /// `scroll(MutatePriority.UserInput)` cancels the fling coroutine holding
523    /// the `MutatorMutex` so the drag wins. Smoothing only applies between
524    /// samples of one gesture: averaging up from zero on every frame would
525    /// leave every flick at a fraction of its real speed.
526    pub fn record_user_input(&mut self, consumed: f32) {
527        self.sync_generation();
528        let (instant_vel, fresh) = self.sample(consumed);
529        if fresh || (self.animating && instant_vel * self.vel < 0.0) {
530            self.vel = instant_vel;
531        } else {
532            const SMOOTHING: f32 = 0.35;
533            self.vel = self.vel * (1.0 - SMOOTHING) + instant_vel * SMOOTHING;
534        }
535        self.finish_sample();
536    }
537
538    /// Feed a delta that arrived as leftover from a nested child. Never takes
539    /// over an in-flight fling: Compose's `dispatchRawDelta` bypasses mutual
540    /// exclusion precisely so a parent keeps coasting.
541    pub fn record_nested_input(&mut self, consumed: f32) {
542        let (instant_vel, _) = self.sample(consumed);
543        const SMOOTHING: f32 = 0.35;
544        self.vel = self.vel * (1.0 - SMOOTHING) + instant_vel * SMOOTHING;
545        self.finish_sample();
546    }
547
548    fn sample(&mut self, consumed: f32) -> (f32, bool) {
549        let now = Instant::now();
550        let raw_dt = (now - self.last_input_t).as_secs_f32();
551        let dt = raw_dt.clamp(1.0 / 240.0, 1.0 / 15.0);
552        self.last_dt = dt;
553        // A gap this long means a new gesture rather than another sample.
554        let fresh = raw_dt > 0.05;
555        self.last_input_t = now;
556        if raw_dt > 0.1 {
557            self.vel = 0.0;
558        }
559        (consumed / dt, fresh)
560    }
561
562    fn finish_sample(&mut self) {
563        self.vel = self.vel.clamp(-MAX_SCROLL_VELOCITY, MAX_SCROLL_VELOCITY);
564        self.animating = self.vel.abs() > self.input_activate_velocity;
565        self.input_pending = true;
566    }
567
568    fn dt(&mut self) -> f32 {
569        let now = Instant::now();
570        let dt = (now - self.last_t).as_secs_f32().min(0.1);
571        self.last_t = now;
572        dt
573    }
574
575    pub fn tick_integrate(&mut self, current: f32, min: f32, max: f32) -> Option<f32> {
576        // Sample the clock first, unconditionally. Bailing out before this
577        // would let `last_t` go stale for the whole duration of a drag and
578        // then dump all of it into the first fling frame, which shows up as a
579        // single large lurch the moment the finger lifts.
580        let dt = self.dt();
581        self.sync_generation();
582        self.settle_after_touch();
583        if touch_gesture_active() {
584            // The finger is down: Compose integrates no velocity mid-drag.
585            // Keep the sampled velocity for the fling on release.
586            self.input_pending = false;
587            return None;
588        }
589        if self.input_pending {
590            // A delta was applied since the last integration, so this frame's
591            // motion is already accounted for. Compose feeds velocity from the
592            // gesture layer and runs no integrator mid-drag; we infer velocity
593            // from the same delta stream we also apply, so integrating here
594            // would move the surface by roughly 2x.
595            self.input_pending = false;
596            return None;
597        }
598        if !self.animating {
599            return None;
600        }
601        if dt <= 0.0 {
602            return None;
603        }
604        let vel0 = self.vel;
605        if vel0.abs() < self.stop_velocity {
606            self.vel = 0.0;
607            self.animating = false;
608            return None;
609        }
610        let new = {
611            let raw = current + vel0 * dt;
612            let raw = if raw.is_finite() { raw } else { current };
613            raw.clamp(min, max.max(min))
614        };
615        if (new - current).abs() < 0.01 && (current <= min || current >= max) {
616            self.clamped_velocity = Some(self.vel);
617            self.vel = 0.0;
618            self.animating = false;
619            return None;
620        }
621        let speed = self.vel.abs();
622        let t = (speed / 4000.0).min(1.0);
623        let effective_decay = (self.decay_per_60hz + t * 0.10).min(0.999);
624        let decay = effective_decay.powf(dt * 60.0);
625        self.vel = vel0 * decay;
626        if self.vel.abs() < self.stop_velocity {
627            self.vel = 0.0;
628            self.animating = false;
629            return None;
630        }
631        Some(new)
632    }
633
634    pub fn is_animating(&self) -> bool {
635        self.animating
636    }
637}
638
639/// Inertial scroll state (single axis Y).
640#[derive(Clone)]
641pub struct ScrollState {
642    scroll_offset: Signal<f32>,
643    viewport_height: Signal<f32>,
644    content_height: Signal<f32>,
645    physics: Rc<RefCell<ScrollPhysics>>,
646    overscroll: Signal<f32>,
647    overscroll_enabled: Cell<bool>,
648    pub(crate) parent_connection: Rc<RefCell<Option<NestedScrollConnection>>>,
649    show_scrollbar: Cell<bool>,
650    reversed: Rc<Cell<bool>>,
651    prev_tick: Cell<Instant>,
652    fling_dispatched: Cell<bool>,
653}
654
655impl Default for ScrollState {
656    fn default() -> Self {
657        Self::new()
658    }
659}
660
661impl ScrollState {
662    pub fn new() -> Self {
663        Self {
664            scroll_offset: signal(0.0),
665            viewport_height: signal(0.0),
666            content_height: signal(0.0),
667            physics: Rc::new(RefCell::new(ScrollPhysics::new())),
668            overscroll: signal(0.0),
669            overscroll_enabled: Cell::new(true),
670            parent_connection: Rc::new(RefCell::new(None)),
671            show_scrollbar: Cell::new(true),
672            reversed: Rc::new(Cell::new(false)),
673            prev_tick: Cell::new(Instant::now()),
674            fling_dispatched: Cell::new(false),
675        }
676    }
677
678    pub fn set_overscroll_enabled(&self, enabled: bool) {
679        self.overscroll_enabled.set(enabled);
680    }
681
682    pub fn overscroll_offset(&self) -> f32 {
683        self.overscroll.get()
684    }
685
686    pub fn set_nested_scroll_parent(&self, conn: NestedScrollConnection) {
687        *self.parent_connection.borrow_mut() = Some(conn);
688    }
689
690    /// Use it to wire a child scrollable to a parent scroll container
691    /// explicitly: `child_state.set_nested_scroll_parent(parent_state.connection())`.
692    pub fn connection(&self) -> NestedScrollConnection {
693        let this = Rc::new(self.clone());
694        let pc = Rc::clone(&this.parent_connection);
695        let fling_target = Rc::clone(&this);
696        NestedScrollConnection::new()
697            .on_post_scroll(
698                move |consumed: Vec2, available: Vec2, _source: NestedScrollSource| -> Vec2 {
699                    if available.x.abs() < 0.001 && available.y.abs() < 0.001 {
700                        return Vec2::ZERO;
701                    }
702                    let leftover_y = this.scroll_nested(available.y);
703                    let own_consumed = available.y - leftover_y;
704                    let after = run_post_scroll(
705                        &pc,
706                        Vec2 {
707                            x: consumed.x,
708                            y: consumed.y + own_consumed,
709                        },
710                        Vec2 {
711                            x: available.x,
712                            y: leftover_y,
713                        },
714                        NestedScrollSource::UserInput,
715                    );
716                    Vec2 {
717                        x: available.x - after.x,
718                        y: available.y - after.y,
719                    }
720                },
721            )
722            .on_post_fling(
723                move |_consumed: Vec2, available: Vec2, _source: NestedScrollSource| -> Vec2 {
724                    fling_target.fling(available);
725                    available
726                },
727            )
728    }
729
730    pub fn set_show_scrollbar(&self, show: bool) {
731        self.show_scrollbar.set(show);
732    }
733
734    /// Reverse layout (Compose `reverseLayout`): offset 0 sits at the end of
735    /// the track and the thumb mapping runs backwards. Call before
736    /// `to_binding`; the binding snapshots the flag like `show_scrollbar`.
737    pub fn set_reversed(&self, reversed: bool) {
738        self.reversed.set(reversed);
739    }
740
741    pub fn set_viewport_height(&self, h: f32) {
742        let h = h.max(0.0);
743        if (self.viewport_height.get() - h).abs() > 0.5 {
744            self.viewport_height.set(h);
745            self.clamp_offset();
746        }
747    }
748
749    pub fn set_content_height(&self, h: f32) {
750        let h = h.max(0.0);
751        if (self.content_height.get() - h).abs() > 0.5 {
752            self.content_height.set(h);
753            self.clamp_offset();
754        }
755    }
756
757    pub fn set_overscroll(&self, val: f32) {
758        self.overscroll.set(val);
759    }
760
761    pub fn set_offset(&self, off: f32) {
762        let off = if off.is_finite() { off } else { 0.0 };
763        let vh = self.viewport_height.get();
764        let ch = self.content_height.get();
765        let max_off = (ch - vh).max(0.0);
766        self.scroll_offset.set(clamp_offset(off, max_off));
767    }
768
769    fn clamp_offset(&self) {
770        let vh = self.viewport_height.get();
771        let ch = self.content_height.get();
772        let max_off = (ch - vh).max(0.0);
773        self.scroll_offset.update(|o| {
774            if *o > max_off {
775                *o = max_off;
776            }
777            if *o < 0.0 {
778                *o = 0.0;
779            }
780        });
781    }
782
783    pub fn get(&self) -> f32 {
784        self.scroll_offset.get()
785    }
786
787    /// Apply a scroll delta from real user input. Pre-empts any in-flight
788    /// fling, matching Compose where a new `scroll(UserInput)` cancels the
789    /// fling coroutine holding the `MutatorMutex`.
790    pub fn scroll_immediate(&self, dy: f32) -> f32 {
791        self.apply_delta(dy, DeltaVelocity::User)
792    }
793
794    /// Apply a delta that arrived as leftover from a nested child. This is
795    /// Compose's `dispatchRawDelta`: it bypasses mutual exclusion, so it must
796    /// not cancel this container's own fling.
797    pub fn scroll_nested(&self, dy: f32) -> f32 {
798        self.apply_delta(dy, DeltaVelocity::Nested)
799    }
800
801    /// Apply a delta while honouring what produced it. Wheel deltas move the
802    /// surface but start no fling; touch deltas keep the usual velocity
803    /// tracking. `scroll_immediate` and `scroll_nested` remain unchanged.
804    pub fn apply_delta_with_source(&self, dy: f32, source: ScrollSource) -> f32 {
805        let mode = if source == ScrollSource::Wheel {
806            DeltaVelocity::Wheel
807        } else {
808            DeltaVelocity::User
809        };
810        self.apply_delta(dy, mode)
811    }
812
813    fn apply_delta(&self, dy: f32, mode: DeltaVelocity) -> f32 {
814        let dy = if dy.is_finite() { dy } else { 0.0 };
815        let before = self.scroll_offset.get();
816        let vh = self.viewport_height.get();
817        let ch = self.content_height.get();
818        let max_off = (ch - vh).max(0.0);
819
820        let new_off = clamp_offset(before + dy, max_off);
821        self.scroll_offset.set(new_off);
822        let consumed = new_off - before;
823        match mode {
824            DeltaVelocity::User => {
825                self.fling_dispatched.set(false);
826                self.physics.borrow_mut().record_user_input(consumed);
827            }
828            DeltaVelocity::Nested => self.physics.borrow_mut().record_nested_input(consumed),
829            DeltaVelocity::Wheel => self.physics.borrow_mut().clear_velocity(),
830        }
831        dy - consumed
832    }
833
834    /// Seed a fling from a velocity (px/s), for example velocity handed over
835    /// by a parent through `NestedScrollConnection::dispatch_post_fling`.
836    pub fn fling(&self, velocity: Vec2) {
837        self.fling_dispatched.set(false);
838        self.physics.borrow_mut().set_fling_velocity(velocity.y);
839        request_frame();
840    }
841
842    fn dispatch_post_fling(&self, velocity: Vec2) {
843        if self.fling_dispatched.get() {
844            return;
845        }
846        if let Some(ref parent) = *self.parent_connection.borrow() {
847            self.fling_dispatched.set(true);
848            parent.dispatch_post_fling(Vec2::ZERO, velocity, NestedScrollSource::UserInput);
849        }
850    }
851
852    /// Feed leftover (after the nested parent chain has had its chance via
853    /// post-scroll) into the rubber-band overscroll. Returns the amount still
854    /// unconsumed. Overscroll deliberately runs LAST so parents get first dibs.
855    pub fn apply_overscroll(&self, leftover: f32) -> f32 {
856        let vh = self.viewport_height.get();
857        let ch = self.content_height.get();
858        os_scroll_axis(
859            &self.scroll_offset,
860            &self.overscroll,
861            self.overscroll_enabled.get(),
862            (ch - vh).max(0.0),
863            self.scroll_offset.get(),
864            leftover,
865            &self.physics,
866        )
867    }
868
869    pub fn tick(&self) -> bool {
870        let now = Instant::now();
871        let dt = (now - self.prev_tick.get()).as_secs_f32().min(0.1);
872        self.prev_tick.set(now);
873
874        if tick_os_axis(&self.overscroll, self.overscroll_enabled.get(), dt) {
875            return true;
876        }
877
878        let vh = self.viewport_height.get();
879        let ch = self.content_height.get();
880        let max_off = (ch - vh).max(0.0);
881
882        let mut p = self.physics.borrow_mut();
883        if let Some(new_off) = p.tick_integrate(self.scroll_offset.get(), 0.0, max_off) {
884            drop(p);
885            self.scroll_offset.set(new_off);
886            request_frame();
887            true
888        } else {
889            let clamped_velocity = p.take_clamped_velocity();
890            drop(p);
891            if let Some(v) = clamped_velocity {
892                self.dispatch_post_fling(Vec2 { x: 0.0, y: v });
893            }
894            false
895        }
896    }
897
898    pub fn show_scrollbar(&self) -> bool {
899        self.show_scrollbar.get()
900    }
901
902    /// Build a `ScrollBinding::Vertical` from this state for use with `Modifier::vertical_scroll`.
903    pub fn to_binding(&self) -> ScrollBinding {
904        let this = Rc::new(self.clone());
905        let pc = Rc::clone(&this.parent_connection);
906        let c_on_scroll_with_source = {
907            let state = Rc::clone(&pc);
908            let this = Rc::clone(&this);
909            Rc::new(move |d: Vec2, source: ScrollSource| -> Vec2 {
910                let available = run_pre_scroll(&state, d);
911                let pre_consumed = d - available;
912                // Clamp this scroller first; leftover goes to the nested parent
913                // chain (post-scroll) BEFORE rubber-band overscroll.
914                let leftover_y = this.apply_delta_with_source(available.y, source);
915                let result = Vec2 {
916                    x: available.x,
917                    y: leftover_y,
918                };
919                let consumed = pre_consumed
920                    + Vec2 {
921                        x: 0.0,
922                        y: available.y - leftover_y,
923                    };
924                let after_parent =
925                    run_post_scroll(&state, consumed, result, NestedScrollSource::UserInput);
926                let final_y = this.apply_overscroll(after_parent.y);
927                Vec2 {
928                    x: after_parent.x,
929                    y: final_y,
930                }
931            })
932        } as Rc<dyn Fn(Vec2, ScrollSource) -> Vec2>;
933        let c_on_scroll = {
934            let source_aware = Rc::clone(&c_on_scroll_with_source);
935            Rc::new(move |d: Vec2| source_aware(d, ScrollSource::Touch))
936        } as Rc<dyn Fn(Vec2) -> Vec2>;
937        let c_set_viewport = {
938            let this = Rc::clone(&this);
939            Rc::new(move |h: f32| this.set_viewport_height(h))
940        };
941        let c_set_content = {
942            let this = Rc::clone(&this);
943            Rc::new(move |h: f32| this.set_content_height(h))
944        };
945        let c_get = {
946            let this = Rc::clone(&this);
947            Rc::new(move || this.get() + this.overscroll_offset())
948        };
949        let c_set = {
950            let this = Rc::clone(&this);
951            Rc::new(move |off: f32| this.set_offset(off))
952        };
953        let c_tick = {
954            let this = Rc::clone(&this);
955            Rc::new(move || {
956                this.tick();
957            })
958        };
959        let c_set_nested = {
960            let state = Rc::clone(&pc);
961            Rc::new(move |conn| {
962                *state.borrow_mut() = Some(conn);
963            })
964        };
965        ScrollBinding::Vertical(ScrollAxisBinding {
966            on_scroll: Some(c_on_scroll),
967            on_scroll_with_source: Some(c_on_scroll_with_source),
968            set_viewport_main: Some(c_set_viewport),
969            set_content_main: Some(c_set_content),
970            get_offset_main: Some(c_get),
971            set_offset_main: Some(c_set),
972            reversed: this.reversed.get(),
973            show_scrollbar: self.show_scrollbar(),
974            tick: Some(c_tick),
975            set_nested_scroll_parent: Some(c_set_nested),
976        })
977    }
978}
979
980/// X-only state
981#[derive(Clone)]
982pub struct HorizontalScrollState {
983    scroll_offset: Signal<f32>,
984    viewport_width: Signal<f32>,
985    content_width: Signal<f32>,
986    physics: Rc<RefCell<ScrollPhysics>>,
987    overscroll: Signal<f32>,
988    overscroll_enabled: Cell<bool>,
989    pub(crate) parent_connection: Rc<RefCell<Option<NestedScrollConnection>>>,
990    show_scrollbar: Cell<bool>,
991    reversed: Rc<Cell<bool>>,
992    prev_tick: Cell<Instant>,
993    fling_dispatched: Cell<bool>,
994}
995
996impl Default for HorizontalScrollState {
997    fn default() -> Self {
998        Self::new()
999    }
1000}
1001
1002impl HorizontalScrollState {
1003    pub fn new() -> Self {
1004        Self {
1005            scroll_offset: signal(0.0),
1006            viewport_width: signal(0.0),
1007            content_width: signal(0.0),
1008            physics: Rc::new(RefCell::new(ScrollPhysics::new())),
1009            overscroll: signal(0.0),
1010            overscroll_enabled: Cell::new(true),
1011            parent_connection: Rc::new(RefCell::new(None)),
1012            show_scrollbar: Cell::new(true),
1013            reversed: Rc::new(Cell::new(false)),
1014            prev_tick: Cell::new(Instant::now()),
1015            fling_dispatched: Cell::new(false),
1016        }
1017    }
1018
1019    pub fn set_overscroll_enabled(&self, enabled: bool) {
1020        self.overscroll_enabled.set(enabled);
1021    }
1022
1023    pub fn overscroll_offset(&self) -> f32 {
1024        self.overscroll.get()
1025    }
1026
1027    pub fn set_nested_scroll_parent(&self, conn: NestedScrollConnection) {
1028        *self.parent_connection.borrow_mut() = Some(conn);
1029    }
1030
1031    /// A `NestedScrollConnection` that consumes leftover scroll by scrolling
1032    /// THIS container, then chains anything still unabsorbed up to this
1033    /// container's own parent connection.
1034    pub fn connection(&self) -> NestedScrollConnection {
1035        let this = Rc::new(self.clone());
1036        let pc = Rc::clone(&this.parent_connection);
1037        let fling_target = Rc::clone(&this);
1038        NestedScrollConnection::new()
1039            .on_post_scroll(
1040                move |consumed: Vec2, available: Vec2, _source: NestedScrollSource| -> Vec2 {
1041                    if available.x.abs() < 0.001 && available.y.abs() < 0.001 {
1042                        return Vec2::ZERO;
1043                    }
1044                    let leftover_x = this.scroll_nested(available.x);
1045                    let own_consumed = available.x - leftover_x;
1046                    let after = run_post_scroll(
1047                        &pc,
1048                        Vec2 {
1049                            x: consumed.x + own_consumed,
1050                            y: consumed.y,
1051                        },
1052                        Vec2 {
1053                            x: leftover_x,
1054                            y: available.y,
1055                        },
1056                        NestedScrollSource::UserInput,
1057                    );
1058                    Vec2 {
1059                        x: available.x - after.x,
1060                        y: available.y - after.y,
1061                    }
1062                },
1063            )
1064            .on_post_fling(
1065                move |_consumed: Vec2, available: Vec2, _source: NestedScrollSource| -> Vec2 {
1066                    fling_target.fling(available);
1067                    available
1068                },
1069            )
1070    }
1071
1072    pub fn set_show_scrollbar(&self, show: bool) {
1073        self.show_scrollbar.set(show);
1074    }
1075
1076    /// Reverse layout (Compose `reverseLayout`): offset 0 sits at the end of
1077    /// the track and the thumb mapping runs backwards. Call before
1078    /// `to_binding`; the binding snapshots the flag like `show_scrollbar`.
1079    pub fn set_reversed(&self, reversed: bool) {
1080        self.reversed.set(reversed);
1081    }
1082
1083    pub fn set_viewport_width(&self, w: f32) {
1084        let w = w.max(0.0);
1085        if (self.viewport_width.get() - w).abs() > 0.5 {
1086            self.viewport_width.set(w);
1087            self.clamp();
1088        }
1089    }
1090
1091    pub fn set_content_width(&self, w: f32) {
1092        let w = w.max(0.0);
1093        if (self.content_width.get() - w).abs() > 0.5 {
1094            self.content_width.set(w);
1095            self.clamp();
1096        }
1097    }
1098
1099    pub fn set_overscroll(&self, val: f32) {
1100        self.overscroll.set(val);
1101    }
1102
1103    pub fn set_offset(&self, off: f32) {
1104        let max_off = (self.content_width.get() - self.viewport_width.get()).max(0.0);
1105        self.scroll_offset.set(clamp_offset(off, max_off));
1106    }
1107
1108    fn clamp(&self) {
1109        let max_off = (self.content_width.get() - self.viewport_width.get()).max(0.0);
1110        self.scroll_offset.update(|o| {
1111            *o = clamp_offset(*o, max_off);
1112        });
1113    }
1114
1115    pub fn get(&self) -> f32 {
1116        self.scroll_offset.get()
1117    }
1118
1119    /// Apply a scroll delta from real user input; pre-empts any in-flight
1120    /// fling. See [`ScrollState::scroll_immediate`].
1121    pub fn scroll_immediate(&self, dx: f32) -> f32 {
1122        self.apply_delta(dx, DeltaVelocity::User)
1123    }
1124
1125    /// Apply leftover from a nested child without cancelling this container's
1126    /// own fling. See [`ScrollState::scroll_nested`].
1127    pub fn scroll_nested(&self, dx: f32) -> f32 {
1128        self.apply_delta(dx, DeltaVelocity::Nested)
1129    }
1130
1131    /// Source-aware delta application; wheel deltas never seed a fling.
1132    pub fn apply_delta_with_source(&self, dx: f32, source: ScrollSource) -> f32 {
1133        let mode = if source == ScrollSource::Wheel {
1134            DeltaVelocity::Wheel
1135        } else {
1136            DeltaVelocity::User
1137        };
1138        self.apply_delta(dx, mode)
1139    }
1140
1141    fn apply_delta(&self, dx: f32, mode: DeltaVelocity) -> f32 {
1142        let dx = if dx.is_finite() { dx } else { 0.0 };
1143        let before = self.scroll_offset.get();
1144        let max_off = (self.content_width.get() - self.viewport_width.get()).max(0.0);
1145
1146        let new_off = clamp_offset(before + dx, max_off);
1147        self.scroll_offset.set(new_off);
1148        let consumed = new_off - before;
1149        match mode {
1150            DeltaVelocity::User => {
1151                self.fling_dispatched.set(false);
1152                self.physics.borrow_mut().record_user_input(consumed);
1153            }
1154            DeltaVelocity::Nested => self.physics.borrow_mut().record_nested_input(consumed),
1155            DeltaVelocity::Wheel => self.physics.borrow_mut().clear_velocity(),
1156        }
1157        dx - consumed
1158    }
1159
1160    /// Seed a fling from a velocity (px/s).
1161    pub fn fling(&self, velocity: Vec2) {
1162        self.fling_dispatched.set(false);
1163        self.physics.borrow_mut().set_fling_velocity(velocity.x);
1164        request_frame();
1165    }
1166
1167    fn dispatch_post_fling(&self, velocity: Vec2) {
1168        if self.fling_dispatched.get() {
1169            return;
1170        }
1171        if let Some(ref parent) = *self.parent_connection.borrow() {
1172            self.fling_dispatched.set(true);
1173            parent.dispatch_post_fling(Vec2::ZERO, velocity, NestedScrollSource::UserInput);
1174        }
1175    }
1176
1177    /// Feed leftover (after the nested parent chain) into rubber-band overscroll.
1178    pub fn apply_overscroll(&self, leftover: f32) -> f32 {
1179        let max_off = (self.content_width.get() - self.viewport_width.get()).max(0.0);
1180        os_scroll_axis(
1181            &self.scroll_offset,
1182            &self.overscroll,
1183            self.overscroll_enabled.get(),
1184            max_off,
1185            self.scroll_offset.get(),
1186            leftover,
1187            &self.physics,
1188        )
1189    }
1190
1191    pub fn tick(&self) -> bool {
1192        let now = Instant::now();
1193        let dt = (now - self.prev_tick.get()).as_secs_f32().min(0.1);
1194        self.prev_tick.set(now);
1195
1196        if tick_os_axis(&self.overscroll, self.overscroll_enabled.get(), dt) {
1197            return true;
1198        }
1199
1200        let max_off = (self.content_width.get() - self.viewport_width.get()).max(0.0);
1201        let mut p = self.physics.borrow_mut();
1202        if let Some(new_off) = p.tick_integrate(self.scroll_offset.get(), 0.0, max_off) {
1203            drop(p);
1204            self.scroll_offset.set(new_off);
1205            request_frame();
1206            true
1207        } else {
1208            let clamped_velocity = p.take_clamped_velocity();
1209            drop(p);
1210            if let Some(v) = clamped_velocity {
1211                self.dispatch_post_fling(Vec2 { x: v, y: 0.0 });
1212            }
1213            false
1214        }
1215    }
1216
1217    pub fn show_scrollbar(&self) -> bool {
1218        self.show_scrollbar.get()
1219    }
1220
1221    pub fn to_binding(&self) -> ScrollBinding {
1222        let this = Rc::new(self.clone());
1223        let pc = Rc::clone(&this.parent_connection);
1224        let c_on_scroll_with_source = {
1225            let state = Rc::clone(&pc);
1226            let this = Rc::clone(&this);
1227            Rc::new(move |d: Vec2, source: ScrollSource| -> Vec2 {
1228                let available = run_pre_scroll(&state, d);
1229                let pre_consumed = d - available;
1230                let leftover_x = this.apply_delta_with_source(available.x, source);
1231                let result = Vec2 {
1232                    x: leftover_x,
1233                    y: available.y,
1234                };
1235                let consumed = pre_consumed
1236                    + Vec2 {
1237                        x: available.x - leftover_x,
1238                        y: 0.0,
1239                    };
1240                let after_parent =
1241                    run_post_scroll(&state, consumed, result, NestedScrollSource::UserInput);
1242                let final_x = this.apply_overscroll(after_parent.x);
1243                Vec2 {
1244                    x: final_x,
1245                    y: after_parent.y,
1246                }
1247            })
1248        } as Rc<dyn Fn(Vec2, ScrollSource) -> Vec2>;
1249        let c_on_scroll = {
1250            let source_aware = Rc::clone(&c_on_scroll_with_source);
1251            Rc::new(move |d: Vec2| source_aware(d, ScrollSource::Touch))
1252        } as Rc<dyn Fn(Vec2) -> Vec2>;
1253        let c_set_vp = {
1254            let this = Rc::clone(&this);
1255            Rc::new(move |w: f32| this.set_viewport_width(w))
1256        };
1257        let c_set_ct = {
1258            let this = Rc::clone(&this);
1259            Rc::new(move |w: f32| this.set_content_width(w))
1260        };
1261        let c_get = {
1262            let this = Rc::clone(&this);
1263            Rc::new(move || this.get() + this.overscroll_offset())
1264        };
1265        let c_set = {
1266            let this = Rc::clone(&this);
1267            Rc::new(move |off: f32| this.set_offset(off))
1268        };
1269        let c_tick = {
1270            let this = Rc::clone(&this);
1271            Rc::new(move || {
1272                this.tick();
1273            })
1274        };
1275        let c_set_nested = {
1276            let state = Rc::clone(&pc);
1277            Rc::new(move |conn| {
1278                *state.borrow_mut() = Some(conn);
1279            })
1280        };
1281        ScrollBinding::Horizontal(ScrollAxisBinding {
1282            on_scroll: Some(c_on_scroll),
1283            on_scroll_with_source: Some(c_on_scroll_with_source),
1284            set_viewport_main: Some(c_set_vp),
1285            set_content_main: Some(c_set_ct),
1286            get_offset_main: Some(c_get),
1287            set_offset_main: Some(c_set),
1288            reversed: this.reversed.get(),
1289            show_scrollbar: this.show_scrollbar(),
1290            tick: Some(c_tick),
1291            set_nested_scroll_parent: Some(c_set_nested),
1292        })
1293    }
1294}
1295
1296/// 2D state
1297#[derive(Clone)]
1298pub struct ScrollStateXY {
1299    off_x: Signal<f32>,
1300    off_y: Signal<f32>,
1301    vp_w: Signal<f32>,
1302    vp_h: Signal<f32>,
1303    c_w: Signal<f32>,
1304    c_h: Signal<f32>,
1305    physics_x: Rc<RefCell<ScrollPhysics>>,
1306    physics_y: Rc<RefCell<ScrollPhysics>>,
1307    os_x: Signal<f32>,
1308    os_y: Signal<f32>,
1309    overscroll_enabled: Cell<bool>,
1310    pub(crate) parent_connection: Rc<RefCell<Option<NestedScrollConnection>>>,
1311    show_scrollbar: Cell<bool>,
1312    reversed_x: Rc<Cell<bool>>,
1313    reversed_y: Rc<Cell<bool>>,
1314    prev_tick: Cell<Instant>,
1315    fling_dispatched: Cell<bool>,
1316}
1317
1318impl Default for ScrollStateXY {
1319    fn default() -> Self {
1320        Self::new()
1321    }
1322}
1323
1324impl ScrollStateXY {
1325    pub fn new() -> Self {
1326        Self {
1327            off_x: signal(0.0),
1328            off_y: signal(0.0),
1329            vp_w: signal(0.0),
1330            vp_h: signal(0.0),
1331            c_w: signal(0.0),
1332            c_h: signal(0.0),
1333            physics_x: Rc::new(RefCell::new(ScrollPhysics::new())),
1334            physics_y: Rc::new(RefCell::new(ScrollPhysics::new())),
1335            os_x: signal(0.0),
1336            os_y: signal(0.0),
1337            overscroll_enabled: Cell::new(true),
1338            parent_connection: Rc::new(RefCell::new(None)),
1339            show_scrollbar: Cell::new(true),
1340            reversed_x: Rc::new(Cell::new(false)),
1341            reversed_y: Rc::new(Cell::new(false)),
1342            prev_tick: Cell::new(Instant::now()),
1343            fling_dispatched: Cell::new(false),
1344        }
1345    }
1346
1347    pub fn set_overscroll_enabled(&self, enabled: bool) {
1348        self.overscroll_enabled.set(enabled);
1349    }
1350
1351    pub fn set_show_scrollbar(&self, show: bool) {
1352        self.show_scrollbar.set(show);
1353    }
1354
1355    /// Reverse layout per axis (Compose `reverseLayout`); see
1356    /// `ScrollState::set_reversed`. Snapshotted by `to_binding`.
1357    pub fn set_reversed_x(&self, reversed: bool) {
1358        self.reversed_x.set(reversed);
1359    }
1360
1361    /// Reverse layout per axis (Compose `reverseLayout`); see
1362    /// `ScrollState::set_reversed`. Snapshotted by `to_binding`.
1363    pub fn set_reversed_y(&self, reversed: bool) {
1364        self.reversed_y.set(reversed);
1365    }
1366
1367    pub fn overscroll_offset(&self) -> (f32, f32) {
1368        (self.os_x.get(), self.os_y.get())
1369    }
1370
1371    pub fn set_nested_scroll_parent(&self, conn: NestedScrollConnection) {
1372        *self.parent_connection.borrow_mut() = Some(conn);
1373    }
1374
1375    /// A `NestedScrollConnection` that consumes leftover scroll by scrolling
1376    /// THIS container, then chains anything still unabsorbed up to this
1377    /// container's own parent connection.
1378    pub fn connection(&self) -> NestedScrollConnection {
1379        let this = Rc::new(self.clone());
1380        let pc = Rc::clone(&this.parent_connection);
1381        let fling_target = Rc::clone(&this);
1382        NestedScrollConnection::new()
1383            .on_post_scroll(
1384                move |consumed: Vec2, available: Vec2, _source: NestedScrollSource| -> Vec2 {
1385                    if available.x.abs() < 0.001 && available.y.abs() < 0.001 {
1386                        return Vec2::ZERO;
1387                    }
1388                    let leftover = this.scroll_nested(available);
1389                    let own_consumed = available - leftover;
1390                    let after2 = run_post_scroll(
1391                        &pc,
1392                        consumed + own_consumed,
1393                        leftover,
1394                        NestedScrollSource::UserInput,
1395                    );
1396                    Vec2 {
1397                        x: available.x - after2.x,
1398                        y: available.y - after2.y,
1399                    }
1400                },
1401            )
1402            .on_post_fling(
1403                move |_consumed: Vec2, available: Vec2, _source: NestedScrollSource| -> Vec2 {
1404                    fling_target.fling(available);
1405                    available
1406                },
1407            )
1408    }
1409
1410    pub fn set_viewport(&self, w: f32, h: f32) {
1411        let w = w.max(0.0);
1412        let h = h.max(0.0);
1413        let changed = (self.vp_w.get() - w).abs() > 0.5 || (self.vp_h.get() - h).abs() > 0.5;
1414        if changed {
1415            self.vp_w.set(w);
1416            self.vp_h.set(h);
1417            self.clamp();
1418        }
1419    }
1420    pub fn set_content(&self, w: f32, h: f32) {
1421        let w = w.max(0.0);
1422        let h = h.max(0.0);
1423        let changed = (self.c_w.get() - w).abs() > 0.5 || (self.c_h.get() - h).abs() > 0.5;
1424        if changed {
1425            self.c_w.set(w);
1426            self.c_h.set(h);
1427            self.clamp();
1428        }
1429    }
1430    pub fn set_offset_xy(&self, x: f32, y: f32) {
1431        let max_x = (self.c_w.get() - self.vp_w.get()).max(0.0);
1432        let max_y = (self.c_h.get() - self.vp_h.get()).max(0.0);
1433        self.off_x.set(clamp_offset(x, max_x));
1434        self.off_y.set(clamp_offset(y, max_y));
1435    }
1436    fn clamp(&self) {
1437        let max_x = (self.c_w.get() - self.vp_w.get()).max(0.0);
1438        let max_y = (self.c_h.get() - self.vp_h.get()).max(0.0);
1439        self.off_x.update(|x| *x = clamp_offset(*x, max_x));
1440        self.off_y.update(|y| *y = clamp_offset(*y, max_y));
1441    }
1442    pub fn get(&self) -> (f32, f32) {
1443        (self.off_x.get(), self.off_y.get())
1444    }
1445
1446    fn os_scroll_axis(
1447        off: &Signal<f32>,
1448        os: &Signal<f32>,
1449        overscroll_enabled: bool,
1450        max_off: f32,
1451        before: f32,
1452        leftover: f32,
1453        physics: &RefCell<ScrollPhysics>,
1454    ) -> f32 {
1455        if !overscroll_enabled || leftover.abs() < 0.001 {
1456            return leftover;
1457        }
1458        let os_val = os.get();
1459        // Recovering from an active rubber band: absorb the reverse delta first.
1460        if os_val.abs() > 0.5 && os_val.signum() * leftover < 0.0 {
1461            let reduction = leftover.abs().min(os_val.abs());
1462            os.set(os_val - os_val.signum() * reduction);
1463            let remainder = leftover - leftover.signum() * reduction;
1464            if remainder.abs() > 0.5 {
1465                let new_off = clamp_offset(before + remainder, max_off);
1466                off.set(new_off);
1467                let consumed = new_off - before;
1468                physics.borrow_mut().record_nested_input(consumed);
1469                return remainder - consumed;
1470            }
1471            return 0.0;
1472        }
1473
1474        // At the edge, pushing further: stretch the rubber band.
1475        let at_edge = (before <= 0.0 && leftover < 0.0) || (before >= max_off && leftover > 0.0);
1476        if max_off > 5.0 && at_edge && leftover.abs() > 0.5 {
1477            os.set(os_val + rubber_band(leftover, SCROLL_OVERSROLL_BAND_MAX));
1478            physics.borrow_mut().record_nested_input(0.0);
1479            return 0.0;
1480        }
1481        leftover
1482    }
1483    /// Apply a scroll delta from real user input; pre-empts any in-flight
1484    /// fling. See [`ScrollState::scroll_immediate`].
1485    pub fn scroll_immediate(&self, d: Vec2) -> Vec2 {
1486        self.apply_delta(d, DeltaVelocity::User)
1487    }
1488
1489    /// Apply leftover from a nested child without cancelling this container's
1490    /// own fling. See [`ScrollState::scroll_nested`].
1491    pub fn scroll_nested(&self, d: Vec2) -> Vec2 {
1492        self.apply_delta(d, DeltaVelocity::Nested)
1493    }
1494
1495    /// Source-aware delta application; wheel deltas never seed a fling.
1496    pub fn apply_delta_with_source(&self, d: Vec2, source: ScrollSource) -> Vec2 {
1497        let mode = if source == ScrollSource::Wheel {
1498            DeltaVelocity::Wheel
1499        } else {
1500            DeltaVelocity::User
1501        };
1502        self.apply_delta(d, mode)
1503    }
1504
1505    fn apply_delta(&self, d: Vec2, mode: DeltaVelocity) -> Vec2 {
1506        let d = Vec2 {
1507            x: if d.x.is_finite() { d.x } else { 0.0 },
1508            y: if d.y.is_finite() { d.y } else { 0.0 },
1509        };
1510        let max_x = (self.c_w.get() - self.vp_w.get()).max(0.0);
1511        let max_y = (self.c_h.get() - self.vp_h.get()).max(0.0);
1512        let (bx, by) = (self.off_x.get(), self.off_y.get());
1513
1514        let nx = clamp_offset(bx + d.x, max_x);
1515        let ny = clamp_offset(by + d.y, max_y);
1516        self.off_x.set(nx);
1517        self.off_y.set(ny);
1518        let (cx, cy) = (nx - bx, ny - by);
1519
1520        let mut px = self.physics_x.borrow_mut();
1521        let mut py = self.physics_y.borrow_mut();
1522        match mode {
1523            DeltaVelocity::User => {
1524                self.fling_dispatched.set(false);
1525                px.record_user_input(cx);
1526                py.record_user_input(cy);
1527            }
1528            DeltaVelocity::Nested => {
1529                px.record_nested_input(cx);
1530                py.record_nested_input(cy);
1531            }
1532            DeltaVelocity::Wheel => {
1533                px.clear_velocity();
1534                py.clear_velocity();
1535            }
1536        }
1537        drop((px, py));
1538
1539        Vec2 {
1540            x: d.x - cx,
1541            y: d.y - cy,
1542        }
1543    }
1544
1545    /// Seed a fling from a velocity (px/s) on both axes.
1546    pub fn fling(&self, velocity: Vec2) {
1547        self.fling_dispatched.set(false);
1548        self.physics_x.borrow_mut().set_fling_velocity(velocity.x);
1549        self.physics_y.borrow_mut().set_fling_velocity(velocity.y);
1550        request_frame();
1551    }
1552
1553    fn dispatch_post_fling(&self, velocity: Vec2) {
1554        if self.fling_dispatched.get() {
1555            return;
1556        }
1557        if let Some(ref parent) = *self.parent_connection.borrow() {
1558            self.fling_dispatched.set(true);
1559            parent.dispatch_post_fling(Vec2::ZERO, velocity, NestedScrollSource::UserInput);
1560        }
1561    }
1562
1563    /// Feed leftover (after the nested parent chain) into rubber-band overscroll.
1564    pub fn apply_overscroll(&self, d: Vec2) -> Vec2 {
1565        let max_x = (self.c_w.get() - self.vp_w.get()).max(0.0);
1566        let max_y = (self.c_h.get() - self.vp_h.get()).max(0.0);
1567        let (bx, by) = (self.off_x.get(), self.off_y.get());
1568
1569        let lx = Self::os_scroll_axis(
1570            &self.off_x,
1571            &self.os_x,
1572            self.overscroll_enabled.get(),
1573            max_x,
1574            bx,
1575            d.x,
1576            &self.physics_x,
1577        );
1578        let ly = Self::os_scroll_axis(
1579            &self.off_y,
1580            &self.os_y,
1581            self.overscroll_enabled.get(),
1582            max_y,
1583            by,
1584            d.y,
1585            &self.physics_y,
1586        );
1587        Vec2 { x: lx, y: ly }
1588    }
1589    pub fn tick(&self) -> bool {
1590        let now = Instant::now();
1591        let dt = (now - self.prev_tick.get()).as_secs_f32().min(0.1);
1592        self.prev_tick.set(now);
1593
1594        {
1595            let mut px = self.physics_x.borrow_mut();
1596            let mut py = self.physics_y.borrow_mut();
1597            px.sync_generation();
1598            py.sync_generation();
1599            px.settle_after_touch();
1600            py.settle_after_touch();
1601        }
1602        if touch_gesture_active() {
1603            return false;
1604        }
1605
1606        if self.overscroll_enabled.get()
1607            && (tick_os_axis(&self.os_x, true, dt) || tick_os_axis(&self.os_y, true, dt))
1608        {
1609            return true;
1610        }
1611
1612        let max_x = (self.c_w.get() - self.vp_w.get()).max(0.0);
1613        let max_y = (self.c_h.get() - self.vp_h.get()).max(0.0);
1614        let (bx, by) = (self.off_x.get(), self.off_y.get());
1615
1616        let mut px = self.physics_x.borrow_mut();
1617        let mut py = self.physics_y.borrow_mut();
1618        if !px.animating && !py.animating {
1619            return false;
1620        }
1621        if px.input_pending {
1622            px.input_pending = false;
1623        } else if px.animating {
1624            if px.vel.abs() < px.stop_velocity {
1625                px.vel = 0.0;
1626                px.animating = false;
1627            } else {
1628                let nx = clamp_offset(bx + px.vel * dt, max_x);
1629                if (nx - bx).abs() < 0.01 && (bx <= 0.0 || bx >= max_x) {
1630                    px.clamped_velocity = Some(px.vel);
1631                    px.vel = 0.0;
1632                    px.animating = false;
1633                } else {
1634                    let speed = px.vel.abs();
1635                    let t = (speed / 4000.0).min(1.0);
1636                    let effective_decay = 0.85 + t * 0.10;
1637                    px.vel *= effective_decay.powf(dt * 60.0);
1638                    if px.vel.abs() < px.stop_velocity {
1639                        px.vel = 0.0;
1640                        px.animating = false;
1641                    } else {
1642                        self.off_x.set(nx);
1643                    }
1644                }
1645            }
1646        }
1647        if py.input_pending {
1648            py.input_pending = false;
1649        } else if py.animating {
1650            if py.vel.abs() < py.stop_velocity {
1651                py.vel = 0.0;
1652                py.animating = false;
1653            } else {
1654                let ny = clamp_offset(by + py.vel * dt, max_y);
1655                if (ny - by).abs() < 0.01 && (by <= 0.0 || by >= max_y) {
1656                    py.clamped_velocity = Some(py.vel);
1657                    py.vel = 0.0;
1658                    py.animating = false;
1659                } else {
1660                    let speed = py.vel.abs();
1661                    let t = (speed / 4000.0).min(1.0);
1662                    let effective_decay = 0.85 + t * 0.10;
1663                    py.vel *= effective_decay.powf(dt * 60.0);
1664                    if py.vel.abs() < py.stop_velocity {
1665                        py.vel = 0.0;
1666                        py.animating = false;
1667                    } else {
1668                        self.off_y.set(ny);
1669                    }
1670                }
1671            }
1672        }
1673        let running = px.animating || py.animating;
1674        let clamped_x = px.take_clamped_velocity();
1675        let clamped_y = py.take_clamped_velocity();
1676        drop((px, py));
1677        if running {
1678            request_frame();
1679        }
1680        if clamped_x.is_some() || clamped_y.is_some() {
1681            self.dispatch_post_fling(Vec2 {
1682                x: clamped_x.unwrap_or(0.0),
1683                y: clamped_y.unwrap_or(0.0),
1684            });
1685        }
1686        running
1687    }
1688
1689    pub fn show_scrollbar(&self) -> bool {
1690        self.show_scrollbar.get()
1691    }
1692
1693    pub fn to_binding(&self) -> ScrollBinding {
1694        let this = Rc::new(self.clone());
1695        let pc = Rc::clone(&this.parent_connection);
1696        let c_on_scroll_with_source = {
1697            let state = Rc::clone(&pc);
1698            let this = Rc::clone(&this);
1699            Rc::new(move |d: Vec2, source: ScrollSource| -> Vec2 {
1700                let available = run_pre_scroll(&state, d);
1701                let pre_consumed = d - available;
1702                let result = this.apply_delta_with_source(available, source);
1703                let consumed = pre_consumed + (available - result);
1704                let after_parent =
1705                    run_post_scroll(&state, consumed, result, NestedScrollSource::UserInput);
1706                this.apply_overscroll(after_parent)
1707            })
1708        } as Rc<dyn Fn(Vec2, ScrollSource) -> Vec2>;
1709        let c_on_scroll = {
1710            let source_aware = Rc::clone(&c_on_scroll_with_source);
1711            Rc::new(move |d: Vec2| source_aware(d, ScrollSource::Touch))
1712        } as Rc<dyn Fn(Vec2) -> Vec2>;
1713        let c_set_vw = {
1714            let this = Rc::clone(&this);
1715            Rc::new(move |w: f32| this.set_viewport(w, this.vp_h.get()))
1716        };
1717        let c_set_vh = {
1718            let this = Rc::clone(&this);
1719            Rc::new(move |h: f32| this.set_viewport(this.vp_w.get(), h))
1720        };
1721        let c_set_cw = {
1722            let this = Rc::clone(&this);
1723            Rc::new(move |w: f32| this.set_content(w, this.c_h.get()))
1724        };
1725        let c_set_ch = {
1726            let this = Rc::clone(&this);
1727            Rc::new(move |h: f32| this.set_content(this.c_w.get(), h))
1728        };
1729        let c_get_xy = {
1730            let this = Rc::clone(&this);
1731            Rc::new(move || {
1732                let (ox, oy) = this.get();
1733                let (osx, osy) = this.overscroll_offset();
1734                (ox + osx, oy + osy)
1735            })
1736        };
1737        let c_set_xy = {
1738            let this = Rc::clone(&this);
1739            Rc::new(move |x: f32, y: f32| this.set_offset_xy(x, y))
1740        };
1741        let c_tick = {
1742            let this = Rc::clone(&this);
1743            Rc::new(move || {
1744                this.tick();
1745            })
1746        };
1747        let c_set_nested = {
1748            let state = Rc::clone(&pc);
1749            Rc::new(move |conn| {
1750                *state.borrow_mut() = Some(conn);
1751            })
1752        };
1753        ScrollBinding::Both(ScrollBothBinding {
1754            on_scroll: Some(c_on_scroll),
1755            on_scroll_with_source: Some(c_on_scroll_with_source),
1756            set_viewport_width: Some(c_set_vw),
1757            set_viewport_height: Some(c_set_vh),
1758            set_content_width: Some(c_set_cw),
1759            set_content_height: Some(c_set_ch),
1760            get_offset_xy: Some(c_get_xy),
1761            set_offset_xy: Some(c_set_xy),
1762            reversed_x: this.reversed_x.get(),
1763            reversed_y: this.reversed_y.get(),
1764            show_scrollbar: this.show_scrollbar(),
1765            tick: Some(c_tick),
1766            set_nested_scroll_parent: Some(c_set_nested),
1767        })
1768    }
1769}
1770
1771pub fn run_pre_scroll(conn: &RefCell<Option<NestedScrollConnection>>, d: Vec2) -> Vec2 {
1772    if let Some(ref parent) = *conn.borrow() {
1773        let consumed = parent.dispatch_pre_scroll(d, NestedScrollSource::UserInput);
1774        d - consumed
1775    } else {
1776        d
1777    }
1778}
1779
1780/// Dispatch leftover scroll to the parent chain and return what remains after
1781/// the chain's consumption. `consumed` is the amount already consumed before
1782/// reaching this helper (by pre-scroll and by this scroller).
1783pub fn run_post_scroll(
1784    connection: &RefCell<Option<NestedScrollConnection>>,
1785    consumed: Vec2,
1786    available: Vec2,
1787    source: NestedScrollSource,
1788) -> Vec2 {
1789    if let Some(ref parent) = *connection.borrow() {
1790        let added = parent.dispatch_post_scroll(consumed, available, source);
1791        available - added
1792    } else {
1793        available
1794    }
1795}
1796
1797/// Compatibility wrapper for callers that have no consumption to report.
1798pub fn run_post_scroll_zero(
1799    connection: &RefCell<Option<NestedScrollConnection>>,
1800    available: Vec2,
1801) -> Vec2 {
1802    run_post_scroll(
1803        connection,
1804        Vec2::ZERO,
1805        available,
1806        NestedScrollSource::UserInput,
1807    )
1808}
1809
1810#[cfg(test)]
1811mod fling_tests {
1812    use super::*;
1813
1814    const FRAME: web_time::Duration = web_time::Duration::from_millis(16);
1815
1816    fn seeded() -> ScrollState {
1817        let st = ScrollState::new();
1818        st.set_viewport_height(100.0);
1819        st.set_content_height(4000.0);
1820        st
1821    }
1822
1823    /// Advance one 60Hz frame. The physics derives `dt` from the wall clock, so
1824    /// a test that never advances real time cannot observe fling integration at
1825    /// all and would pass even with the double-count restored.
1826    fn frame() {
1827        std::thread::sleep(FRAME);
1828    }
1829
1830    /// A sustained drag must move the surface by the input and nothing more.
1831    /// This is the regression: the per-frame integrator used to run on the same
1832    /// frames that applied the drag delta, so travel was roughly doubled.
1833    #[test]
1834    fn drag_does_not_double_count() {
1835        let st = seeded();
1836        let (frames, step) = (10, 30.0);
1837        for _ in 0..frames {
1838            st.scroll_immediate(step);
1839            frame();
1840            st.tick();
1841        }
1842        let expected = step * frames as f32;
1843        assert!(
1844            (st.get() - expected).abs() < 1.0,
1845            "drag of {expected} over {frames} frames moved {}",
1846            st.get()
1847        );
1848    }
1849
1850    /// Once input stops arriving the stored velocity must carry the surface on
1851    /// as a fling, so a flick still coasts.
1852    #[test]
1853    fn fling_continues_after_input_stops() {
1854        let st = seeded();
1855        st.scroll_immediate(200.0);
1856        frame();
1857        st.tick();
1858        let at_release = st.get();
1859        let mut coasted = 0.0;
1860        for _ in 0..10 {
1861            frame();
1862            if st.tick() {
1863                coasted += 1.0;
1864            }
1865        }
1866        assert!(coasted > 0.0, "fling stopped immediately after release");
1867        assert!(st.get() > at_release, "fling must travel further");
1868    }
1869
1870    /// The first frame after release must continue at roughly the speed the
1871    /// finger was moving. A lurch here reads as a jitter kick: the integrator
1872    /// used to bail out before sampling the clock, so `last_t` went stale for
1873    /// the whole drag and all of it landed in one frame.
1874    #[test]
1875    fn release_is_continuous_with_the_drag() {
1876        for step in [8.0f32, 30.0, 70.0] {
1877            let st = seeded();
1878            for _ in 0..10 {
1879                st.scroll_immediate(step);
1880                frame();
1881                st.tick();
1882            }
1883            let released = st.get();
1884            frame();
1885            st.tick();
1886            let first = st.get() - released;
1887            assert!(
1888                (first - step).abs() < step * 0.25,
1889                "drag at {step}px/frame released into a {first}px step"
1890            );
1891        }
1892    }
1893
1894    /// A drag landing mid-fling follows the finger instead of being yanked by
1895    /// the stale velocity.
1896    #[test]
1897    fn drag_cancels_stale_fling_direction() {
1898        let st = seeded();
1899        for _ in 0..6 {
1900            st.scroll_immediate(200.0);
1901            frame();
1902            st.tick();
1903        }
1904        let before = st.get();
1905        for _ in 0..6 {
1906            st.scroll_immediate(-20.0);
1907            frame();
1908            st.tick();
1909        }
1910        assert!(
1911            st.get() < before,
1912            "reverse drag must win over the old fling ({} -> {})",
1913            before,
1914            st.get()
1915        );
1916    }
1917
1918    /// A parent handed leftover by a child must still be able to fling.
1919    #[test]
1920    fn parent_flings_after_taking_child_leftover() {
1921        let st = seeded();
1922        let conn = st.connection();
1923        let consumed = conn.dispatch_post_scroll(
1924            Vec2::ZERO,
1925            Vec2 { x: 0.0, y: 200.0 },
1926            NestedScrollSource::UserInput,
1927        );
1928        // `on_post_scroll` reports what THIS container consumed.
1929        assert!(
1930            (consumed.y - 200.0).abs() < 0.001,
1931            "consumed {}",
1932            consumed.y
1933        );
1934        assert!(st.get() > 0.0, "parent scrolled");
1935        assert!(st.physics.borrow().is_animating(), "parent has velocity");
1936        frame();
1937        st.tick();
1938        let before_coast = st.get();
1939        frame();
1940        st.tick();
1941        assert!(
1942            st.get() > before_coast,
1943            "parent must coast: nested velocity reached the driven physics"
1944        );
1945    }
1946
1947    /// A brief pause before lifting (a dropped frame on a busy screen) must
1948    /// still coast. Compose keeps samples for a 100ms horizon; the old 40ms
1949    /// cutoff killed the fling here, which read as random loss of inertia.
1950    #[test]
1951    fn fling_survives_short_pause_before_lift() {
1952        struct TouchGuard;
1953        impl Drop for TouchGuard {
1954            fn drop(&mut self) {
1955                set_touch_gesture_active(false);
1956            }
1957        }
1958        let _guard = TouchGuard;
1959        set_touch_gesture_active(true);
1960
1961        let st = seeded();
1962        for _ in 0..8 {
1963            st.scroll_immediate(30.0);
1964            frame();
1965            st.tick();
1966        }
1967        let at_release = st.get();
1968
1969        std::thread::sleep(web_time::Duration::from_millis(60));
1970        set_touch_gesture_active(false);
1971        st.tick();
1972
1973        let mut coasted = false;
1974        for _ in 0..8 {
1975            frame();
1976            if st.tick() {
1977                coasted = true;
1978            }
1979        }
1980        assert!(coasted, "a 60ms pause before lift must still coast");
1981        assert!(
1982            st.get() > at_release,
1983            "fling must travel further after release"
1984        );
1985    }
1986}