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