Skip to main content

nsh_core/
scroll.rs

1//! Scroll views without a toolkit: offsets, wheel / touchpad / touch /
2//! keyboard scrolling with momentum, snapping, paging, rubber banding,
3//! sticky cells, the indicator as a scroll bar, the refresh spinner's
4//! state, zooming, the core's scroll requests and scroll events.
5//!
6//! A scroll view moves along its main axis; a zoomable one
7//! (`maximumZoomScale` above `minimumZoomScale`) along both, zoomed by
8//! touchpad and touch pinches around the pointer ([`pinch`]) and by
9//! `zoomTo` ([`command`]), on the backends that draw zoomed content
10//! ([`ScrollState::can_zoom`]; elsewhere `zoomTo` and the zoom props are
11//! ignored). Its offset lives in [`ScrollState`] (`x` / `y`, 0 showing the
12//! start of the content inset; UIKit's zoomed `contentOffset`), which the
13//! backends keep in their views. Every change goes through one
14//! place, which shows the indicator, tells the backend
15//! ([`ScrollHost::moved`]: it places the children, pins the sticky cells
16//! and feeds the native scroll value in the same frame) and queues a
17//! report to the engine. Reports are coalesced to one per frame by the
18//! view's frame callback ([`ScrollHost::start_ticking`], which calls
19//! [`frame`]), which also runs glides, animated scrolls, the indicator's
20//! fade and the refresh spinner, and stops when none of them is left.
21//!
22//! Offsets are reported as UIKit's `contentOffset` (minus the leading
23//! content inset, clamped to the content), so lists see the same numbers
24//! as on iOS. Glides decelerate as UIKit does (velocity kept per
25//! millisecond: `behavior.deceleration`, 0.998 by default, 0.99 when
26//! snapping); snapping and paging use [`ScrollBehavior::snap_target`].
27//! Touch drags rubber-band past the edges when `bounces`; wheels and
28//! touchpads stop at the edges, as desktop scrolling does.
29//!
30//! Mirrored (right to left) horizontal lists keep their offsets left to
31//! right: the backends place each child at the mirror image of its frame,
32//! and drags, wheels and the indicator are mirrored here.
33//!
34//! The backends keep what their toolkits do: drawing the indicator and
35//! the spinner, the sticky cells' views, picking which view a key or a
36//! focused field scrolls, and the frame clock.
37
38#[doc(hidden)]
39pub mod wheel_glide;
40
41use std::f32::consts::PI;
42
43use crate::{
44    Bounds, Command, EventKind, EventPayload, NodeId, Point, Points, ScrollBehavior, Size,
45    StickyCell,
46    geometry::{Axis, Percentage, Radians, point},
47};
48
49/// Below this release speed (points per ms) a drag does not glide.
50const MIN_GLIDE: f32 = 0.05;
51/// A glide stops below this speed (points per ms).
52const STOP: f32 = 0.01;
53/// A wheel without a gesture (a mouse) has settled after this many ms.
54const WHEEL_IDLE: f64 = 150.0;
55/// The indicator stays this long (ms) after the last scroll...
56const INDICATOR_HOLD: f64 = 700.0;
57/// ...then fades out in this long.
58const INDICATOR_FADE: f64 = 300.0;
59/// Duration of animated scrolls and bounces back (ms).
60const ANIMATION: f64 = 300.0;
61/// The release speed (points per ms) a settled mouse wheel snaps with:
62/// fast enough to move on to the next snap point.
63const WHEEL_SNAP: f32 = 0.6;
64/// Space between the indicator and the ends of the viewport.
65const INDICATOR_MARGIN: f32 = 2.0;
66/// The indicator's thickness.
67pub const INDICATOR_THICK: Points = Points(3.0);
68/// How close to its edge (points) a mouse press grabs the indicator,
69/// which is much thinner than a pointer is precise...
70const THUMB_GRAB: f32 = 12.0;
71/// ...and how far past its ends.
72const THUMB_SLOP: f32 = 4.0;
73
74/// A scroll offset, a move or a velocity (points, or points per ms) along
75/// both axes. Scroll views move along their main axis, the other staying
76/// 0; zoomable ones along both.
77#[derive(Debug, Default, Clone, Copy, PartialEq)]
78struct Offset {
79    x: f32,
80    y: f32,
81}
82
83impl Offset {
84    const fn new(x: f32, y: f32) -> Self {
85        Self { x, y }
86    }
87
88    fn along(self, horizontal: bool) -> f32 {
89        if horizontal { self.x } else { self.y }
90    }
91
92    /// This offset with `v` along one axis.
93    fn with(self, horizontal: bool, v: f32) -> Self {
94        if horizontal {
95            Self::new(v, self.y)
96        } else {
97            Self::new(self.x, v)
98        }
99    }
100
101    fn lerp(self, to: Self, k: f32) -> Self {
102        Self::new(self.x + (to.x - self.x) * k, self.y + (to.y - self.y) * k)
103    }
104
105    /// The larger distance along an axis to `to`.
106    fn distance(self, to: Self) -> f32 {
107        (to.x - self.x).abs().max((to.y - self.y).abs())
108    }
109
110    /// `self` within `(min, max)`.
111    fn clamp(self, (min, max): (Self, Self)) -> Self {
112        Self::new(
113            self.x.clamp(min.x, max.x.max(min.x)),
114            self.y.clamp(min.y, max.y.max(min.y)),
115        )
116    }
117}
118
119impl std::ops::Add for Offset {
120    type Output = Self;
121
122    fn add(self, o: Self) -> Self {
123        Self::new(self.x + o.x, self.y + o.y)
124    }
125}
126
127impl From<Offset> for Point<Points> {
128    fn from(o: Offset) -> Self {
129        point(Points(o.x), Points(o.y))
130    }
131}
132
133impl From<Point<Points>> for Offset {
134    fn from(p: Point<Points>) -> Self {
135        Offset::new(p.x.0, p.y.0)
136    }
137}
138
139/// What a scroll view is doing.
140#[derive(Debug, Default, Clone, Copy, PartialEq)]
141enum Phase {
142    /// At rest.
143    #[default]
144    Idle,
145    /// A touch-style drag: `start` is the offset it began at, `moved` how
146    /// far the pointer went since (content follows it).
147    Drag { start: Offset, moved: Offset },
148    /// The mouse drags the indicator as a scroll bar's thumb, from offset
149    /// `start`.
150    Thumb { start: f32 },
151    /// Wheel or touchpad input: the last at `last` (ms), `total` points
152    /// so far; `gesture` for touchpads (begin / end), not mouse wheels.
153    /// A `smoothWheel` view's notches glide (`glide`, [`wheel_glide`]) to
154    /// `raw`, where they point; otherwise `raw` is where the view is.
155    Wheel {
156        last: f64,
157        total: f32,
158        gesture: bool,
159        raw: Offset,
160        glide: wheel_glide::Glide,
161    },
162    /// Momentum after a fling: `velocity` points per ms at `last` (ms).
163    Glide { velocity: Offset, last: f64 },
164    /// An eased move from `from` to `to`, started at `start` (ms):
165    /// `momentum` for snapping after a fling (momentum events), `end` to
166    /// send `onScrollEnd` when it arrives.
167    Animate {
168        from: Offset,
169        to: Offset,
170        start: f64,
171        duration: f64,
172        momentum: bool,
173        end: bool,
174    },
175    /// An eased zoom from `from` to `to`, started at `start` (ms), the
176    /// content point (unzoomed) at viewport point `at` moving from `from_c`
177    /// to `to_c` meanwhile: `zoomTo`, or a pinch springing back within the
178    /// limits.
179    Zoom {
180        from: f32,
181        to: f32,
182        from_c: Offset,
183        to_c: Offset,
184        at: Offset,
185        start: f64,
186        duration: f64,
187    },
188}
189
190/// The running state of a scroll view: input phase, the indicator and
191/// the refresh spinner.
192#[derive(Debug, Default, Clone)]
193#[non_exhaustive]
194pub struct Live {
195    phase: Phase,
196    /// The view's frame callback runs.
197    ticking: bool,
198    /// The offset changed since it was last reported.
199    report: bool,
200    /// When the indicator was last shown (ms).
201    shown: f64,
202    /// [`ScrollHost::wake_after`] was asked and has not called back.
203    hold_timer: bool,
204    /// The indicator's opacity.
205    pub alpha: f32,
206    /// The refresh spinner shows.
207    pub refreshing: bool,
208    /// `refreshing` turned off while pulled past the top: the spinner keeps
209    /// turning until the offset returns to 0 instead of falling back to pull
210    /// progress.
211    dismissing: bool,
212    /// When the current refresh spin started (ms), so large monotonic
213    /// timestamps do not lose precision in `f32`.
214    spin_start: Option<f64>,
215    /// The spinner's angle.
216    pub spin: Radians,
217    /// [`ScrollHost::dark`] when the indicator was last shown, for
218    /// backends that pick its colors then.
219    pub dark: bool,
220    /// The zoom a pinch began at ([`pinch`]).
221    pinch_from: f32,
222    /// The zoom last reported to the engine (0: none yet).
223    reported_zoom: f32,
224    /// The zoom changed since the view was last moved.
225    rezoomed: bool,
226}
227
228/// Scroll position and extent of a scroll view.
229#[derive(Debug, Clone)]
230#[non_exhaustive]
231pub struct ScrollState {
232    /// Current offset (points; the viewport's top left in the zoomed
233    /// content).
234    pub x: Points,
235    /// Vertical offset.
236    pub y: Points,
237    /// Size of the scrollable content (unzoomed).
238    pub content: Size<Points>,
239    /// How far the content is zoomed (1 unless it zooms).
240    pub zoom: f32,
241    /// The backend draws, hit tests and pinches zoomed content: only then
242    /// does a view zoom ([`ScrollState::zooms`]).
243    pub can_zoom: bool,
244    /// Scrolls horizontally.
245    pub horizontal: bool,
246    /// Shows the scroll indicator.
247    pub indicator: bool,
248    /// How it scrolls (paging, snapping, insets...).
249    pub behavior: ScrollBehavior,
250    /// Scrolls the core asked for (`ScrollBy`, `scrollTo`) that were
251    /// applied: reported with each offset.
252    pub applied: u32,
253    /// The sticky cells: (cell, start, end).
254    pub sticky: Vec<StickyCell>,
255    /// A horizontal list laid out right to left: children are placed
256    /// mirrored (offsets stay left to right).
257    pub mirrored: bool,
258    /// Gestures, glides and the indicator.
259    pub live: Live,
260}
261
262impl Default for ScrollState {
263    fn default() -> Self {
264        Self {
265            x: Points::ZERO,
266            y: Points::ZERO,
267            content: Size::default(),
268            zoom: 1.0,
269            can_zoom: false,
270            horizontal: false,
271            indicator: false,
272            behavior: ScrollBehavior::default(),
273            applied: 0,
274            sticky: Vec::new(),
275            mirrored: false,
276            live: Live::default(),
277        }
278    }
279}
280
281/// A scroll view in a backend's view tree: what the logic here reads and
282/// does through it. Backends implement it over a view and its surface.
283pub trait ScrollHost {
284    /// Runs `f` with the view's scroll state and its size, or `None` when
285    /// it is no scroll view.
286    fn scroll<R>(&self, f: impl FnOnce(&ScrollState, Size<Points>) -> R) -> Option<R>;
287    /// Runs `f` with the view's scroll state, mutable, and its size.
288    fn scroll_mut<R>(&self, f: impl FnOnce(&mut ScrollState, Size<Points>) -> R) -> Option<R>;
289    /// The clock phases keep, in ms.
290    fn now(&self) -> f64;
291    /// Whether JS listens to `kind` on the view.
292    fn listens(&self, kind: EventKind) -> bool;
293    /// Sends `kind` on the view to the engine.
294    fn event(&self, kind: EventKind, payload: EventPayload);
295    /// Reports the view's offset (UIKit's `contentOffset`) to the engine
296    /// with the count of the core's scrolls applied.
297    fn report(&self, offset: Point<Points>, applied: u32);
298    /// Reports the view's zoom to the engine, before the offset it
299    /// changed ([`ScrollState::can_zoom`]'s backends).
300    fn report_zoom(&self, scale: f32) {
301        let _ = scale;
302    }
303    /// Tells the engine that a scroll key moved the view by `key_move`
304    /// (`EngineControl::key_scrolled`), once [`key_scroll`] started its
305    /// animation: a list follows its real end from End on.
306    fn key_scrolled(&self, key_move: KeyMove) {
307        let _ = key_move;
308    }
309    /// The offset or the zoom changed (`offset` is the one reported): the
310    /// children move, the sticky cells pin to it, native scroll values
311    /// follow.
312    fn moved(&self, offset: Point<Points>);
313    /// A vertical view is pulled `distance` past its top (0 once it is
314    /// back): its native pull value follows.
315    fn pulled(&self, distance: Points);
316    /// The children's placement changed (mirroring, insets).
317    fn relayout(&self);
318    /// The view draws again (the indicator, the spinner, the content).
319    fn redraw(&self);
320    /// Whether the view is in a window, where frames come.
321    fn attached(&self) -> bool;
322    /// Runs [`frame`] on every frame from now until it returns false.
323    fn start_ticking(&self);
324    /// Schedules [`hold_ended`] on the view's thread after `ms` milliseconds.
325    /// Returns `false` if the platform does not override this method or could
326    /// not arm a timer; the core then stays on the frame callback path to
327    /// finish fading the indicator.
328    #[doc(hidden)]
329    fn wake_after(&self, ms: u64) -> bool {
330        let _ = ms;
331        false
332    }
333    /// The scroll view came to rest (its drag and momentum ended, as it
334    /// sends `onScrollEnd`): the snapping animated values that follow it
335    /// settle ([`crate::animation::Animator::scroll_ended`]).
336    fn settled(&self) {}
337    /// Whether the surface is dark, kept in [`Live::dark`] when the
338    /// indicator shows.
339    fn dark(&self) -> bool {
340        false
341    }
342}
343
344// Pure logic. Lengths are points; velocities are points per ms, times ms.
345
346/// The rubber band of iOS: how far content dragged `over` points past an
347/// edge of a `dim`-point viewport moves.
348fn rubber(over: f32, dim: f32) -> f32 {
349    let dim = dim.max(1.0);
350    (1.0 - 1.0 / (over * 0.55 / dim + 1.0)) * dim
351}
352
353/// Position on a drag that went to `raw`, with `[min, max]` the limits, in
354/// a `dim`-point viewport: past them it rubber-bands when `bounces`.
355pub fn dragged(raw: Points, min: Points, max: Points, dim: Points, bounces: bool) -> Points {
356    Points(drag_position(raw.0, min.0, max.0, dim.0, bounces))
357}
358
359fn drag_position(raw: f32, min: f32, max: f32, dim: f32, bounces: bool) -> f32 {
360    if raw < min {
361        if bounces {
362            min - rubber(min - raw, dim)
363        } else {
364            min
365        }
366    } else if raw > max {
367        if bounces {
368            max + rubber(raw - max, dim)
369        } else {
370            max
371        }
372    } else {
373        raw
374    }
375}
376
377/// The deceleration rate: velocity kept per ms.
378pub fn rate(behavior: &ScrollBehavior) -> f32 {
379    if behavior.deceleration > 0.0 && behavior.deceleration < 1.0 {
380        behavior.deceleration
381    } else if behavior.snaps() || behavior.paging {
382        0.99
383    } else {
384        0.998
385    }
386}
387
388/// One step of a glide: `(distance, new velocity)` after `dt` ms at
389/// velocity `v` (points per ms), decaying exponentially by `rate` per ms.
390fn glide_step(v: f32, rate: f32, dt: f32) -> (f32, f32) {
391    let k = rate.powf(dt);
392    (v * (k - 1.0) / rate.ln(), v * k)
393}
394
395/// Where a glide at `velocity` (points per ms) from `offset` comes to
396/// rest, decelerating by `rate` ([`rate`]).
397pub fn projected(offset: Points, velocity: f32, rate: f32) -> Points {
398    Points(offset.0 - velocity / rate.ln())
399}
400
401/// How far a sticky cell from `start` to `end` (where the next one pushes
402/// it out, or its containing block's start for an end inset) moves at
403/// `offset`.
404pub fn sticky_shift(offset: Points, start: Points, end: Points) -> Points {
405    let travel = end.0 - start.0;
406    Points((offset.0 - start.0).clamp(travel.min(0.0), travel.max(0.0)))
407}
408
409/// Cubic ease out of `t` (0 to 1).
410pub fn ease_out(t: f64) -> f32 {
411    let t = t.clamp(0.0, 1.0);
412    (1.0 - (1.0 - t).powi(3)) as f32
413}
414
415/// How long (ms) an eased move of `distance` that starts at `velocity`
416/// (points per ms, in its direction) takes: ease out starts at 3 ×
417/// distance / duration, which then matches the release.
418pub fn snap_duration(distance: Points, velocity: f32) -> f64 {
419    let (distance, v) = (distance.0, velocity);
420    if distance.abs() < 0.5 {
421        return 0.0;
422    }
423    if v * distance > 0.0 {
424        (3.0 * distance.abs() / v.abs()).clamp(180.0, 600.0) as f64
425    } else {
426        ANIMATION
427    }
428}
429
430/// How many ms the indicator still holds `since` ms after it was shown;
431/// `None` once it fades.
432#[doc(hidden)]
433pub fn indicator_hold_left(since: f64) -> Option<u64> {
434    (since < INDICATOR_HOLD).then(|| (INDICATOR_HOLD - since).ceil() as u64)
435}
436
437/// The indicator's opacity `since` ms after it was shown.
438pub fn indicator_alpha(since: f64) -> f32 {
439    if since < INDICATOR_HOLD {
440        1.0
441    } else {
442        (1.0 - (since - INDICATOR_HOLD) / INDICATOR_FADE).max(0.0) as f32
443    }
444}
445
446/// The indicator along the main axis: `(start, length)` in a viewport of
447/// `viewport` points showing `total` points at `offset`, or `None` when
448/// everything fits.
449pub fn indicator_span(viewport: Points, total: Points, offset: Points) -> Option<(Points, Points)> {
450    indicator_span_within(viewport, total, offset, Points::ZERO, Points::ZERO)
451}
452
453/// [`indicator_span`] along a track that keeps `before` points from the
454/// viewport's start and `after` from its end (the view's
455/// [`crate::ScrollBehavior::scrollbar_inset`] along its axis), so that the
456/// indicator stays clear of bars floating over the ends of the view.
457/// `None` also when the insets leave no room for it.
458pub fn indicator_span_within(
459    viewport: Points,
460    total: Points,
461    offset: Points,
462    before: Points,
463    after: Points,
464) -> Option<(Points, Points)> {
465    span(viewport.0, total.0, offset.0, before.0, after.0)
466        .map(|(start, len)| (Points(start), Points(len)))
467}
468
469fn span(viewport: f32, total: f32, offset: f32, before: f32, after: f32) -> Option<(f32, f32)> {
470    /// Short enough to see where it is in long lists, long enough to see.
471    const MIN_LENGTH: f32 = 32.0;
472    let (before, after) = (before.max(0.0), after.max(0.0));
473    let room = viewport - before - after;
474    if total <= viewport + 0.5 || room <= 4.0 * INDICATOR_MARGIN {
475        return None;
476    }
477    let track = room - 2.0 * INDICATOR_MARGIN;
478    let max = total - viewport;
479    // Overscrolling shrinks it, as on iOS.
480    let over = if offset < 0.0 {
481        -offset
482    } else {
483        (offset - max).max(0.0)
484    };
485    let len = (track * viewport / total - over).max(MIN_LENGTH).min(track);
486    let t = (offset / max).clamp(0.0, 1.0);
487    Some((before + INDICATOR_MARGIN + (track - len) * t, len))
488}
489
490/// How far the offset moves when the thumb moves by `d`: the thumb's
491/// `travel` (`track - length`) spans the whole scroll `range`.
492pub fn thumb_scroll(d: Points, range: Points, travel: Points) -> Points {
493    if travel.0 > 0.0 {
494        Points(d.0 * range.0 / travel.0)
495    } else {
496        Points(0.0)
497    }
498}
499
500/// A gesture or animation in flight when the core moves the content by
501/// `d` (`ScrollBy`) moves along, so that it continues from the content it
502/// was on.
503fn shifted(phase: Phase, d: Offset, horizontal: bool) -> Phase {
504    match phase {
505        Phase::Drag { start, moved } => Phase::Drag {
506            start: start + d,
507            moved,
508        },
509        Phase::Thumb { start } => Phase::Thumb {
510            start: start + d.along(horizontal),
511        },
512        Phase::Animate {
513            from,
514            to,
515            start,
516            duration,
517            momentum,
518            end,
519        } => Phase::Animate {
520            from: from + d,
521            to: to + d,
522            start,
523            duration,
524            momentum,
525            end,
526        },
527        Phase::Wheel {
528            last,
529            total,
530            gesture,
531            raw,
532            glide,
533        } => Phase::Wheel {
534            last,
535            total,
536            gesture,
537            raw: raw + d,
538            glide: glide.shifted(d.into()),
539        },
540        other => other,
541    }
542}
543
544/// Angle of the refresh spinner `elapsed` ms after it started (one turn a
545/// second), reduced in `f64` before casting to `f32` so large monotonic
546/// clocks stay precise.
547fn spin_angle(elapsed: f64) -> Radians {
548    let frac = elapsed.max(0.0).rem_euclid(1000.0) / 1000.0;
549    Radians(frac as f32 * 2.0 * PI)
550}
551
552/// The spokes of the refresh spinner, as an activity indicator of eight
553/// spokes draws them: `progress` of them show while pulling, and they turn
554/// in whole spokes by `spin`. Each is its rotation and its opacity; a
555/// spoke is drawn pointing up from the spinner's center.
556pub fn spokes(progress: Percentage, spin: Radians) -> impl Iterator<Item = (Radians, f32)> {
557    const SPOKES: usize = 8;
558    let (progress, spin) = (progress.0, spin.0);
559    let shown = ((progress * SPOKES as f32).ceil() as usize).min(SPOKES);
560    let step = 2.0 * PI / SPOKES as f32;
561    let lead = (spin / step) as usize % SPOKES;
562    (0..shown).map(move |i| {
563        let fade = if progress < 1.0 {
564            0.8
565        } else {
566            1.0 - ((lead + SPOKES - i) % SPOKES) as f32 / SPOKES as f32 * 0.85
567        };
568        (Radians(i as f32 * step), fade)
569    })
570}
571
572// The reading order.
573
574/// Orders a view's children as they are on screen, the order Tab and
575/// screen readers go through a scroll view's content (and a list's cells,
576/// [`crate::ViewProps::screen_order`]) in: along `axis`, then across it. A
577/// list recycles its cells, so in the view tree they stay in the order
578/// they were made, not their rows'. `origin` is a child's frame origin;
579/// the sort is stable.
580pub fn reading_order<T>(axis: Axis, children: &mut [T], origin: impl Fn(&T) -> Point<Points>) {
581    if children.len() < 2 {
582        return;
583    }
584    let key = |child: &T| {
585        let at = origin(child);
586        match axis {
587            Axis::Horizontal => (at.x.0, at.y.0),
588            Axis::Vertical => (at.y.0, at.x.0),
589        }
590    };
591    children.sort_by(|a, b| {
592        let (a, b) = (key(a), key(b));
593        a.0.total_cmp(&b.0).then(a.1.total_cmp(&b.1))
594    });
595}
596
597// The state.
598
599impl ScrollState {
600    /// The largest offsets in a view of `size`.
601    pub fn max(&self, size: Size<Points>) -> Point<Points> {
602        let (x, y) = self.max_f(size);
603        point(Points(x), Points(y))
604    }
605
606    fn max_f(&self, size: Size<Points>) -> (f32, f32) {
607        let inset = self.behavior.content_inset;
608        let z = self.zoom;
609        (
610            (self.content.width.0 * z + inset.left.0 + inset.right.0 - size.width.0).max(0.0),
611            (self.content.height.0 * z + inset.top.0 + inset.bottom.0 - size.height.0).max(0.0),
612        )
613    }
614
615    /// The offset children are drawn at: the scroll offset less the
616    /// content inset (a zoomed view's children are scaled by
617    /// [`ScrollState::zoom`] first, and moved by [`ScrollState::centered`]).
618    pub fn origin(&self) -> Point<Points> {
619        let inset = self.behavior.content_inset;
620        point(self.x - inset.left, self.y - inset.top)
621    }
622
623    /// Whether the content zooms: its props ask for it
624    /// ([`ScrollBehavior::zooms`]) and the backend draws it
625    /// ([`ScrollState::can_zoom`]).
626    pub fn zooms(&self) -> bool {
627        self.can_zoom && self.behavior.zooms()
628    }
629
630    /// The room before zoomed content smaller than the viewport of a view
631    /// of `size`, which a zoomable view with `centerContent` centers it in
632    /// (viewport points; 0 for any other view).
633    pub fn centered(&self, size: Size<Points>) -> Point<Points> {
634        if !self.zooms() || !self.behavior.center_content {
635            return Point::default();
636        }
637        let inset = self.behavior.content_inset;
638        let free = |viewport: f32, content: f32| ((viewport - content * self.zoom) / 2.0).max(0.0);
639        point(
640            Points(free(
641                size.width.0 - inset.left.0 - inset.right.0,
642                self.content.width.0,
643            )),
644            Points(free(
645                size.height.0 - inset.top.0 - inset.bottom.0,
646                self.content.height.0,
647            )),
648        )
649    }
650
651    /// Where a point of the content (unzoomed, as the children's frames
652    /// are) shows in the viewport of a view of `size`.
653    pub fn to_viewport(&self, size: Size<Points>, content: Point<Points>) -> Point<Points> {
654        let (o, room) = (self.origin(), self.centered(size));
655        point(
656            Points(content.x.0 * self.zoom - o.x.0 + room.x.0),
657            Points(content.y.0 * self.zoom - o.y.0 + room.y.0),
658        )
659    }
660
661    /// The point of the content (unzoomed) at point `at` of the viewport
662    /// of a view of `size`.
663    pub fn to_content(&self, size: Size<Points>, at: Point<Points>) -> Point<Points> {
664        let (o, room) = (self.origin(), self.centered(size));
665        point(
666            Points((at.x.0 + o.x.0 - room.x.0) / self.zoom),
667            Points((at.y.0 + o.y.0 - room.y.0) / self.zoom),
668        )
669    }
670
671    /// The offset along the main axis.
672    fn offset(&self) -> f32 {
673        if self.horizontal { self.x.0 } else { self.y.0 }
674    }
675
676    /// The offset along both axes.
677    fn pos(&self) -> Offset {
678        Offset::new(self.x.0, self.y.0)
679    }
680
681    /// The rest limits, `(min, max)`, along both axes: along the main axis
682    /// ([`ScrollState::limits`]), the other staying at 0, except for a
683    /// zoomable view.
684    fn range(&self, size: Size<Points>) -> (Offset, Offset) {
685        let (min, max) = self.limits(size);
686        if self.zooms() {
687            let (mx, my) = self.max_f(size);
688            // The refresh room is above the content only.
689            let top = if self.horizontal { 0.0 } else { min };
690            (Offset::new(0.0, top), Offset::new(mx, my))
691        } else {
692            let zero = Offset::default();
693            (
694                zero.with(self.horizontal, min),
695                zero.with(self.horizontal, max),
696            )
697        }
698    }
699
700    /// The content point (unzoomed) at point `at` of the viewport.
701    fn content_at(&self, size: Size<Points>, at: Offset) -> Offset {
702        let c = self.to_content(size, point(Points(at.x), Points(at.y)));
703        Offset::new(c.x.0, c.y.0)
704    }
705
706    /// The offset that shows content point `c` (unzoomed) at point `at` of
707    /// the viewport at the current zoom, within the limits.
708    fn showing(&self, size: Size<Points>, c: Offset, at: Offset) -> Offset {
709        let inset = self.behavior.content_inset;
710        let room = self.centered(size);
711        Offset::new(
712            c.x * self.zoom + room.x.0 - at.x + inset.left.0,
713            c.y * self.zoom + room.y.0 - at.y + inset.top.0,
714        )
715        .clamp(self.range(size))
716    }
717
718    /// Where the offset is headed: the end of a running animated scroll,
719    /// else the offset (a key repeat or a reveal continues from there).
720    fn goal(&self) -> f32 {
721        match self.live.phase {
722            Phase::Animate { to, .. } => to.along(self.horizontal),
723            _ => self.offset(),
724        }
725    }
726
727    /// The viewport's length along the main axis, in a view of `size`.
728    fn viewport(&self, size: Size<Points>) -> f32 {
729        if self.horizontal {
730            size.width.0
731        } else {
732            size.height.0
733        }
734    }
735
736    /// The leading content inset along the main axis.
737    fn lead(&self) -> f32 {
738        if self.horizontal {
739            self.behavior.content_inset.left.0
740        } else {
741            self.behavior.content_inset.top.0
742        }
743    }
744
745    /// The rest limits along the main axis (the top is lower while the
746    /// refresh spinner shows).
747    fn limits(&self, size: Size<Points>) -> (f32, f32) {
748        let max = self.max_f(size);
749        let min = if !self.horizontal && self.live.refreshing {
750            -self.behavior.refresh_inset().0
751        } else {
752            0.0
753        };
754        (min, if self.horizontal { max.0 } else { max.1 })
755    }
756
757    /// The offset reported to the engine and in events: UIKit's
758    /// `contentOffset`, within the content.
759    pub fn reported(&self, size: Size<Points>) -> Point<Points> {
760        let (mx, my) = self.max_f(size);
761        let inset = self.behavior.content_inset;
762        point(
763            Points(self.x.0.clamp(0.0, mx) - inset.left.0),
764            Points(self.y.0.clamp(0.0, my) - inset.top.0),
765        )
766    }
767
768    /// Whether the user can scroll the view of `size` by `delta` (wheel
769    /// deltas: positive moves the content up / left): it is enabled,
770    /// scrolls along that axis and is not at that edge yet. Input uses it
771    /// to pick which of nested scroll views a wheel moves.
772    pub fn can_scroll(&self, size: Size<Points>, delta: Point<Points>) -> bool {
773        let (dx, dy) = (delta.x.0, delta.y.0);
774        if !self.behavior.enabled {
775            return false;
776        }
777        if self.zooms() {
778            let ((min, max), p) = (self.range(size), self.pos());
779            let can = |d: f32, p: f32, min: f32, max: f32| {
780                (d > 0.0 && p < max - 0.5) || (d < 0.0 && p > min + 0.5)
781            };
782            return can(dx, p.x, min.x, max.x) || can(dy, p.y, min.y, max.y);
783        }
784        let (min, max) = self.limits(size);
785        if max <= min {
786            return false;
787        }
788        let d = if self.horizontal {
789            let d = if dx != 0.0 { dx } else { dy };
790            if self.mirrored && dx != 0.0 { -d } else { d }
791        } else {
792            dy
793        };
794        let pos = self.offset();
795        (d > 0.0 && pos < max - 0.5) || (d < 0.0 && pos > min + 0.5)
796    }
797
798    /// The indicator's rectangle in a view of `size` and how far it can
799    /// travel along its track, or `None` when the content fits.
800    pub fn thumb(&self, size: Size<Points>) -> Option<(Bounds<Points>, Points)> {
801        self.thumb_within(
802            size,
803            Bounds {
804                origin: Point::default(),
805                size,
806            },
807        )
808    }
809
810    /// [`ScrollState::thumb`] in a view of `size` of which the scroll
811    /// views and clips around it leave `visible` (view coordinates) in
812    /// sight: the indicator runs along the visible part's bottom (a
813    /// horizontal view) or right edge (a vertical one), so a scroll view
814    /// taller or wider than the one it is in keeps its bar in view. `None`
815    /// also when nothing of the view is visible.
816    pub fn thumb_within(
817        &self,
818        size: Size<Points>,
819        visible: Bounds<Points>,
820    ) -> Option<(Bounds<Points>, Points)> {
821        let (rect, travel) = self.thumb_f(size, visible)?;
822        Some((rect, Points(travel)))
823    }
824
825    /// The visible part's right and bottom edges in a view of `size`, or
826    /// `None` when none of it is visible.
827    fn visible_edges(size: Size<Points>, visible: Bounds<Points>) -> Option<(f32, f32)> {
828        let (w, h) = (size.width.0, size.height.0);
829        let left = visible.origin.x.0.max(0.0);
830        let top = visible.origin.y.0.max(0.0);
831        let right = (visible.origin.x.0 + visible.size.width.0).min(w);
832        let bottom = (visible.origin.y.0 + visible.size.height.0).min(h);
833        (right > left && bottom > top).then_some((right, bottom))
834    }
835
836    fn thumb_f(
837        &self,
838        size: Size<Points>,
839        visible: Bounds<Points>,
840    ) -> Option<(Bounds<Points>, f32)> {
841        const EDGE: f32 = 2.0;
842        // Zoomed content pans both ways, without a bar (as on the web).
843        if self.zooms() {
844            return None;
845        }
846        let thick = INDICATOR_THICK.0;
847        let (w, h) = (size.width.0, size.height.0);
848        let (right, bottom) = Self::visible_edges(size, visible)?;
849        let inset = self.behavior.content_inset;
850        let bar = self.behavior.scrollbar_inset.map(|v| v.0.max(0.0));
851        // Along the axis, from where the offset counts (the right of a
852        // mirrored view).
853        let (dim, total, offset, before, after) = if self.horizontal {
854            let (before, after) = if self.mirrored {
855                (bar.right, bar.left)
856            } else {
857                (bar.left, bar.right)
858            };
859            (
860                w,
861                self.content.width.0 + inset.left.0 + inset.right.0,
862                self.x.0,
863                before,
864                after,
865            )
866        } else {
867            (
868                h,
869                self.content.height.0 + inset.top.0 + inset.bottom.0,
870                self.y.0,
871                bar.top,
872                bar.bottom,
873            )
874        };
875        let (start, len) = span(dim, total, offset, before, after)?;
876        let (x, y, rw, rh) = if self.horizontal {
877            let x = if self.mirrored {
878                w - start - len
879            } else {
880                start
881            };
882            (x, bottom - bar.bottom - thick - EDGE, len, thick)
883        } else {
884            (right - bar.right - thick - EDGE, start, thick, len)
885        };
886        let rect = Bounds {
887            origin: point(Points(x), Points(y)),
888            size: Size {
889                width: Points(rw),
890                height: Points(rh),
891            },
892        };
893        Some((rect, dim - before - after - 2.0 * INDICATOR_MARGIN - len))
894    }
895
896    /// Whether a mouse press `at` a point (view coordinates) in a view of
897    /// `size` grabs the indicator, faded out or not: on the desktop it is a
898    /// scroll bar.
899    pub fn grabs_thumb(&self, size: Size<Points>, at: Point<Points>) -> bool {
900        self.grabs_thumb_within(
901            size,
902            Bounds {
903                origin: Point::default(),
904                size,
905            },
906            at,
907        )
908    }
909
910    /// [`ScrollState::grabs_thumb`] in a view of which `visible` is in
911    /// sight, the indicator placed as [`ScrollState::thumb_within`] places
912    /// it.
913    pub fn grabs_thumb_within(
914        &self,
915        size: Size<Points>,
916        visible: Bounds<Points>,
917        at: Point<Points>,
918    ) -> bool {
919        let (x, y) = (at.x.0, at.y.0);
920        if !self.indicator || !self.behavior.enabled {
921            return false;
922        }
923        let Some((rect, _)) = self.thumb_f(size, visible) else {
924            return false;
925        };
926        let Some((right, bottom)) = Self::visible_edges(size, visible) else {
927            return false;
928        };
929        // The edge the indicator runs along, moved in by its inset.
930        let bar = self.behavior.scrollbar_inset.map(|v| v.0.max(0.0));
931        let (along, across, start, len, edge) = if self.horizontal {
932            (
933                x,
934                y,
935                rect.origin.x.0,
936                rect.size.width.0,
937                bottom - bar.bottom,
938            )
939        } else {
940            (y, x, rect.origin.y.0, rect.size.height.0, right - bar.right)
941        };
942        (edge - THUMB_GRAB..=edge).contains(&across)
943            && (start - THUMB_SLOP..=start + len + THUMB_SLOP).contains(&along)
944    }
945
946    /// True when the indicator may draw something (it shows, or the view
947    /// is pulled down).
948    pub fn indicates(&self) -> bool {
949        (self.indicator && self.live.alpha > 0.0) || self.y.0 < 0.0
950    }
951
952    /// The refresh spinner's center in a view `width` wide and how far it
953    /// is pulled out (all of it while refreshing), when it shows (not when
954    /// the app draws its own); `refresh` is whether JS listens to
955    /// `onRefresh`.
956    pub fn spinner(&self, width: Points, refresh: bool) -> Option<(Point<Points>, Percentage)> {
957        let y = self.y.0;
958        let b = &self.behavior;
959        let active = self.live.refreshing || self.live.dismissing;
960        if self.horizontal || y >= 0.0 || b.refresh_indicator.is_some() || !(active || refresh) {
961            return None;
962        }
963        let progress = if active {
964            1.0
965        } else {
966            (-y / b.refresh_threshold().0).min(1.0)
967        };
968        let cy = b.content_inset.top.0 - y - b.refresh_inset().0 / 2.0;
969        Some((point(width / 2.0, Points(cy)), Percentage(progress)))
970    }
971
972    /// Opacity (`0..=1`) of the refresh spinner: `1.0` while pulling or
973    /// refreshing, fading linearly to `0.0` as the offset retracts on dismiss.
974    pub fn spinner_opacity(&self) -> f32 {
975        if self.live.dismissing {
976            let inset = self.behavior.refresh_inset().0;
977            if inset > 0.0 {
978                (-self.y.0 / inset).clamp(0.0, 1.0)
979            } else {
980                0.0
981            }
982        } else {
983            1.0
984        }
985    }
986
987    /// Each sticky cell with how far it moves at the offset.
988    pub fn sticky_shifts(&self) -> impl Iterator<Item = (NodeId, Point<Points>)> + '_ {
989        self.sticky_shifts_with(|_| 0.0)
990    }
991
992    /// [`ScrollState::sticky_shifts`], a cell's animated offset
993    /// (`StickyCell::offset`) valued by `value` (the animation graph's).
994    pub fn sticky_shifts_with<'a>(
995        &'a self,
996        value: impl Fn(crate::animation::NodeId) -> f32 + 'a,
997    ) -> impl Iterator<Item = (NodeId, Point<Points>)> + 'a {
998        let offset = Points(self.offset() - self.lead());
999        self.sticky.iter().map(move |c| {
1000            let extra = c.offset.map_or(0.0, &value);
1001            let t = sticky_shift(Points(offset.0 + extra), c.start, c.end);
1002            let zero = Points(0.0);
1003            (
1004                c.cell,
1005                if self.horizontal {
1006                    point(t, zero)
1007                } else {
1008                    point(zero, t)
1009                },
1010            )
1011        })
1012    }
1013}
1014
1015// Accessors.
1016
1017fn phase(host: &impl ScrollHost) -> Phase {
1018    host.scroll(|s, _| s.live.phase).unwrap_or(Phase::Idle)
1019}
1020
1021fn set_phase(host: &impl ScrollHost, phase: Phase) {
1022    host.scroll_mut(|s, _| s.live.phase = phase);
1023}
1024
1025/// Whether the user may scroll the view.
1026fn enabled(host: &impl ScrollHost) -> bool {
1027    host.scroll(|s, _| s.behavior.enabled).unwrap_or(false)
1028}
1029
1030/// Sends `kind` with the offset if JS listens to it.
1031fn emit(host: &impl ScrollHost, kind: EventKind) {
1032    if kind == EventKind::ScrollEnd {
1033        host.settled();
1034    }
1035    if !host.listens(kind) {
1036        return;
1037    }
1038    let offset = host.scroll(|s, size| s.reported(size)).unwrap_or_default();
1039    host.event(kind, EventPayload::Scroll(offset));
1040}
1041
1042/// Ends a glide or a snap a new input interrupts (`onMomentumEnd`,
1043/// as UIKit sends when a drag catches a glide).
1044fn interrupt(host: &impl ScrollHost) {
1045    let momentum = matches!(
1046        phase(host),
1047        Phase::Glide { .. } | Phase::Animate { momentum: true, .. }
1048    );
1049    set_phase(host, Phase::Idle);
1050    if momentum {
1051        emit(host, EventKind::MomentumEnd);
1052    }
1053}
1054
1055// Moving.
1056
1057/// Moves the offset to `to` (not clamped: drags rubber band) and updates
1058/// everything that follows it (and a zoom changed since the last move).
1059fn moved_to(host: &impl ScrollHost, to: Offset) {
1060    let moved = host.scroll_mut(|s, size| {
1061        let rezoomed = std::mem::take(&mut s.live.rezoomed);
1062        if s.pos() == to && !rezoomed {
1063            return None;
1064        }
1065        // How far it is pulled past its top, when that changes.
1066        let pulled =
1067            (!s.horizontal && (s.y.0 < 0.0 || to.y < 0.0)).then(|| Points((-to.y).max(0.0)));
1068        (s.x, s.y) = (Points(to.x), Points(to.y));
1069        if !s.horizontal && to.y >= 0.0 {
1070            s.live.dismissing = false;
1071            if !s.live.refreshing {
1072                s.live.spin_start = None;
1073                s.live.spin = Radians(0.0);
1074            }
1075        }
1076        if s.indicator {
1077            s.live.shown = host.now();
1078            s.live.alpha = 1.0;
1079            s.live.dark = host.dark();
1080        }
1081        s.live.report = true;
1082        Some((s.reported(size), pulled))
1083    });
1084    let Some(Some((offset, pulled))) = moved else {
1085        return;
1086    };
1087    host.moved(offset);
1088    if let Some(distance) = pulled {
1089        host.pulled(distance);
1090    }
1091    if host.attached() {
1092        ensure_ticking(host);
1093    } else {
1094        // No frames draw it while detached: report now.
1095        report(host);
1096    }
1097}
1098
1099/// [`moved_to`] `pos` along the main axis.
1100fn moved_along(host: &impl ScrollHost, pos: f32) {
1101    if let Some(to) = host.scroll(|s, _| s.pos().with(s.horizontal, pos)) {
1102        moved_to(host, to);
1103    }
1104}
1105
1106fn report(host: &impl ScrollHost) {
1107    let pending = host.scroll_mut(|s, size| {
1108        if !std::mem::take(&mut s.live.report) {
1109            return None;
1110        }
1111        // The zoom goes before the offset it changed: `onScroll` carries it
1112        // (and the 1 a view that zooms no more is back at).
1113        let known = s.zooms() || s.live.reported_zoom != 0.0;
1114        let zoom = (known && s.zoom != s.live.reported_zoom).then(|| {
1115            s.live.reported_zoom = s.zoom;
1116            s.zoom
1117        });
1118        Some((s.reported(size), s.applied, zoom))
1119    });
1120    if let Some(Some((offset, applied, zoom))) = pending {
1121        if let Some(zoom) = zoom {
1122            host.report_zoom(zoom);
1123        }
1124        host.report(offset, applied);
1125    }
1126}
1127
1128/// Eases to `to` (clamped to the rest limits).
1129fn animate_to(host: &impl ScrollHost, to: Offset, duration: f64, momentum: bool, end: bool) {
1130    let Some((from, to)) = host.scroll(|s, size| (s.pos(), to.clamp(s.range(size)))) else {
1131        return;
1132    };
1133    if from.distance(to) < 0.5 || duration <= 0.0 {
1134        set_phase(host, Phase::Idle);
1135        moved_to(host, to);
1136        if momentum {
1137            emit(host, EventKind::MomentumEnd);
1138        }
1139        if end {
1140            emit(host, EventKind::ScrollEnd);
1141        }
1142        return;
1143    }
1144    set_phase(
1145        host,
1146        Phase::Animate {
1147            from,
1148            to,
1149            start: host.now(),
1150            duration,
1151            momentum,
1152            end,
1153        },
1154    );
1155    ensure_ticking(host);
1156}
1157
1158/// [`animate_to`] `to` along the main axis, the other where it is.
1159fn animate_along(host: &impl ScrollHost, to: f32, duration: f64, momentum: bool, end: bool) {
1160    if let Some(to) = host.scroll(|s, _| s.pos().with(s.horizontal, to)) {
1161        animate_to(host, to, duration, momentum, end);
1162    }
1163}
1164
1165/// The user let go at `v` points per ms (positive: the offset grows):
1166/// bounces back, snaps, glides or settles. Snapping uses `snap_velocity`
1167/// (along the main axis) when it is not 0 (a settled mouse wheel).
1168fn release(host: &impl ScrollHost, v: Offset, snap_velocity: f32) {
1169    let Some((pos, (min, max), main, target)) = host.scroll(|s, size| {
1170        let range = s.range(size);
1171        let pos = s.pos();
1172        let main = v.along(s.horizontal);
1173        let lead = s.lead();
1174        let dim = s.viewport(size);
1175        let snap_velocity = if snap_velocity == 0.0 {
1176            main
1177        } else {
1178            snap_velocity
1179        };
1180        let max = range.1.along(s.horizontal);
1181        // Snap points are content offsets: UIKit's coordinates. Zoomed
1182        // content does not snap.
1183        let target = s
1184            .behavior
1185            .snap_target(
1186                Points(s.offset() - lead),
1187                projected(Points(s.offset()), main, rate(&s.behavior)) - Points(lead),
1188                snap_velocity,
1189                Points(dim),
1190                Points(max + dim - lead),
1191            )
1192            .filter(|_| !s.zooms())
1193            .map(|t| (pos.with(s.horizontal, t.0 + lead), t.0 + lead - s.offset()));
1194        (pos, range, main, target)
1195    }) else {
1196        return;
1197    };
1198    let past = |p: f32, min: f32, max: f32| p < min - 0.5 || p > max + 0.5;
1199    let room = |v: f32, p: f32, min: f32, max: f32| v > 0.0 && p < max || v < 0.0 && p > min;
1200    if past(pos.x, min.x, max.x) || past(pos.y, min.y, max.y) || (min.y == 0.0 && pos.y < 0.0) {
1201        animate_to(host, pos.clamp((min, max)), ANIMATION, false, true);
1202    } else if let Some((target, distance)) = target {
1203        let duration = snap_duration(Points(distance), main);
1204        if duration > 0.0 {
1205            emit(host, EventKind::MomentumStart);
1206        }
1207        animate_to(host, target, duration, duration > 0.0, true);
1208    } else if v.x.abs().max(v.y.abs()) > MIN_GLIDE
1209        && (room(v.x, pos.x, min.x, max.x) || room(v.y, pos.y, min.y, max.y))
1210    {
1211        set_phase(
1212            host,
1213            Phase::Glide {
1214                velocity: v,
1215                last: host.now(),
1216            },
1217        );
1218        emit(host, EventKind::MomentumStart);
1219        ensure_ticking(host);
1220    } else {
1221        set_phase(host, Phase::Idle);
1222        emit(host, EventKind::ScrollEnd);
1223    }
1224}
1225
1226// The frame clock.
1227
1228fn ensure_ticking(host: &impl ScrollHost) {
1229    let start = host.scroll_mut(|s, _| !std::mem::replace(&mut s.live.ticking, true));
1230    if start == Some(true) {
1231        host.start_ticking();
1232    }
1233}
1234
1235/// One frame of the view's motion at `now` (ms); false when there is
1236/// nothing left to do, and the frame callback stops.
1237pub fn frame(host: &impl ScrollHost, now: f64) -> bool {
1238    let left = tick(host, now);
1239    if left == Left::Busy {
1240        return true;
1241    }
1242    let now_for_timer = (left == Left::Hold).then(|| host.now());
1243    let wake = host.scroll_mut(|s, _| {
1244        s.live.ticking = false;
1245        match (left, now_for_timer) {
1246            // Nothing changes on screen until the hold ends: no frames until
1247            // then, or following the end of a stream would draw every frame.
1248            // Measure remaining hold from the current clock, not the frame
1249            // timestamp, because `shown` was recorded from `host.now()`.
1250            (Left::Hold, Some(current)) if !std::mem::replace(&mut s.live.hold_timer, true) => {
1251                Some(indicator_hold_left(current - s.live.shown))
1252            }
1253            _ => None,
1254        }
1255    });
1256    match wake {
1257        Some(Some(Some(ms))) => {
1258            if host.wake_after(ms) {
1259                return false;
1260            }
1261            // Timer creation failed: clear the flag and stay on the frame
1262            // callback path so the indicator still fades and future holds work.
1263            host.scroll_mut(|s, _| {
1264                s.live.hold_timer = false;
1265                s.live.ticking = true;
1266            });
1267            true
1268        }
1269        Some(Some(None)) => {
1270            // The hold already elapsed by `host.now()`: keep ticking to fade.
1271            host.scroll_mut(|s, _| {
1272                s.live.hold_timer = false;
1273                s.live.ticking = true;
1274            });
1275            true
1276        }
1277        _ => false,
1278    }
1279}
1280
1281/// What [`hold_ended`] should do once the previous hold timer fires.
1282enum HoldAction {
1283    Done,
1284    Rearm(u64),
1285    Fade,
1286}
1287
1288/// The wait [`frame`] asked of [`ScrollHost::wake_after`] is over: the frames
1289/// that fade the indicator start, or the timer re-arms directly for the
1290/// remaining hold if it was shown again since. A view out of the window gets
1291/// no frames: its indicator is gone when it returns.
1292#[doc(hidden)]
1293pub fn hold_ended(host: &impl ScrollHost) {
1294    let attached = host.attached();
1295    let current = attached.then(|| host.now());
1296    let action = host.scroll_mut(|s, _| {
1297        s.live.hold_timer = false;
1298        if !attached {
1299            s.live.alpha = 0.0;
1300            return HoldAction::Done;
1301        }
1302        if s.live.alpha <= 0.0 || s.live.ticking || matches!(s.live.phase, Phase::Thumb { .. }) {
1303            return HoldAction::Done;
1304        }
1305        if let Some(ms) = indicator_hold_left(current.unwrap_or(0.0) - s.live.shown) {
1306            s.live.hold_timer = true;
1307            HoldAction::Rearm(ms)
1308        } else {
1309            HoldAction::Fade
1310        }
1311    });
1312    match action {
1313        Some(HoldAction::Rearm(ms)) => {
1314            if !host.wake_after(ms) {
1315                host.scroll_mut(|s, _| s.live.hold_timer = false);
1316                ensure_ticking(host);
1317            }
1318        }
1319        Some(HoldAction::Fade) => ensure_ticking(host),
1320        _ => {}
1321    }
1322}
1323
1324/// What a scroll view has left to do after a frame.
1325#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1326enum Left {
1327    Done,
1328    Busy,
1329    /// Only the indicator's hold remains.
1330    Hold,
1331}
1332
1333/// When the view's motion next comes to something (ms, the clock
1334/// [`frame`] is given): a glide's or an eased move's end, a mouse wheel's
1335/// rest; what a surface that draws no frames (a hidden window) runs
1336/// [`frame`] at, so the scroll ends and reports it on time without
1337/// frames. `None` while nothing runs that ends by itself (the indicator's
1338/// fade and the refresh spinner only draw).
1339pub fn deadline(host: &impl ScrollHost, now: f64) -> Option<f64> {
1340    let (phase, rate) = host.scroll(|s, _| (s.live.phase, rate(&s.behavior)))?;
1341    let end = match phase {
1342        Phase::Glide { velocity, last } => {
1343            // It slows below `STOP` then, or meets an edge before.
1344            let speed = velocity.x.abs().max(velocity.y.abs());
1345            if speed < STOP || !(0.0..1.0).contains(&rate) {
1346                last
1347            } else {
1348                last + ((STOP / speed).ln() / rate.ln()).max(0.0) as f64
1349            }
1350        }
1351        Phase::Animate {
1352            start, duration, ..
1353        }
1354        | Phase::Zoom {
1355            start, duration, ..
1356        } => start + duration,
1357        Phase::Wheel {
1358            last,
1359            gesture: false,
1360            glide,
1361            ..
1362        } => (last + WHEEL_IDLE).max(glide.end()),
1363        _ => return None,
1364    };
1365    // A millisecond past it: a frame there finds it ended whatever the
1366    // rounding.
1367    Some(end.max(now) + 1.0)
1368}
1369
1370/// The view left the window during its frames: it stops (a later move
1371/// starts again) and reports where it is.
1372pub fn detached(host: &impl ScrollHost) {
1373    set_phase(host, Phase::Idle);
1374    report(host);
1375    host.scroll_mut(|s, _| {
1376        s.live.ticking = false;
1377        s.live.dismissing = false;
1378        if !s.live.refreshing {
1379            s.live.spin_start = None;
1380            s.live.spin = Radians(0.0);
1381        }
1382    });
1383}
1384
1385/// Cancels an active input gesture (drag, thumb, wheel, or pinch) when its
1386/// scroll view leaves the tree: returns to idle without firing release actions
1387/// such as pull-to-refresh or starting a glide or zoom spring, and clamps any
1388/// rubber-banded zoom or offset back within rest limits.
1389///
1390/// Unlike [`detached`], this leaves `live.ticking` untouched so an already
1391/// registered frame callback is not duplicated if the view is re-inserted.
1392pub fn cancel_input(host: &impl ScrollHost) {
1393    set_phase(host, Phase::Idle);
1394    let clamped = host.scroll(|s, size| {
1395        let zoom = if s.zooms() {
1396            limit_zoom(&s.behavior, s.zoom, false)
1397        } else {
1398            s.zoom
1399        };
1400        if zoom != s.zoom {
1401            let center = Offset::new(size.width.0 / 2.0, size.height.0 / 2.0);
1402            (Some((zoom, s.content_at(size, center), center)), None)
1403        } else {
1404            let pos = s.pos();
1405            let rest = pos.clamp(s.range(size));
1406            (None, (rest != pos).then_some(rest))
1407        }
1408    });
1409    if let Some((Some((zoom, c, center)), _)) = clamped {
1410        zoom_at(host, zoom, c, center);
1411    } else if let Some((None, Some(rest))) = clamped {
1412        moved_to(host, rest);
1413    }
1414    host.scroll_mut(|s, _| {
1415        s.live.dismissing = false;
1416        if !s.live.refreshing {
1417            s.live.spin_start = None;
1418            s.live.spin = Radians(0.0);
1419        }
1420    });
1421    report(host);
1422}
1423
1424fn tick(host: &impl ScrollHost, now: f64) -> Left {
1425    let Some((phase, pos, rate, (min, max))) =
1426        host.scroll(|s, size| (s.live.phase, s.pos(), rate(&s.behavior), s.range(size)))
1427    else {
1428        return Left::Done;
1429    };
1430    match phase {
1431        Phase::Glide { velocity, last } => {
1432            let dt = (now - last).max(0.0) as f32;
1433            // Each axis glides until it slows down or meets an edge; the
1434            // glide ends when both have.
1435            let axis = |v: f32, p: f32, min: f32, max: f32| {
1436                let (d, v) = glide_step(v, rate, dt);
1437                let next = p + d;
1438                let stopped = v.abs() < STOP || next <= min || next >= max;
1439                (next, if stopped { 0.0 } else { v }, stopped)
1440            };
1441            let (x, vx, stop_x) = axis(velocity.x, pos.x, min.x, max.x);
1442            let (y, vy, stop_y) = axis(velocity.y, pos.y, min.y, max.y);
1443            moved_to(host, Offset::new(x, y).clamp((min, max)));
1444            if stop_x && stop_y {
1445                set_phase(host, Phase::Idle);
1446                emit(host, EventKind::MomentumEnd);
1447                emit(host, EventKind::ScrollEnd);
1448            } else {
1449                set_phase(
1450                    host,
1451                    Phase::Glide {
1452                        velocity: Offset::new(vx, vy),
1453                        last: now,
1454                    },
1455                );
1456            }
1457        }
1458        Phase::Animate {
1459            from,
1460            to,
1461            start,
1462            duration,
1463            momentum,
1464            end,
1465        } => {
1466            let t = (now - start) / duration;
1467            moved_to(host, from.lerp(to, ease_out(t)));
1468            if t >= 1.0 {
1469                set_phase(host, Phase::Idle);
1470                if momentum {
1471                    emit(host, EventKind::MomentumEnd);
1472                }
1473                if end {
1474                    emit(host, EventKind::ScrollEnd);
1475                }
1476            }
1477        }
1478        Phase::Zoom {
1479            from,
1480            to,
1481            from_c,
1482            to_c,
1483            at,
1484            start,
1485            duration,
1486        } => {
1487            let t = (now - start) / duration;
1488            let k = ease_out(t);
1489            zoom_at(host, from + (to - from) * k, from_c.lerp(to_c, k), at);
1490            if t >= 1.0 {
1491                set_phase(host, Phase::Idle);
1492            }
1493        }
1494        Phase::Wheel {
1495            gesture: false,
1496            raw,
1497            glide,
1498            ..
1499        } if now < glide.end() => {
1500            moved_to(host, glide.value(raw.into(), now).into());
1501        }
1502        Phase::Wheel {
1503            last,
1504            total,
1505            gesture: false,
1506            raw,
1507            glide,
1508        } if now - last > WHEEL_IDLE => {
1509            // A mouse wheel came to rest (a glide where it was going):
1510            // snapping views move on to the next snap point in the wheel's
1511            // direction, and a view pulled past an edge bounces back.
1512            if glide != wheel_glide::Glide::default() {
1513                moved_to(host, raw);
1514            }
1515            set_phase(host, Phase::Idle);
1516            let snaps = host
1517                .scroll(|s, _| s.behavior.snaps() || s.behavior.paging)
1518                .unwrap_or(false);
1519            let v = if snaps && total.abs() >= 1.0 {
1520                total.signum() * WHEEL_SNAP
1521            } else {
1522                0.0
1523            };
1524            release(host, Offset::default(), v);
1525        }
1526        Phase::Idle
1527            if pos.x < min.x - 0.5
1528                || pos.x > max.x.max(min.x) + 0.5
1529                || pos.y < min.y - 0.5
1530                || pos.y > max.y.max(min.y) + 0.5
1531                || (min.y == 0.0 && pos.y < 0.0) =>
1532        {
1533            moved_to(host, pos.clamp((min, max)))
1534        }
1535        _ => {}
1536    }
1537    report(host);
1538    let Some((left, redraw)) = host.scroll_mut(|s, _| {
1539        let mut redraw = false;
1540        let mut hold = None;
1541        let mut busy = !matches!(
1542            s.live.phase,
1543            Phase::Idle
1544                | Phase::Drag { .. }
1545                | Phase::Thumb { .. }
1546                | Phase::Wheel { gesture: true, .. }
1547        );
1548        if matches!(s.live.phase, Phase::Thumb { .. }) {
1549            // A held thumb stays until it is let go (`thumb_end`).
1550            s.live.shown = now;
1551        } else if s.live.alpha > 0.0 {
1552            let since = now - s.live.shown;
1553            let alpha = indicator_alpha(since);
1554            if alpha != s.live.alpha {
1555                s.live.alpha = alpha;
1556                redraw = true;
1557            }
1558            hold = indicator_hold_left(since);
1559            busy |= alpha > 0.0 && hold.is_none();
1560        }
1561        if matches!(s.live.phase, Phase::Idle) && s.live.dismissing {
1562            s.live.dismissing = false;
1563            if !s.live.refreshing {
1564                s.live.spin_start = None;
1565                s.live.spin = Radians(0.0);
1566            }
1567            redraw = true;
1568        }
1569        if !s.horizontal
1570            && s.offset() < 0.0
1571            && (s.live.refreshing || s.live.dismissing)
1572            && s.behavior.refresh_indicator.is_none()
1573        {
1574            let start = *s.live.spin_start.get_or_insert(now);
1575            s.live.spin = spin_angle(now - start);
1576            redraw = true;
1577            busy = true;
1578        }
1579        let left = match hold {
1580            _ if busy => Left::Busy,
1581            Some(_) => Left::Hold,
1582            None => Left::Done,
1583        };
1584        (left, redraw)
1585    }) else {
1586        return Left::Done;
1587    };
1588    if redraw {
1589        host.redraw();
1590    }
1591    left
1592}
1593
1594// Mount items.
1595
1596/// `ScrollConfig`.
1597pub fn config(
1598    host: &impl ScrollHost,
1599    horizontal: bool,
1600    indicator: bool,
1601    replaced: bool,
1602    mirrored: bool,
1603) {
1604    let changed = host.scroll_mut(|s, _| {
1605        s.horizontal = horizontal;
1606        // The view shows its indicator only when it asks to, on either
1607        // axis: a mouse without a horizontal wheel still moves a
1608        // horizontal view with Shift + wheel, with the vertical wheel
1609        // where nothing around scrolls vertically, and with the keys. A
1610        // built-in bar of the app's (`replaced`) takes its place.
1611        s.indicator = indicator && !replaced;
1612        if !indicator {
1613            s.live.alpha = 0.0;
1614        }
1615        let mirrored = mirrored && horizontal;
1616        std::mem::replace(&mut s.mirrored, mirrored) != mirrored
1617    });
1618    if changed == Some(true) {
1619        host.relayout();
1620    }
1621}
1622
1623/// `ScrollContent`. Content that shrank below the offset pulls it back on
1624/// the next frame, once the rest of the batch (the `ScrollBy` that keeps
1625/// the visible content in place) is applied.
1626pub fn content(host: &impl ScrollHost, content: Size<Points>) {
1627    let Some((past, zooms)) = host.scroll_mut(|s, size| {
1628        s.content = content;
1629        let (p, (min, max)) = (s.pos(), s.range(size));
1630        (
1631            p.x > max.x.max(min.x) + 0.5 || p.y > max.y.max(min.y) + 0.5,
1632            s.zooms(),
1633        )
1634    }) else {
1635        return;
1636    };
1637    if zooms {
1638        // Centered content moves with its size.
1639        host.relayout();
1640    }
1641    if past {
1642        ensure_ticking(host);
1643    }
1644    host.redraw();
1645}
1646
1647/// `ScrollBy`: the core keeps the visible content in place (items above
1648/// the viewport changed size); not clamped, the core knows its content.
1649pub fn scroll_by(host: &impl ScrollHost, delta: Point<Points>) {
1650    let (dx, dy) = (delta.x.0, delta.y.0);
1651    let Some((pos, d)) = host.scroll_mut(|s, _| {
1652        s.applied = s.applied.wrapping_add(1);
1653        // The off axis would only push the content out of the viewport
1654        // (zoomed content moves along both).
1655        let d = if s.zooms() {
1656            Offset::new(dx, dy)
1657        } else {
1658            Offset::default().with(s.horizontal, if s.horizontal { dx } else { dy })
1659        };
1660        s.live.phase = shifted(s.live.phase, d, s.horizontal);
1661        s.live.report = true;
1662        (s.pos(), d)
1663    }) else {
1664        return;
1665    };
1666    if d != Offset::default() {
1667        moved_to(host, pos + d);
1668    }
1669    report(host);
1670}
1671
1672/// `ScrollBehavior`.
1673pub fn behavior(host: &impl ScrollHost, behavior: &ScrollBehavior) {
1674    let Some((inset, refresh, held, zoom)) = host.scroll_mut(|s, _| {
1675        // Zooming and centering place the children too.
1676        let inset = s.behavior.content_inset != behavior.content_inset
1677            || s.can_zoom
1678                && (s.behavior.zooms() != behavior.zooms()
1679                    || s.behavior.center_content != behavior.center_content);
1680        let refresh = s.behavior.refresh_indicator != behavior.refresh_indicator;
1681        s.behavior = behavior.clone();
1682        // Within the new limits; back to 1 when it zooms no more.
1683        let zoom = if s.zooms() {
1684            limit_zoom(behavior, s.zoom, false)
1685        } else {
1686            1.0
1687        };
1688        if !behavior.enabled
1689            && matches!(
1690                s.live.phase,
1691                Phase::Drag { .. } | Phase::Thumb { .. } | Phase::Wheel { .. }
1692            )
1693        {
1694            s.live.phase = Phase::Idle;
1695        }
1696        // A refresh in progress keeps the room of the indicator now showing.
1697        let held = (refresh
1698            && !s.horizontal
1699            && s.live.refreshing
1700            && s.offset() < 0.0
1701            && !matches!(s.live.phase, Phase::Drag { .. }))
1702        .then(|| behavior.refresh_inset().0);
1703        (inset, refresh, held, (zoom != s.zoom).then_some(zoom))
1704    }) else {
1705        return;
1706    };
1707    if let Some(zoom) = zoom {
1708        zoom_to(host, zoom, None, false);
1709    }
1710    if inset {
1711        host.relayout();
1712    }
1713    if refresh {
1714        host.redraw();
1715    }
1716    if let Some(room) = held {
1717        animate_along(host, -room, ANIMATION, false, false);
1718    }
1719}
1720
1721/// `Refreshing`: shows the spinner above the content (scrolling to it
1722/// when at the top) or hides it.
1723pub fn refreshing(host: &impl ScrollHost, refreshing: bool) {
1724    let Some(Some((pos, dragging, inset))) = host.scroll_mut(|s, _| {
1725        if s.horizontal || s.live.refreshing == refreshing {
1726            return None;
1727        }
1728        s.live.refreshing = refreshing;
1729        if refreshing {
1730            s.live.dismissing = false;
1731        } else if s.offset() < 0.0 {
1732            s.live.dismissing = true;
1733        } else {
1734            s.live.dismissing = false;
1735            s.live.spin_start = None;
1736            s.live.spin = Radians(0.0);
1737        }
1738        Some((
1739            s.offset(),
1740            matches!(s.live.phase, Phase::Drag { .. }),
1741            s.behavior.refresh_inset().0,
1742        ))
1743    }) else {
1744        return;
1745    };
1746    host.redraw();
1747    if dragging {
1748        return;
1749    }
1750    if refreshing && pos <= 0.5 {
1751        animate_along(host, -inset, ANIMATION, false, false);
1752    } else if !refreshing && pos < 0.0 {
1753        animate_along(host, 0.0, ANIMATION, false, false);
1754    }
1755}
1756
1757/// `scrollTo`, `scrollToEnd` (the core resolves `scrollToIndex` and,
1758/// usually, `scrollToEnd` into `scrollTo`) and `zoomTo`.
1759pub fn command(host: &impl ScrollHost, command: &Command) {
1760    if let Command::ZoomTo {
1761        scale,
1762        center,
1763        animated,
1764    } = *command
1765    {
1766        let center = center.map(|c| Offset::new(c.x.0, c.y.0));
1767        return zoom_to(host, scale, center, animated);
1768    }
1769    let Some(Some((target, animated))) = host.scroll_mut(|s, size| {
1770        let range = s.range(size);
1771        let inset = s.behavior.content_inset;
1772        let (target, animated) = match *command {
1773            // Zoomed content goes to both; any other view along its axis.
1774            Command::ScrollTo { x, y, animated } => (
1775                if s.zooms() {
1776                    Offset::new(x.0 + inset.left.0, y.0 + inset.top.0)
1777                } else if s.horizontal {
1778                    s.pos().with(true, x.0 + inset.left.0)
1779                } else {
1780                    s.pos().with(false, y.0 + inset.top.0)
1781                },
1782                animated,
1783            ),
1784            Command::ScrollToEnd { animated } => (
1785                s.pos().with(s.horizontal, range.1.along(s.horizontal)),
1786                animated,
1787            ),
1788            Command::ScrollToIndex { .. } => {
1789                log::debug!("scroll: {command:?} is not supported");
1790                return None;
1791            }
1792            _ => return None,
1793        };
1794        s.applied = s.applied.wrapping_add(1);
1795        s.live.report = true;
1796        Some((target.clamp(range), animated))
1797    }) else {
1798        return;
1799    };
1800    interrupt(host);
1801    if animated {
1802        animate_to(host, target, ANIMATION, false, true);
1803    } else {
1804        moved_to(host, target);
1805    }
1806    report(host);
1807}
1808
1809// Zooming.
1810
1811/// `scale` within the zoom limits; past them by a rubber band while
1812/// pinching (`rubber`) when `bouncesZoom`, as the web's.
1813fn limit_zoom(b: &ScrollBehavior, scale: f32, rubber: bool) -> f32 {
1814    let (min, max) = (b.min_zoom, b.max_zoom.max(b.min_zoom));
1815    let band = |limit: f32| limit * (scale / limit).powf(0.3);
1816    if scale > max {
1817        if rubber && b.bounces_zoom {
1818            band(max)
1819        } else {
1820            max
1821        }
1822    } else if scale < min {
1823        if rubber && b.bounces_zoom {
1824            band(min)
1825        } else {
1826            min
1827        }
1828    } else {
1829        scale
1830    }
1831}
1832
1833/// Zooms the view to `scale` with content point `c` (unzoomed) at point
1834/// `at` of its viewport, as far as the content's edges let it.
1835fn zoom_at(host: &impl ScrollHost, scale: f32, c: Offset, at: Offset) {
1836    let to = host.scroll_mut(|s, size| {
1837        if s.zoom != scale {
1838            s.zoom = scale;
1839            s.live.rezoomed = true;
1840        }
1841        s.showing(size, c, at)
1842    });
1843    if let Some(to) = to {
1844        moved_to(host, to);
1845    }
1846}
1847
1848/// `zoomTo`: `scale` (within the limits) with content point `center`
1849/// (unzoomed) in the middle of the viewport, or the point there now.
1850fn zoom_to(host: &impl ScrollHost, scale: f32, center: Option<Offset>, animated: bool) {
1851    let Some(Some((from, to, at, now_c))) = host.scroll(|s, size| {
1852        // One that zooms no more goes back to 1 ([`behavior`]).
1853        if !s.zooms() && s.zoom == 1.0 {
1854            log::debug!("scroll: zoomTo on a scroll view that does not zoom");
1855            return None;
1856        }
1857        let to = if s.zooms() {
1858            limit_zoom(&s.behavior, scale, false)
1859        } else {
1860            1.0
1861        };
1862        let at = Offset::new(size.width.0 / 2.0, size.height.0 / 2.0);
1863        Some((s.zoom, to, at, s.content_at(size, at)))
1864    }) else {
1865        return;
1866    };
1867    interrupt(host);
1868    let c = center.unwrap_or(now_c);
1869    if animated && host.attached() && (to - from).abs() > 1e-4 {
1870        zoom_eased(host, from, to, now_c, c, at);
1871    } else {
1872        zoom_at(host, to, c, at);
1873        report(host);
1874    }
1875}
1876
1877/// Eases the zoom from `from` to `to`, the content point at `at` moving
1878/// from `from_c` to `to_c`.
1879fn zoom_eased(
1880    host: &impl ScrollHost,
1881    from: f32,
1882    to: f32,
1883    from_c: Offset,
1884    to_c: Offset,
1885    at: Offset,
1886) {
1887    set_phase(
1888        host,
1889        Phase::Zoom {
1890            from,
1891            to,
1892            from_c,
1893            to_c,
1894            at,
1895            start: host.now(),
1896            duration: ANIMATION,
1897        },
1898    );
1899    ensure_ticking(host);
1900}
1901
1902/// Whether a pinch over the view zooms it: it zooms and is `zoomable`.
1903pub fn pinches(host: &impl ScrollHost) -> bool {
1904    host.scroll(|s, _| s.zooms() && s.behavior.pinch)
1905        .unwrap_or(false)
1906}
1907
1908/// A pinch (a touchpad's or two fingers') over the view
1909/// ([`pinches`]) began: what moves stops.
1910pub fn pinch_begin(host: &impl ScrollHost) {
1911    interrupt(host);
1912    host.scroll_mut(|s, _| s.live.pinch_from = s.zoom);
1913}
1914
1915/// The pinch is at `scale` times the zoom it began at, around point `at`
1916/// of the viewport, which stays on the same content point. Past the limits
1917/// it rubber-bands when `bouncesZoom`, and stops at them otherwise.
1918pub fn pinch(host: &impl ScrollHost, scale: f32, at: Point<Points>) {
1919    let at = Offset::new(at.x.0, at.y.0);
1920    let Some((to, c)) = host.scroll_mut(|s, size| {
1921        let raw = s.live.pinch_from * scale;
1922        let to = limit_zoom(&s.behavior, raw, true);
1923        (to, s.content_at(size, at))
1924    }) else {
1925        return;
1926    };
1927    zoom_at(host, to, c, at);
1928}
1929
1930/// The pinch around `at` ended: past the limits it springs back to them.
1931pub fn pinch_end(host: &impl ScrollHost, at: Point<Points>) {
1932    let at = Offset::new(at.x.0, at.y.0);
1933    let Some((from, to, c)) = host.scroll(|s, size| {
1934        (
1935            s.zoom,
1936            limit_zoom(&s.behavior, s.zoom, false),
1937            s.content_at(size, at),
1938        )
1939    }) else {
1940        return;
1941    };
1942    if (to - from).abs() > 1e-4 {
1943        zoom_eased(host, from, to, c, c, at);
1944    }
1945}
1946
1947// Drags.
1948
1949/// A finger or pen drag starts scrolling the view (the mouse never drags
1950/// content).
1951pub fn drag_begin(host: &impl ScrollHost) {
1952    if !enabled(host) {
1953        return;
1954    }
1955    interrupt(host);
1956    let (start, cleared) = host
1957        .scroll_mut(|s, _| {
1958            let cleared = !s.live.refreshing && std::mem::take(&mut s.live.dismissing);
1959            if cleared {
1960                s.live.spin_start = None;
1961                s.live.spin = Radians(0.0);
1962            }
1963            (s.pos(), cleared)
1964        })
1965        .unwrap_or_default();
1966    if cleared {
1967        host.redraw();
1968    }
1969    set_phase(
1970        host,
1971        Phase::Drag {
1972            start,
1973            moved: Offset::default(),
1974        },
1975    );
1976    emit(host, EventKind::ScrollDragStart);
1977}
1978
1979/// The drag moved by `delta` since the last move (content follows the
1980/// pointer: positive scrolls toward the start).
1981pub fn drag_move(host: &impl ScrollHost, delta: Point<Points>) {
1982    drag(host, delta.x.0, delta.y.0, false);
1983}
1984
1985/// The drag moved by `moved` since it began.
1986pub fn drag_to(host: &impl ScrollHost, moved: Point<Points>) {
1987    drag(host, moved.x.0, moved.y.0, true);
1988}
1989
1990fn drag(host: &impl ScrollHost, dx: f32, dy: f32, since_begin: bool) {
1991    let Phase::Drag { start, moved } = phase(host) else {
1992        return;
1993    };
1994    let Some((pos, moved)) = host.scroll(|s, size| {
1995        let (min, max) = s.range(size);
1996        let d = if s.zooms() {
1997            Offset::new(-dx, -dy)
1998        } else if !s.horizontal {
1999            Offset::new(0.0, -dy)
2000        } else if s.mirrored {
2001            Offset::new(dx, 0.0)
2002        } else {
2003            Offset::new(-dx, 0.0)
2004        };
2005        // Accumulated, not added to the offset: the rubber band applies to
2006        // where the pointer went, not to where the content was.
2007        let moved = if since_begin { d } else { moved + d };
2008        let raw = start + moved;
2009        let bounces = s.behavior.bounces;
2010        let pos = Offset::new(
2011            drag_position(raw.x, min.x, max.x.max(min.x), size.width.0, bounces),
2012            drag_position(raw.y, min.y, max.y.max(min.y), size.height.0, bounces),
2013        );
2014        (pos, moved)
2015    }) else {
2016        return;
2017    };
2018    set_phase(host, Phase::Drag { start, moved });
2019    moved_to(host, pos);
2020}
2021
2022/// The drag ended with a velocity of `(vx, vy)` points per second: a
2023/// glide follows.
2024pub fn drag_end(host: &impl ScrollHost, vx: f32, vy: f32) {
2025    if !matches!(phase(host), Phase::Drag { .. }) {
2026        return;
2027    }
2028    let listens = host.listens(EventKind::Refresh);
2029    let Some((v, refresh)) = host.scroll(|s, _| {
2030        let v = if s.zooms() {
2031            Offset::new(-vx / 1000.0, -vy / 1000.0)
2032        } else {
2033            let v = if !s.horizontal {
2034                -vy
2035            } else if s.mirrored {
2036                vx
2037            } else {
2038                -vx
2039            } / 1000.0;
2040            Offset::default().with(s.horizontal, v)
2041        };
2042        let refresh = !s.horizontal
2043            && !s.live.refreshing
2044            && listens
2045            && s.behavior.refreshes(Points(s.offset()));
2046        (v, refresh)
2047    }) else {
2048        return;
2049    };
2050    set_phase(host, Phase::Idle);
2051    emit(host, EventKind::ScrollDragEnd);
2052    if refresh {
2053        // Shown right away, as UIRefreshControl does; JS turns it off.
2054        host.scroll_mut(|s, _| {
2055            s.live.refreshing = true;
2056            s.live.dismissing = false;
2057        });
2058        host.event(EventKind::Refresh, EventPayload::None);
2059    }
2060    release(host, v, 0.0);
2061}
2062
2063// The indicator as a scroll bar.
2064
2065/// The mouse moved over the view: its indicator shows (and fades again
2066/// once the mouse rests), as overlay scroll bars do, so that a mouse user
2067/// sees it can scroll and where its scroll bar is.
2068pub fn hovered(host: &impl ScrollHost) {
2069    let shown = host.scroll_mut(|s, size| {
2070        if s.thumb(size).is_none() || !s.indicator || !s.behavior.enabled {
2071            return false;
2072        }
2073        s.live.shown = host.now();
2074        if s.live.alpha == 1.0 {
2075            return false;
2076        }
2077        s.live.alpha = 1.0;
2078        s.live.dark = host.dark();
2079        true
2080    });
2081    if shown != Some(true) {
2082        return;
2083    }
2084    host.redraw();
2085    ensure_ticking(host);
2086}
2087
2088/// The mouse grabbed the view's indicator ([`ScrollState::grabs_thumb`]).
2089pub fn thumb_begin(host: &impl ScrollHost) {
2090    interrupt(host);
2091    let grabbed = host.scroll_mut(|s, _| {
2092        s.live.phase = Phase::Thumb { start: s.offset() };
2093        s.live.shown = host.now();
2094        s.live.alpha = 1.0;
2095        s.live.dark = host.dark();
2096    });
2097    if grabbed.is_none() {
2098        return;
2099    }
2100    host.redraw();
2101    emit(host, EventKind::ScrollDragStart);
2102}
2103
2104/// The grabbed indicator was dragged by `moved` since it was grabbed: the
2105/// content moves the other way, so the thumb follows the pointer (a
2106/// content drag moves the content with it).
2107pub fn thumb_move(host: &impl ScrollHost, moved: Point<Points>) {
2108    let (dx, dy) = (moved.x.0, moved.y.0);
2109    let Phase::Thumb { start } = phase(host) else {
2110        return;
2111    };
2112    let Some(Some(pos)) = host.scroll(|s, size| {
2113        let (_, travel) = s.thumb(size)?;
2114        let (min, max) = s.limits(size);
2115        let d = if !s.horizontal {
2116            dy
2117        } else if s.mirrored {
2118            -dx
2119        } else {
2120            dx
2121        };
2122        let d = thumb_scroll(Points(d), Points(max), travel).0;
2123        Some((start + d).clamp(min, max.max(min)))
2124    }) else {
2125        return;
2126    };
2127    moved_along(host, pos);
2128}
2129
2130/// The grabbed indicator was let go: it fades from now, snapping views
2131/// settle on a snap point.
2132pub fn thumb_end(host: &impl ScrollHost) {
2133    if !matches!(phase(host), Phase::Thumb { .. }) {
2134        return;
2135    }
2136    set_phase(host, Phase::Idle);
2137    host.scroll_mut(|s, _| s.live.shown = host.now());
2138    ensure_ticking(host);
2139    emit(host, EventKind::ScrollDragEnd);
2140    release(host, Offset::default(), 0.0);
2141}
2142
2143// Wheels and touchpads.
2144
2145/// A wheel or touchpad scroll starts on the view (a touchpad gesture: it
2146/// ends with [`wheel_end`]).
2147pub fn wheel_begin(host: &impl ScrollHost) {
2148    if !enabled(host) {
2149        return;
2150    }
2151    interrupt(host);
2152    set_phase(
2153        host,
2154        Phase::Wheel {
2155            last: host.now(),
2156            total: 0.0,
2157            gesture: true,
2158            raw: Offset::default(),
2159            glide: wheel_glide::Glide::default(),
2160        },
2161    );
2162    emit(host, EventKind::ScrollDragStart);
2163}
2164
2165/// Scrolls the view by `delta` (positive toward the end). Without
2166/// [`wheel_begin`] it is a mouse wheel, which settles when idle.
2167pub fn wheel(host: &impl ScrollHost, delta: Point<Points>) {
2168    wheel_by(host, delta, false);
2169}
2170
2171/// A mouse wheel's notch of `delta` on a view that [`smooth_wheel`]s: it
2172/// glides there as Chromium's does ([`wheel_glide`]), and a notch during
2173/// the glide moves where it goes on from where the last one pointed, at the
2174/// speed it has, so a run of notches is one motion. It settles as
2175/// [`wheel`] does.
2176#[doc(hidden)]
2177pub fn wheel_smooth(host: &impl ScrollHost, delta: Point<Points>) {
2178    wheel_by(host, delta, true);
2179}
2180
2181/// Whether a mouse wheel's notches glide on the view (`smoothWheel`): not
2182/// where they step through snap points or pages, or zoom.
2183#[doc(hidden)]
2184pub fn smooth_wheel(host: &impl ScrollHost) -> bool {
2185    host.scroll(|s, _| {
2186        s.behavior.smooth_wheel && !s.zooms() && !s.behavior.snaps() && !s.behavior.paging
2187    })
2188    .unwrap_or(false)
2189}
2190
2191/// A notch's `delta` (points the platform gave it, `line` points a line
2192/// along each axis) in the view's own lines (`wheelLineHeight`), when it
2193/// sets them.
2194#[doc(hidden)]
2195pub fn wheel_line(
2196    host: &impl ScrollHost,
2197    delta: Point<Points>,
2198    line: Point<Points>,
2199) -> Point<Points> {
2200    let height = host
2201        .scroll(|s, _| s.behavior.wheel_line_height)
2202        .unwrap_or(Points::ZERO)
2203        .0;
2204    let axis = |d: Points, line: Points| {
2205        if height > 0.0 && line.0 > 0.0 {
2206            Points(d.0 * height / line.0)
2207        } else {
2208            d
2209        }
2210    };
2211    point(axis(delta.x, line.x), axis(delta.y, line.y))
2212}
2213
2214fn wheel_by(host: &impl ScrollHost, delta: Point<Points>, smooth: bool) {
2215    let (dx, dy) = (delta.x.0, delta.y.0);
2216    if !enabled(host) {
2217        return;
2218    }
2219    let (gesture, total, last) = match phase(host) {
2220        Phase::Wheel {
2221            gesture,
2222            total,
2223            raw,
2224            glide,
2225            ..
2226        } => (gesture, total, (!gesture).then_some((raw, glide))),
2227        _ => {
2228            interrupt(host);
2229            (false, 0.0, None)
2230        }
2231    };
2232    let smooth = smooth && !gesture;
2233    let now = host.now();
2234    let Some((pos, to, total)) = host.scroll(|s, size| {
2235        let (min, max) = s.range(size);
2236        let d = if s.zooms() {
2237            Offset::new(dx, dy)
2238        } else if !s.horizontal {
2239            Offset::new(0.0, dy)
2240        } else if dx != 0.0 {
2241            Offset::new(if s.mirrored { -dx } else { dx }, 0.0)
2242        } else {
2243            // Vertical wheels scroll horizontal views too.
2244            Offset::new(dy, 0.0)
2245        };
2246        let pos = s.pos();
2247        // A smooth wheel's notches add up from where the last one pointed,
2248        // not from where its glide has got to.
2249        let from = match last {
2250            Some((raw, _)) if smooth => raw,
2251            _ => pos,
2252        };
2253        // Past an edge (the refresh space) wheels only move back.
2254        let one =
2255            |p: f32, d: f32, min: f32, max: f32| (p + d).clamp(min.min(p), max.max(min).max(p));
2256        (
2257            pos,
2258            Offset::new(
2259                one(from.x, d.x, min.x, max.x),
2260                one(from.y, d.y, min.y, max.y),
2261            ),
2262            total + d.along(s.horizontal),
2263        )
2264    }) else {
2265        return;
2266    };
2267    let glide = match last {
2268        _ if !smooth => wheel_glide::Glide::default(),
2269        Some((raw, g)) if now < g.end() => g.retargeted(raw.into(), to.into(), now),
2270        _ => wheel_glide::Glide::new(pos.into(), to.into(), now),
2271    };
2272    set_phase(
2273        host,
2274        Phase::Wheel {
2275            last: now,
2276            total,
2277            gesture,
2278            raw: to,
2279            glide,
2280        },
2281    );
2282    if !smooth {
2283        moved_to(host, to);
2284    }
2285    ensure_ticking(host);
2286}
2287
2288/// The wheel scroll ended at a velocity of `(vx, vy)` points per second
2289/// (0 for wheels without momentum).
2290pub fn wheel_end(host: &impl ScrollHost, vx: f32, vy: f32) {
2291    end_wheel(host, vx, vy, true);
2292}
2293
2294/// The wheel scroll came to rest where it is, its momentum spent (Windows'
2295/// precision touchpads, whose system glide comes as more deltas before
2296/// the scroll ends): a snapping view settles on its nearest snap point,
2297/// as browsers' scroll snapping does, rather than moving on in the
2298/// scroll's direction as a mouse wheel's notches do.
2299pub fn wheel_settle(host: &impl ScrollHost) {
2300    end_wheel(host, 0.0, 0.0, false);
2301}
2302
2303fn end_wheel(host: &impl ScrollHost, vx: f32, vy: f32, onward: bool) {
2304    let Phase::Wheel { gesture, total, .. } = phase(host) else {
2305        return;
2306    };
2307    let Some(v) = host.scroll(|s, _| {
2308        let v = if s.zooms() {
2309            return Offset::new(vx / 1000.0, vy / 1000.0);
2310        } else if !s.horizontal {
2311            vy
2312        } else if vx != 0.0 {
2313            if s.mirrored { -vx } else { vx }
2314        } else {
2315            vy
2316        };
2317        Offset::default().with(s.horizontal, v / 1000.0)
2318    }) else {
2319        return;
2320    };
2321    set_phase(host, Phase::Idle);
2322    if gesture {
2323        emit(host, EventKind::ScrollDragEnd);
2324    }
2325    let snap = if onward && v == Offset::default() && total.abs() >= 1.0 {
2326        total.signum() * WHEEL_SNAP
2327    } else {
2328        0.0
2329    };
2330    release(host, v, snap);
2331}
2332
2333/// Duration of a mouse wheel notch's animated scroll (ms), as browsers and
2334/// Windows' own lists glide a notch; notches that follow retarget it.
2335const WHEEL_STEP_ANIMATION: f64 = 150.0;
2336
2337/// Scrolls the view by one notch of a mouse wheel, `delta` (positive
2338/// toward the end), animated: a notch while one runs adds to where it is
2339/// headed, so a spun wheel scrolls on smoothly. Views that snap, page or
2340/// zoom take it as [`wheel`] does (they settle on a snap point when the
2341/// notches stop), as does a view pulled past an edge.
2342pub fn wheel_step(host: &impl ScrollHost, delta: Point<Points>) {
2343    if !enabled(host) {
2344        return;
2345    }
2346    let Some(target) = host.scroll(|s, size| {
2347        if s.zooms() || s.behavior.snaps() || s.behavior.paging {
2348            return None;
2349        }
2350        let (min, max) = s.limits(size);
2351        let max = max.max(min);
2352        let (dx, dy) = (delta.x.0, delta.y.0);
2353        let d = if !s.horizontal {
2354            dy
2355        } else if dx != 0.0 {
2356            if s.mirrored { -dx } else { dx }
2357        } else {
2358            // Vertical wheels scroll horizontal views too.
2359            dy
2360        };
2361        let pos = s.offset();
2362        if pos < min - 0.5 || pos > max + 0.5 {
2363            return None;
2364        }
2365        Some((s.goal() + d).clamp(min, max))
2366    }) else {
2367        return;
2368    };
2369    let Some(to) = target else {
2370        wheel(host, delta);
2371        return;
2372    };
2373    if matches!(phase(host), Phase::Wheel { gesture: true, .. }) {
2374        // A touchpad's scroll is going on: it keeps the view.
2375        return;
2376    }
2377    let goal = host.scroll(|s, _| s.goal()).unwrap_or(to);
2378    if (to - goal).abs() < 0.5 {
2379        // Headed there already (at an edge): nothing changes.
2380        return;
2381    }
2382    interrupt(host);
2383    animate_along(host, to, WHEEL_STEP_ANIMATION, false, true);
2384}
2385
2386// The keyboard.
2387
2388/// Points an arrow key scrolls, as browsers do.
2389pub const KEY_LINE: Points = Points(40.0);
2390/// The share of the viewport a page key scrolls (the rest stays in view).
2391const KEY_PAGE: f32 = 0.875;
2392/// Duration of keyboard scrolls (ms); repeats retarget the running one.
2393const KEY_ANIMATION: f64 = 200.0;
2394
2395/// Where a scroll key moves along an axis.
2396#[derive(Debug, Clone, Copy, PartialEq)]
2397pub enum KeyMove {
2398    /// By this far (positive: towards the end).
2399    Points(Points),
2400    /// By this many viewports.
2401    Pages(f32),
2402    /// To the start.
2403    Start,
2404    /// To the end.
2405    End,
2406}
2407
2408impl KeyMove {
2409    /// The direction it moves in: 1 towards the end, -1 towards the start.
2410    pub fn sign(self) -> f32 {
2411        match self {
2412            KeyMove::Points(d) => d.0.signum(),
2413            KeyMove::Pages(n) => n.signum(),
2414            KeyMove::Start => -1.0,
2415            KeyMove::End => 1.0,
2416        }
2417    }
2418}
2419
2420/// What the key of Windows virtual key code `vk` scrolls (the codes the
2421/// Windows and GPUI backends' keys carry): whether along the horizontal
2422/// axis, and how. `ctrl` held leaves only Ctrl+Home / Ctrl+End, which go
2423/// to the edges as in browsers; other Ctrl combinations are shortcuts.
2424pub fn vk_key_move(vk: u16, shift: bool, ctrl: bool) -> Option<(bool, KeyMove)> {
2425    const VK_SPACE: u16 = 0x20;
2426    const VK_PRIOR: u16 = 0x21;
2427    const VK_NEXT: u16 = 0x22;
2428    const VK_END: u16 = 0x23;
2429    const VK_HOME: u16 = 0x24;
2430    const VK_LEFT: u16 = 0x25;
2431    const VK_UP: u16 = 0x26;
2432    const VK_RIGHT: u16 = 0x27;
2433    const VK_DOWN: u16 = 0x28;
2434    if ctrl {
2435        return match vk {
2436            VK_HOME => Some((false, KeyMove::Start)),
2437            VK_END => Some((false, KeyMove::End)),
2438            _ => None,
2439        };
2440    }
2441    Some(match vk {
2442        VK_UP => (false, KeyMove::Points(-KEY_LINE)),
2443        VK_DOWN => (false, KeyMove::Points(KEY_LINE)),
2444        VK_LEFT => (true, KeyMove::Points(-KEY_LINE)),
2445        VK_RIGHT => (true, KeyMove::Points(KEY_LINE)),
2446        VK_PRIOR => (false, KeyMove::Pages(-1.0)),
2447        VK_NEXT => (false, KeyMove::Pages(1.0)),
2448        VK_SPACE if shift => (false, KeyMove::Pages(-1.0)),
2449        VK_SPACE => (false, KeyMove::Pages(1.0)),
2450        VK_HOME => (false, KeyMove::Start),
2451        VK_END => (false, KeyMove::End),
2452        _ => return None,
2453    })
2454}
2455
2456/// The offset a key move from `base` aims at, within `[min, max]`.
2457fn key_target(m: KeyMove, base: f32, viewport: f32, min: f32, max: f32) -> f32 {
2458    let max = max.max(min);
2459    match m {
2460        KeyMove::Points(d) => base + d.0,
2461        KeyMove::Pages(n) => base + n * (viewport * KEY_PAGE).max(KEY_LINE.0),
2462        KeyMove::Start => min,
2463        KeyMove::End => max,
2464    }
2465    .clamp(min, max)
2466}
2467
2468/// Scrolls the view by the key move `m`, animated; a repeat continues
2469/// from where the running scroll goes. With `flip`, a move by points goes
2470/// the other way in a mirrored view (Left and Right follow what they show
2471/// in a right-to-left list). Tells the host the key's move once the
2472/// scroll started ([`ScrollHost::key_scrolled`]).
2473pub fn key_scroll(host: &impl ScrollHost, m: KeyMove, flip: bool) {
2474    let Some((base, viewport, min, max, flip)) = host.scroll(|s, size| {
2475        let (min, max) = s.limits(size);
2476        (s.goal(), s.viewport(size), min, max, flip && s.mirrored)
2477    }) else {
2478        return;
2479    };
2480    let moved = match m {
2481        KeyMove::Points(d) if flip => KeyMove::Points(-d),
2482        m => m,
2483    };
2484    let to = key_target(moved, base, viewport, min, max);
2485    interrupt(host);
2486    animate_along(host, to, KEY_ANIMATION, false, true);
2487    // A list follows its real end from here on (rows never rendered are
2488    // only estimated), and the other keys leave it. The key's own move,
2489    // as the backends with a key scroll of their own report it.
2490    host.key_scrolled(m);
2491}
2492
2493/// Room kept around a view scrolled into view.
2494const REVEAL_MARGIN: f32 = 16.0;
2495
2496/// How far a scroll view must move along an axis so that the span
2497/// `[start, end)` (viewport coordinates) shows in `[0, viewport)`, with
2498/// a margin; the start wins when the span does not fit.
2499pub fn reveal_delta(start: Points, end: Points, viewport: Points) -> Points {
2500    Points(reveal_by(start.0, end.0, viewport.0))
2501}
2502
2503/// [`reveal_delta`] for a view that gets the focus: a span taller than
2504/// the viewport that shows already stays where it is. It could only show
2505/// in part anyway, and moving it would move what the pointer is on (a web
2506/// view the height of its page, focused by a click near its end or by its
2507/// context menu).
2508pub fn reveal_focus_delta(start: Points, end: Points, viewport: Points) -> Points {
2509    Points(reveal_focus_by(start.0, end.0, viewport.0))
2510}
2511
2512fn reveal_by(start: f32, end: f32, viewport: f32) -> f32 {
2513    let margin = REVEAL_MARGIN.min(viewport / 4.0);
2514    if start < margin {
2515        start - margin
2516    } else if end > viewport - margin {
2517        (end - (viewport - margin)).min(start - margin)
2518    } else {
2519        0.0
2520    }
2521}
2522
2523fn reveal_focus_by(start: f32, end: f32, viewport: f32) -> f32 {
2524    if end - start > viewport && end > 0.0 && start < viewport {
2525        0.0
2526    } else {
2527        reveal_by(start, end, viewport)
2528    }
2529}
2530
2531/// Scrolls the view (animated) so that the span of `len` points at
2532/// `start` along its main axis (viewport coordinates, as measured now)
2533/// shows, as iOS and Android do for the focused field; how far it moves
2534/// (0 when it shows already). Backends call it on each scroll view around
2535/// the field, innermost first, less what the inner ones moved.
2536///
2537/// A view the user is holding (a content drag or a grabbed indicator)
2538/// stays where they put it: a reveal then would end their gesture, and
2539/// what they point at is in view anyway.
2540pub fn reveal(host: &impl ScrollHost, start: Points, len: Points) -> Points {
2541    if matches!(phase(host), Phase::Drag { .. } | Phase::Thumb { .. }) {
2542        return Points(0.0);
2543    }
2544    let (start, len) = (start.0, len.0);
2545    let Some((base, pos, dim, min, max)) = host.scroll(|s, size| {
2546        let (min, max) = s.limits(size);
2547        (s.goal(), s.offset(), s.viewport(size), min, max)
2548    }) else {
2549        return Points(0.0);
2550    };
2551    // Pending animations count from where they are headed.
2552    let start = start - (base - pos);
2553    let delta = reveal_focus_by(start, start + len, dim);
2554    let to = (base + delta).clamp(min, max.max(min));
2555    if (to - base).abs() < 0.5 {
2556        return Points(0.0);
2557    }
2558    interrupt(host);
2559    animate_along(host, to, ANIMATION, false, true);
2560    Points(to - base)
2561}
2562
2563#[cfg(test)]
2564mod tests {
2565    use super::*;
2566    use crate::EdgeInsets;
2567
2568    #[test]
2569    fn content_is_read_in_the_order_it_is_on_screen() {
2570        // Recycled cells: made for rows 0 to 3, rows 0 and 1 scrolled
2571        // away and their cells bound to rows 4 and 5.
2572        let cells = [(0, 160.0), (1, 200.0), (2, 80.0), (3, 120.0)];
2573        let mut vertical = cells;
2574        reading_order(Axis::Vertical, &mut vertical, |c| {
2575            point(Points(0.0), Points(c.1))
2576        });
2577        assert_eq!(vertical.map(|c| c.0), [2, 3, 0, 1]);
2578        // Two columns read row by row; a horizontal list column by column.
2579        let grid = [
2580            (0, (50.0, 0.0)),
2581            (1, (0.0, 40.0)),
2582            (2, (0.0, 0.0)),
2583            (3, (50.0, 40.0)),
2584        ];
2585        let at = |c: &(i32, (f32, f32))| point(Points(c.1.0), Points(c.1.1));
2586        let mut rows = grid;
2587        reading_order(Axis::Vertical, &mut rows, at);
2588        assert_eq!(rows.map(|c| c.0), [2, 0, 1, 3]);
2589        let mut columns = grid;
2590        reading_order(Axis::Horizontal, &mut columns, at);
2591        assert_eq!(columns.map(|c| c.0), [2, 1, 0, 3]);
2592    }
2593
2594    fn scroll_state(content: (f32, f32), horizontal: bool) -> ScrollState {
2595        ScrollState {
2596            content: sz(content.0, content.1),
2597            horizontal,
2598            ..Default::default()
2599        }
2600    }
2601
2602    fn sz(w: f32, h: f32) -> Size<Points> {
2603        crate::geometry::size(Points(w), Points(h))
2604    }
2605
2606    fn pt(x: f32, y: f32) -> Point<Points> {
2607        point(Points(x), Points(y))
2608    }
2609
2610    #[test]
2611    fn rubber_band_resists() {
2612        assert_eq!(drag_position(50.0, 0.0, 100.0, 400.0, true), 50.0);
2613        let over = drag_position(-100.0, 0.0, 100.0, 400.0, true);
2614        assert!(over < 0.0 && over > -100.0, "{over}");
2615        let more = drag_position(-400.0, 0.0, 100.0, 400.0, true);
2616        assert!(more < over && more > -400.0 * 0.55);
2617        assert_eq!(drag_position(-100.0, 0.0, 100.0, 400.0, false), 0.0);
2618        assert_eq!(drag_position(300.0, 0.0, 100.0, 400.0, false), 100.0);
2619        assert!(drag_position(150.0, 0.0, 100.0, 400.0, true) > 100.0);
2620        let p = Points;
2621        assert_eq!(dragged(p(50.0), p(0.0), p(100.0), p(400.0), true), p(50.0));
2622        // Never more than 55% of the viewport.
2623        assert!(rubber(1e6, 400.0) < 400.0);
2624    }
2625
2626    #[test]
2627    fn glide_integrates_to_projection() {
2628        let rate = 0.998;
2629        let (mut pos, mut v) = (0.0f32, 2.0f32);
2630        for _ in 0..2000 {
2631            let (d, nv) = glide_step(v, rate, 16.0);
2632            pos += d;
2633            v = nv;
2634        }
2635        let end = projected(Points(0.0), 2.0, rate).0;
2636        assert!((pos - end).abs() < 1.0, "{pos} vs {end}");
2637        // Frame rate does not change the path.
2638        let (a, _) = glide_step(2.0, rate, 32.0);
2639        let (b1, v1) = glide_step(2.0, rate, 16.0);
2640        let (b2, _) = glide_step(v1, rate, 16.0);
2641        assert!((a - (b1 + b2)).abs() < 1e-3);
2642    }
2643
2644    #[test]
2645    fn animated_sticky_offsets_stick_further_in() {
2646        let mut s = scroll_state((320.0, 2000.0), false);
2647        s.y = Points(150.0);
2648        s.sticky = vec![
2649            crate::StickyCell {
2650                cell: 1,
2651                start: Points(100.0),
2652                end: Points(300.0),
2653                offset: None,
2654            },
2655            crate::StickyCell {
2656                cell: 2,
2657                start: Points(100.0),
2658                end: Points(300.0),
2659                offset: Some(7),
2660            },
2661        ];
2662        // Below a 56 pt header: the second sticks 56 further in.
2663        let shifts: Vec<_> = s
2664            .sticky_shifts_with(|n| if n == 7 { 56.0 } else { 0.0 })
2665            .map(|(c, p)| (c, p.y.0))
2666            .collect();
2667        assert_eq!(shifts, [(1, 50.0), (2, 106.0)]);
2668    }
2669
2670    #[test]
2671    fn sticky_shift_clamps() {
2672        let p = Points;
2673        assert_eq!(sticky_shift(p(0.0), p(100.0), p(300.0)), p(0.0));
2674        assert_eq!(sticky_shift(p(150.0), p(100.0), p(300.0)), p(50.0));
2675        assert_eq!(sticky_shift(p(500.0), p(100.0), p(300.0)), p(200.0));
2676        assert_eq!(sticky_shift(p(500.0), p(100.0), p(f32::INFINITY)), p(400.0));
2677        // An end inset travels the other way: from the containing block's
2678        // start, to the normal place.
2679        assert_eq!(sticky_shift(p(0.0), p(300.0), p(100.0)), p(-200.0));
2680        assert_eq!(sticky_shift(p(150.0), p(300.0), p(100.0)), p(-150.0));
2681        assert_eq!(sticky_shift(p(300.0), p(300.0), p(100.0)), p(0.0));
2682        assert_eq!(sticky_shift(p(500.0), p(300.0), p(100.0)), p(0.0));
2683    }
2684
2685    #[test]
2686    fn rates_follow_behavior() {
2687        let mut b = ScrollBehavior::default();
2688        assert_eq!(rate(&b), 0.998);
2689        b.paging = true;
2690        assert_eq!(rate(&b), 0.99);
2691        b.deceleration = 0.95;
2692        assert_eq!(rate(&b), 0.95);
2693    }
2694
2695    #[test]
2696    fn snapping_and_paging_targets() {
2697        // Paging in a 400 point viewport over 1600 points of content: a
2698        // slow release past half a page moves on, a fling moves one page.
2699        let b = ScrollBehavior {
2700            paging: true,
2701            ..Default::default()
2702        };
2703        let r = rate(&b);
2704        let pt = Points;
2705        let t = b.snap_target(
2706            pt(250.0),
2707            projected(pt(250.0), 0.0, r),
2708            0.0,
2709            pt(400.0),
2710            pt(1600.0),
2711        );
2712        assert_eq!(t, Some(pt(400.0)));
2713        let t = b.snap_target(
2714            pt(100.0),
2715            projected(pt(100.0), 1.0, r),
2716            1.0,
2717            pt(400.0),
2718            pt(1600.0),
2719        );
2720        assert_eq!(t, Some(pt(400.0)));
2721        let t = b.snap_target(
2722            pt(300.0),
2723            projected(pt(300.0), -1.0, r),
2724            -1.0,
2725            pt(400.0),
2726            pt(1600.0),
2727        );
2728        assert_eq!(t, Some(pt(0.0)));
2729        let b = ScrollBehavior {
2730            snap_interval: pt(100.0),
2731            ..Default::default()
2732        };
2733        let t = b.snap_target(pt(140.0), pt(140.0), 0.0, pt(400.0), pt(1600.0));
2734        assert_eq!(t, Some(pt(100.0)));
2735        assert_eq!(
2736            ScrollBehavior::default().snap_target(pt(140.0), pt(140.0), 0.0, pt(400.0), pt(1600.0)),
2737            None
2738        );
2739    }
2740
2741    #[test]
2742    fn indicator_geometry() {
2743        assert_eq!(span(400.0, 400.0, 0.0, 0.0, 0.0), None);
2744        let (s0, l0) = span(400.0, 1600.0, 0.0, 0.0, 0.0).unwrap();
2745        assert_eq!(s0, 2.0);
2746        assert!((l0 - 99.0).abs() < 0.01);
2747        let (s1, l1) = span(400.0, 1600.0, 1200.0, 0.0, 0.0).unwrap();
2748        assert!((s1 + l1 - 398.0).abs() < 0.01);
2749        let (_, l2) = span(400.0, 1600.0, -50.0, 0.0, 0.0).unwrap();
2750        assert!(l2 < l0);
2751        assert_eq!(
2752            indicator_span(Points(400.0), Points(1600.0), Points(0.0)),
2753            Some((Points(s0), Points(l0)))
2754        );
2755        assert_eq!(indicator_alpha(0.0), 1.0);
2756        assert_eq!(indicator_alpha(INDICATOR_HOLD + INDICATOR_FADE), 0.0);
2757    }
2758
2759    #[test]
2760    fn snap_durations() {
2761        let p = Points;
2762        assert_eq!(snap_duration(p(0.2), 1.0), 0.0);
2763        assert_eq!(snap_duration(p(100.0), -1.0), ANIMATION);
2764        assert_eq!(snap_duration(p(300.0), 1.0), 600.0);
2765        assert_eq!(snap_duration(p(300.0), 3.0), 300.0);
2766        assert_eq!(ease_out(1.0), 1.0);
2767        assert_eq!(ease_out(2.0), 1.0);
2768    }
2769
2770    #[test]
2771    fn insets_clamp_and_report() {
2772        let mut s = scroll_state((300.0, 1000.0), false);
2773        let size = sz(300.0, 400.0);
2774        s.behavior.content_inset = EdgeInsets {
2775            top: Points(50.0),
2776            bottom: Points(20.0),
2777            ..Default::default()
2778        };
2779        assert_eq!(s.limits(size), (0.0, 670.0));
2780        assert_eq!(s.max(size), pt(0.0, 670.0));
2781        // The offset 0 shows the top inset: UIKit's contentOffset is -50.
2782        assert_eq!(s.reported(size), pt(0.0, -50.0));
2783        s.y = Points(900.0);
2784        assert_eq!(s.reported(size), pt(0.0, 620.0));
2785        // Children are drawn up by the offset, down by the inset.
2786        assert_eq!(s.origin(), pt(0.0, 850.0));
2787        // Refreshing lowers the top limit.
2788        s.live.refreshing = true;
2789        assert_eq!(s.limits(size).0, -56.0);
2790        s.behavior.refresh_indicator = Some(Points(80.0));
2791        assert_eq!(s.limits(size).0, -80.0);
2792    }
2793
2794    #[test]
2795    fn can_scroll_follows_edges_and_mirroring() {
2796        let size = sz(300.0, 400.0);
2797        let mut s = scroll_state((300.0, 1000.0), false);
2798        s.behavior.enabled = true;
2799        assert!(s.can_scroll(size, pt(0.0, 10.0)));
2800        assert!(!s.can_scroll(size, pt(0.0, -10.0)));
2801        s.y = Points(600.0);
2802        assert!(!s.can_scroll(size, pt(0.0, 10.0)));
2803        s.behavior.enabled = false;
2804        assert!(!s.can_scroll(size, pt(0.0, -10.0)));
2805
2806        let size = sz(300.0, 100.0);
2807        let mut row = scroll_state((1000.0, 100.0), true);
2808        row.behavior.enabled = true;
2809        row.mirrored = true;
2810        // Right to left: content past the start is on the left.
2811        assert!(row.can_scroll(size, pt(-10.0, 0.0)));
2812        assert!(!row.can_scroll(size, pt(10.0, 0.0)));
2813        // Vertical wheels move horizontal lists, unmirrored.
2814        assert!(row.can_scroll(size, pt(0.0, 10.0)));
2815    }
2816
2817    #[test]
2818    fn scroll_by_moves_gestures_along() {
2819        let y = |v: f32| Offset::new(0.0, v);
2820        let drag = shifted(
2821            Phase::Drag {
2822                start: y(10.0),
2823                moved: y(5.0),
2824            },
2825            y(30.0),
2826            false,
2827        );
2828        assert_eq!(
2829            drag,
2830            Phase::Drag {
2831                start: y(40.0),
2832                moved: y(5.0)
2833            }
2834        );
2835        let anim = Phase::Animate {
2836            from: y(0.0),
2837            to: y(100.0),
2838            start: 1.0,
2839            duration: 300.0,
2840            momentum: false,
2841            end: true,
2842        };
2843        let Phase::Animate { from, to, .. } = shifted(anim, y(-20.0), false) else {
2844            panic!()
2845        };
2846        assert_eq!((from, to), (y(-20.0), y(80.0)));
2847        assert_eq!(shifted(Phase::Idle, y(5.0), false), Phase::Idle);
2848        assert_eq!(
2849            shifted(Phase::Thumb { start: 10.0 }, y(30.0), false),
2850            Phase::Thumb { start: 40.0 }
2851        );
2852    }
2853
2854    #[test]
2855    fn thumb_follows_the_pointer() {
2856        // The thumb's travel spans the scroll range: moving it by its
2857        // whole travel scrolls to the end, and it ends that far along.
2858        let p = Points;
2859        let (s0, l0) = span(400.0, 1600.0, 0.0, 0.0, 0.0).unwrap();
2860        let travel = 400.0 - 2.0 * INDICATOR_MARGIN - l0;
2861        let end = thumb_scroll(p(travel), p(1200.0), p(travel)).0;
2862        assert!((end - 1200.0).abs() < 0.01);
2863        let (s1, _) = span(400.0, 1600.0, end, 0.0, 0.0).unwrap();
2864        assert!((s1 - s0 - travel).abs() < 0.01);
2865        assert!(thumb_scroll(p(-10.0), p(1200.0), p(travel)).0 < 0.0);
2866        assert_eq!(thumb_scroll(p(10.0), p(1200.0), p(0.0)), p(0.0));
2867    }
2868
2869    #[test]
2870    fn thumb_is_grabbed_at_the_edge() {
2871        let mut s = scroll_state((300.0, 1600.0), false);
2872        s.indicator = true;
2873        s.behavior.enabled = true;
2874        let size = sz(300.0, 400.0);
2875        let (rect, _) = s.thumb(size).unwrap();
2876        assert_eq!(rect.origin.x.0, 300.0 - INDICATOR_THICK.0 - 2.0);
2877        assert!(s.grabs_thumb(size, pt(295.0, 10.0)));
2878        assert!(!s.grabs_thumb(size, pt(200.0, 10.0)));
2879        assert!(!s.grabs_thumb(size, pt(295.0, 300.0)));
2880    }
2881
2882    #[test]
2883    fn thumb_keeps_clear_of_the_scrollbar_inset() {
2884        // A list under a 100-point bar floating at its bottom and a 50-point
2885        // one at its top: the thumb runs between them, as far as before.
2886        let (s0, l0) = span(400.0, 1600.0, 0.0, 50.0, 100.0).unwrap();
2887        assert_eq!(s0, 50.0 + INDICATOR_MARGIN);
2888        let (s1, l1) = span(400.0, 1600.0, 1200.0, 50.0, 100.0).unwrap();
2889        assert!((s1 + l1 - (300.0 - INDICATOR_MARGIN)).abs() < 0.01);
2890        // Its length is the shorter track's share of what shows.
2891        let (_, full) = span(400.0, 1600.0, 0.0, 0.0, 0.0).unwrap();
2892        assert!(l0 < full && (l0 - 246.0 / 4.0).abs() < 0.01, "{l0}");
2893        // No room left between the insets: no indicator.
2894        assert_eq!(span(400.0, 1600.0, 0.0, 200.0, 195.0), None);
2895        // Negative insets count as none.
2896        assert_eq!(
2897            span(400.0, 1600.0, 0.0, -10.0, 0.0),
2898            span(400.0, 1600.0, 0.0, 0.0, 0.0)
2899        );
2900        assert_eq!(
2901            indicator_span_within(
2902                Points(400.0),
2903                Points(1600.0),
2904                Points(0.0),
2905                Points(50.0),
2906                Points(100.0)
2907            ),
2908            Some((Points(s0), Points(l0)))
2909        );
2910
2911        // In a view: the thumb, its travel and where a press grabs it.
2912        let mut s = scroll_state((300.0, 1600.0), false);
2913        s.indicator = true;
2914        s.behavior.enabled = true;
2915        s.behavior.scrollbar_inset = EdgeInsets {
2916            top: Points(50.0),
2917            right: Points(8.0),
2918            bottom: Points(100.0),
2919            left: Points::ZERO,
2920        };
2921        let size = sz(300.0, 400.0);
2922        let (rect, travel) = s.thumb(size).unwrap();
2923        assert_eq!(rect.origin.x.0, 300.0 - 8.0 - INDICATOR_THICK.0 - 2.0);
2924        assert_eq!(rect.origin.y.0, s0);
2925        assert!((travel.0 - (400.0 - 150.0 - 2.0 * INDICATOR_MARGIN - l0)).abs() < 0.01);
2926        assert!(s.grabs_thumb(size, pt(287.0, 60.0)));
2927        assert!(!s.grabs_thumb(size, pt(295.0, 60.0)), "past its edge");
2928        assert!(!s.grabs_thumb(size, pt(287.0, 20.0)), "above its track");
2929
2930        // A horizontal one moves up by the bottom inset and runs between
2931        // the left and right ones, from the right when mirrored.
2932        let mut s = scroll_state((900.0, 2000.0), true);
2933        s.behavior.scrollbar_inset = EdgeInsets {
2934            top: Points::ZERO,
2935            right: Points(30.0),
2936            bottom: Points(20.0),
2937            left: Points(10.0),
2938        };
2939        let size = sz(300.0, 400.0);
2940        let (rect, _) = s.thumb(size).unwrap();
2941        assert_eq!(rect.origin.y.0, 400.0 - 20.0 - INDICATOR_THICK.0 - 2.0);
2942        assert_eq!(rect.origin.x.0, 10.0 + INDICATOR_MARGIN);
2943        s.mirrored = true;
2944        let (rect, _) = s.thumb(size).unwrap();
2945        assert_eq!(
2946            rect.origin.x.0 + rect.size.width.0,
2947            300.0 - 30.0 - INDICATOR_MARGIN
2948        );
2949    }
2950
2951    #[test]
2952    fn thumb_stays_in_the_visible_part() {
2953        // A horizontal scroll view 2000 tall in a viewport showing its rows
2954        // 600 to 1000: the bar runs along the visible part's bottom, where
2955        // a press grabs it, not along the view's own.
2956        let mut s = scroll_state((900.0, 2000.0), true);
2957        s.indicator = true;
2958        s.behavior.enabled = true;
2959        let size = sz(300.0, 2000.0);
2960        let visible = Bounds::new(pt(0.0, 600.0), sz(300.0, 400.0));
2961        let (rect, _) = s.thumb_within(size, visible).unwrap();
2962        assert_eq!(rect.origin.y.0, 1000.0 - INDICATOR_THICK.0 - 2.0);
2963        assert!(s.grabs_thumb_within(size, visible, pt(20.0, 997.0)));
2964        assert!(!s.grabs_thumb_within(size, visible, pt(20.0, 1997.0)));
2965        // Unclipped, it is the view's own bottom.
2966        let (rect, _) = s.thumb(size).unwrap();
2967        assert_eq!(rect.origin.y.0, 2000.0 - INDICATOR_THICK.0 - 2.0);
2968        // Out of sight: no bar.
2969        let hidden = Bounds::new(pt(0.0, 2100.0), sz(300.0, 400.0));
2970        assert!(s.thumb_within(size, hidden).is_none());
2971    }
2972
2973    #[test]
2974    fn scroll_keys() {
2975        assert_eq!(
2976            vk_key_move(0x28, false, false),
2977            Some((false, KeyMove::Points(KEY_LINE)))
2978        );
2979        assert_eq!(
2980            vk_key_move(0x25, false, false),
2981            Some((true, KeyMove::Points(-KEY_LINE)))
2982        );
2983        assert_eq!(
2984            vk_key_move(0x20, true, false),
2985            Some((false, KeyMove::Pages(-1.0)))
2986        );
2987        assert_eq!(
2988            vk_key_move(0x24, false, true),
2989            Some((false, KeyMove::Start))
2990        );
2991        assert_eq!(vk_key_move(0x28, false, true), None);
2992        assert_eq!(vk_key_move(b'A' as u16, false, false), None);
2993        assert_eq!(KeyMove::Start.sign(), -1.0);
2994        assert_eq!(KeyMove::Pages(1.0).sign(), 1.0);
2995        assert_eq!(
2996            key_target(KeyMove::Points(Points(40.0)), 10.0, 400.0, 0.0, 1000.0),
2997            50.0
2998        );
2999        assert_eq!(
3000            key_target(KeyMove::Pages(1.0), 0.0, 400.0, 0.0, 1000.0),
3001            350.0
3002        );
3003        assert_eq!(
3004            key_target(KeyMove::Pages(-1.0), 100.0, 400.0, 0.0, 1000.0),
3005            0.0
3006        );
3007        assert_eq!(key_target(KeyMove::End, 0.0, 400.0, 0.0, 1000.0), 1000.0);
3008        assert_eq!(
3009            key_target(KeyMove::Start, 500.0, 400.0, -56.0, 1000.0),
3010            -56.0
3011        );
3012    }
3013
3014    #[test]
3015    fn reveal_deltas() {
3016        assert_eq!(reveal_by(100.0, 140.0, 400.0), 0.0);
3017        assert_eq!(reveal_by(-30.0, 10.0, 400.0), -46.0);
3018        assert_eq!(reveal_by(380.0, 420.0, 400.0), 36.0);
3019        // Taller than the viewport: its start shows.
3020        assert_eq!(reveal_by(200.0, 900.0, 400.0), 184.0);
3021        // A focused one stays when some of it shows already; out of view,
3022        // its start shows.
3023        assert_eq!(reveal_focus_by(500.0, 1200.0, 400.0), 484.0);
3024        assert_eq!(reveal_focus_by(-1200.0, -500.0, 400.0), -1216.0);
3025        assert_eq!(reveal_focus_by(200.0, 900.0, 400.0), 0.0);
3026        assert_eq!(reveal_focus_by(-2000.0, 300.0, 400.0), 0.0);
3027        assert_eq!(reveal_focus_by(-2000.0, 900.0, 400.0), 0.0);
3028        // One that fits the viewport, but not with both margins, still
3029        // shows whole.
3030        assert_eq!(reveal_focus_by(-100.0, 290.0, 400.0), -116.0);
3031        assert_eq!(
3032            reveal_focus_delta(Points(200.0), Points(900.0), Points(400.0)),
3033            Points(0.0)
3034        );
3035        assert_eq!(
3036            reveal_delta(Points(-30.0), Points(10.0), Points(400.0)),
3037            Points(-46.0)
3038        );
3039    }
3040
3041    #[test]
3042    fn spinner_spokes() {
3043        assert_eq!(spokes(Percentage(0.3), Radians(0.0)).count(), 3);
3044        assert!(spokes(Percentage(0.3), Radians(0.0)).all(|(_, a)| a == 0.8));
3045        let all: Vec<_> = spokes(Percentage(1.0), Radians(0.0)).collect();
3046        assert_eq!(all.len(), 8);
3047        // The leading spoke is the brightest.
3048        assert_eq!(all[0].1, 1.0);
3049        assert_eq!(all[1].0, Radians(PI / 4.0));
3050    }
3051
3052    #[test]
3053    fn refresh_follows_its_props() {
3054        let mut s = scroll_state((300.0, 1000.0), false);
3055        assert!(!s.behavior.refreshes(Points(-63.0)));
3056        assert!(s.behavior.refreshes(Points(-64.0)));
3057        // Pulled 32 of 64: half the spokes, centered in the 56 kept.
3058        s.y = Points(-32.0);
3059        assert_eq!(
3060            s.spinner(Points(300.0), true),
3061            Some((pt(150.0, 4.0), Percentage(0.5)))
3062        );
3063        // The app's own indicator, 100 tall: no spinner, a pull refreshes
3064        // at its height, which refreshing keeps.
3065        s.behavior.refresh_indicator = Some(Points(100.0));
3066        assert!(!s.behavior.refreshes(Points(-64.0)));
3067        assert!(s.behavior.refreshes(Points(-100.0)));
3068        assert_eq!(s.behavior.refresh_inset(), Points(100.0));
3069        assert_eq!(s.spinner(Points(300.0), true), None);
3070    }
3071
3072    #[test]
3073    fn refresh_dismissal_keeps_spinning_and_large_clocks_stay_precise() {
3074        let host = TestHost::new(scroll_state((300.0, 1000.0), false));
3075        refreshing(&host, true);
3076        // Complete the reveal to -56 and spin one spoke step on a monotonic clock.
3077        assert!(host.tick(ANIMATION));
3078        assert_eq!(host.state.borrow().y, Points(-56.0));
3079        assert!(host.tick(ANIMATION + 125.0));
3080        let before = host.state.borrow().live.spin;
3081        assert!((before.0 - PI / 4.0).abs() < 1e-5, "{before:?}");
3082
3083        // Ending refresh while pulled enters dismissing: keeps full spinning
3084        // progress instead of snapping to 56/64 = 0.875, even without onRefresh.
3085        refreshing(&host, false);
3086        assert_eq!(
3087            host.state
3088                .borrow()
3089                .spinner(Points(300.0), true)
3090                .map(|s| s.1),
3091            Some(Percentage(1.0))
3092        );
3093        assert_eq!(
3094            host.state
3095                .borrow()
3096                .spinner(Points(300.0), false)
3097                .map(|s| s.1),
3098            Some(Percentage(1.0))
3099        );
3100        assert_eq!(host.state.borrow().spinner_opacity(), 1.0);
3101
3102        // Mid-retraction on the same monotonic clock: keeps full progress,
3103        // fades opacity with the remaining pull, and advances spin continuously
3104        // from `before` without resetting `spin_start`.
3105        assert!(host.tick(ANIMATION + 125.0 + 150.0));
3106        let mid_y = host.state.borrow().y.0;
3107        assert!(mid_y < 0.0 && mid_y > -56.0, "{mid_y}");
3108        assert_eq!(
3109            host.state
3110                .borrow()
3111                .spinner(Points(300.0), true)
3112                .map(|s| s.1),
3113            Some(Percentage(1.0))
3114        );
3115        let mid_opacity = host.state.borrow().spinner_opacity();
3116        assert!(
3117            (mid_opacity - (-mid_y / 56.0)).abs() < 1e-5 && mid_opacity > 0.0 && mid_opacity < 1.0,
3118            "{mid_opacity}"
3119        );
3120        let mid_spin = host.state.borrow().live.spin;
3121        assert!(
3122            mid_spin.0 > before.0 && (mid_spin.0 - spin_angle(275.0).0).abs() < 1e-5,
3123            "before={before:?} mid={mid_spin:?}"
3124        );
3125
3126        // Settled back at 0: spinner hides, dismissing clears, and a fresh
3127        // pull uses pull progress again.
3128        host.tick(ANIMATION + 125.0 + ANIMATION);
3129        assert_eq!(host.state.borrow().y, Points(0.0));
3130        assert_eq!(host.state.borrow().spinner(Points(300.0), true), None);
3131        assert_eq!(host.state.borrow().spinner_opacity(), 1.0);
3132        assert!(!host.tick(ANIMATION + 125.0 + ANIMATION + 16.0));
3133        host.state.borrow_mut().y = Points(-32.0);
3134        assert_eq!(
3135            host.state
3136                .borrow()
3137                .spinner(Points(300.0), true)
3138                .map(|s| s.1),
3139            Some(Percentage(0.5))
3140        );
3141        assert_eq!(host.state.borrow().spinner_opacity(), 1.0);
3142
3143        // With `contentInset.top = 48`, the spinner center stays well inside
3144        // the viewport up to the final frame and fades smoothly to 0 instead of
3145        // popping out at full opacity.
3146        let mut inset_state = scroll_state((300.0, 1000.0), false);
3147        inset_state.behavior.content_inset.top = Points(48.0);
3148        let host = TestHost::new(inset_state);
3149        refreshing(&host, true);
3150        assert!(host.tick(ANIMATION));
3151        assert_eq!(
3152            host.state
3153                .borrow()
3154                .spinner(Points(300.0), true)
3155                .map(|(c, p)| (c.y.0, p)),
3156            Some((76.0, Percentage(1.0)))
3157        );
3158        refreshing(&host, false);
3159        assert!(host.tick(ANIMATION + 250.0));
3160        let (center, progress) = host.state.borrow().spinner(Points(300.0), true).unwrap();
3161        let near_end_opacity = host.state.borrow().spinner_opacity();
3162        assert!(center.y.0 > 20.0, "center stays in viewport: {center:?}");
3163        assert_eq!(progress, Percentage(1.0));
3164        assert!(
3165            near_end_opacity > 0.0 && near_end_opacity < 0.1,
3166            "{near_end_opacity}"
3167        );
3168        host.tick(ANIMATION + ANIMATION);
3169        assert_eq!(host.state.borrow().spinner(Points(300.0), true), None);
3170
3171        // Wheel input interrupting dismissal retracts cleanly after WHEEL_IDLE
3172        // instead of stranding at -46pt and spinning forever.
3173        let host = TestHost::new(scroll_state((300.0, 1000.0), false));
3174        refreshing(&host, true);
3175        assert!(host.tick(ANIMATION));
3176        refreshing(&host, false);
3177        wheel(&host, pt(0.0, 10.0));
3178        assert_eq!(host.state.borrow().y, Points(-46.0));
3179        let settled_wheel = ANIMATION + WHEEL_IDLE + 1.0;
3180        assert!(host.tick(settled_wheel));
3181        assert!(matches!(
3182            host.state.borrow().live.phase,
3183            Phase::Animate { to, .. } if to.y == 0.0
3184        ));
3185        assert!(host.tick(settled_wheel + 150.0));
3186        let bounce_y = host.state.borrow().y.0;
3187        assert!(bounce_y < 0.0 && bounce_y > -46.0, "{bounce_y}");
3188        host.tick(settled_wheel + ANIMATION);
3189        assert_eq!(host.state.borrow().y, Points(0.0));
3190        assert_eq!(host.state.borrow().spinner(Points(300.0), true), None);
3191        assert!(!host.tick(10_000.0));
3192
3193        // Sub-half-point offset left by an interrupting wheel also snaps back
3194        // to 0 and stops frame callbacks.
3195        let host = TestHost::new(scroll_state((300.0, 1000.0), false));
3196        refreshing(&host, true);
3197        assert!(host.tick(ANIMATION));
3198        refreshing(&host, false);
3199        wheel(&host, pt(0.0, 55.7));
3200        assert!((host.state.borrow().y.0 - -0.3).abs() < 1e-4);
3201        assert!(!host.tick(ANIMATION + WHEEL_IDLE + 1.0));
3202        assert_eq!(host.state.borrow().y, Points(0.0));
3203        assert_eq!(host.state.borrow().spinner(Points(300.0), true), None);
3204
3205        // A new drag or detach during dismissal clears `dismissing`.
3206        let host = TestHost::new(scroll_state((300.0, 1000.0), false));
3207        refreshing(&host, true);
3208        assert!(host.tick(ANIMATION));
3209        refreshing(&host, false);
3210        drag_begin(&host);
3211        assert_eq!(host.state.borrow().spinner_opacity(), 1.0);
3212        assert_eq!(
3213            host.state
3214                .borrow()
3215                .spinner(Points(300.0), true)
3216                .map(|s| s.1),
3217            Some(Percentage(56.0 / 64.0))
3218        );
3219        drag_end(&host, 0.0, 0.0);
3220        host.tick(ANIMATION + ANIMATION);
3221        assert_eq!(host.state.borrow().y, Points(0.0));
3222
3223        let host = TestHost::new(scroll_state((300.0, 1000.0), false));
3224        refreshing(&host, true);
3225        assert!(host.tick(ANIMATION));
3226        refreshing(&host, false);
3227        detached(&host);
3228        assert!(!host.state.borrow().live.dismissing);
3229
3230        // A monotonic clock past 115 days (where `f32` seconds lose sub-second
3231        // precision) still advances through all 8 spokes evenly.
3232        let mut s = scroll_state((300.0, 1000.0), false);
3233        s.y = Points(-56.0);
3234        s.live.refreshing = true;
3235        let host = TestHost::new(s);
3236        let base = 10_000_000_000.0;
3237        for step in 0..8 {
3238            assert!(host.tick(base + step as f64 * 125.0));
3239            let spin = host.state.borrow().live.spin;
3240            let brightest = spokes(Percentage(1.0), spin)
3241                .enumerate()
3242                .max_by(|a, b| a.1.1.total_cmp(&b.1.1))
3243                .map(|(i, _)| i);
3244            assert_eq!(brightest, Some(step));
3245        }
3246    }
3247
3248    /// A vertical view 500 tall the tests drive by hand: the clock starts
3249    /// at 0 and advances when [`TestHost::tick`] runs a frame.
3250    struct TestHost {
3251        state: std::cell::RefCell<ScrollState>,
3252        clock: std::cell::Cell<f64>,
3253        attached: std::cell::Cell<bool>,
3254        fail_wake: std::cell::Cell<bool>,
3255        redraws: std::cell::Cell<u32>,
3256        ticks_started: std::cell::Cell<u32>,
3257        /// Delays asked of [`ScrollHost::wake_after`], in order.
3258        wakes: std::cell::RefCell<Vec<u64>>,
3259        /// What it reported, in order: `zoom <scale>` and `scroll <x> <y>`.
3260        reports: std::cell::RefCell<Vec<String>>,
3261        /// The key moves it was told of, in order.
3262        key_moves: std::cell::RefCell<Vec<KeyMove>>,
3263        events: std::cell::RefCell<Vec<EventKind>>,
3264    }
3265
3266    impl TestHost {
3267        fn new(state: ScrollState) -> Self {
3268            Self {
3269                state: std::cell::RefCell::new(state),
3270                clock: std::cell::Cell::new(0.0),
3271                attached: std::cell::Cell::new(true),
3272                fail_wake: std::cell::Cell::new(false),
3273                redraws: std::cell::Cell::new(0),
3274                ticks_started: std::cell::Cell::new(0),
3275                wakes: Default::default(),
3276                reports: Default::default(),
3277                key_moves: Default::default(),
3278                events: Default::default(),
3279            }
3280        }
3281
3282        fn tick(&self, now: f64) -> bool {
3283            self.clock.set(now);
3284            frame(self, now)
3285        }
3286    }
3287
3288    impl ScrollHost for TestHost {
3289        fn scroll<R>(&self, f: impl FnOnce(&ScrollState, Size<Points>) -> R) -> Option<R> {
3290            Some(f(&self.state.borrow(), sz(300.0, 500.0)))
3291        }
3292        fn scroll_mut<R>(&self, f: impl FnOnce(&mut ScrollState, Size<Points>) -> R) -> Option<R> {
3293            Some(f(&mut self.state.borrow_mut(), sz(300.0, 500.0)))
3294        }
3295        fn now(&self) -> f64 {
3296            self.clock.get()
3297        }
3298        fn listens(&self, _: EventKind) -> bool {
3299            true
3300        }
3301        fn event(&self, kind: EventKind, _: EventPayload) {
3302            self.events.borrow_mut().push(kind);
3303        }
3304        fn report(&self, offset: Point<Points>, _: u32) {
3305            let line = format!("scroll {} {}", offset.x.0, offset.y.0);
3306            self.reports.borrow_mut().push(line);
3307        }
3308        fn report_zoom(&self, scale: f32) {
3309            self.reports.borrow_mut().push(format!("zoom {scale}"));
3310        }
3311        fn key_scrolled(&self, key_move: KeyMove) {
3312            self.key_moves.borrow_mut().push(key_move);
3313        }
3314        fn moved(&self, _: Point<Points>) {}
3315        fn pulled(&self, _: Points) {}
3316        fn relayout(&self) {}
3317        fn redraw(&self) {
3318            self.redraws.set(self.redraws.get() + 1);
3319        }
3320        fn attached(&self) -> bool {
3321            self.attached.get()
3322        }
3323        fn start_ticking(&self) {
3324            self.ticks_started.set(self.ticks_started.get() + 1);
3325        }
3326        fn wake_after(&self, ms: u64) -> bool {
3327            if self.fail_wake.get() {
3328                return false;
3329            }
3330            self.wakes.borrow_mut().push(ms);
3331            true
3332        }
3333    }
3334
3335    #[test]
3336    fn indicator_hold_pauses_the_frame_clock_until_fade() {
3337        let mut s = scroll_state((300.0, 2000.0), false);
3338        s.indicator = true;
3339        let host = TestHost::new(s);
3340        scroll_by(&host, pt(0.0, 100.0));
3341        assert_eq!(host.ticks_started.get(), 1);
3342        assert_eq!(host.state.borrow().live.alpha, 1.0);
3343
3344        // On the first idle frame during the hold, the frame callback stops
3345        // and schedules one wake-up for the remaining hold duration.
3346        assert!(!host.tick(100.0));
3347        assert_eq!(*host.wakes.borrow(), [(INDICATOR_HOLD - 100.0) as u64]);
3348
3349        // Another scroll while the wake-up is already armed restarts ticking
3350        // without scheduling a duplicate wake-up when it pauses again.
3351        host.clock.set(300.0);
3352        scroll_by(&host, pt(0.0, 50.0));
3353        assert_eq!(host.ticks_started.get(), 2);
3354        assert!(!host.tick(300.0));
3355        assert_eq!(*host.wakes.borrow(), [(INDICATOR_HOLD - 100.0) as u64]);
3356
3357        // When the original wake-up fires before the refreshed hold expires,
3358        // it re-arms directly for the remaining hold without waking a frame.
3359        host.clock.set(INDICATOR_HOLD);
3360        hold_ended(&host);
3361        assert_eq!(host.ticks_started.get(), 2);
3362        assert_eq!(*host.wakes.borrow(), [(INDICATOR_HOLD - 100.0) as u64, 300]);
3363
3364        // Once the hold has elapsed, hold_ended resumes ticking for the fade
3365        // until alpha reaches 0.
3366        host.clock.set(300.0 + INDICATOR_HOLD);
3367        hold_ended(&host);
3368        assert_eq!(host.ticks_started.get(), 3);
3369        assert!(host.tick(300.0 + INDICATOR_HOLD + INDICATOR_FADE / 2.0));
3370        assert!(host.state.borrow().live.alpha > 0.0 && host.state.borrow().live.alpha < 1.0);
3371        assert!(!host.tick(300.0 + INDICATOR_HOLD + INDICATOR_FADE));
3372        assert_eq!(host.state.borrow().live.alpha, 0.0);
3373    }
3374
3375    #[test]
3376    fn failed_wake_timer_keeps_ticking_and_does_not_wedge_future_holds() {
3377        let mut s = scroll_state((300.0, 2000.0), false);
3378        s.indicator = true;
3379        let host = TestHost::new(s);
3380        host.fail_wake.set(true);
3381        scroll_by(&host, pt(0.0, 100.0));
3382
3383        // When timer creation fails, frame() stays on the frame callback path
3384        // instead of dropping ticking with hold_timer stuck true.
3385        assert!(host.tick(100.0));
3386        assert!(host.wakes.borrow().is_empty());
3387        assert!(host.tick(INDICATOR_HOLD + INDICATOR_FADE / 2.0));
3388        assert!(!host.tick(INDICATOR_HOLD + INDICATOR_FADE));
3389        assert_eq!(host.state.borrow().live.alpha, 0.0);
3390
3391        // Once timer scheduling works again, a subsequent scroll pauses normally.
3392        host.fail_wake.set(false);
3393        host.clock.set(2000.0);
3394        scroll_by(&host, pt(0.0, 100.0));
3395        assert!(!host.tick(2000.0));
3396        assert_eq!(*host.wakes.borrow(), [INDICATOR_HOLD as u64]);
3397    }
3398
3399    #[test]
3400    fn hold_timer_uses_current_clock_when_frame_timestamp_lags_shown() {
3401        let mut s = scroll_state((300.0, 2000.0), false);
3402        s.indicator = true;
3403        let host = TestHost::new(s);
3404        host.clock.set(200.0);
3405        scroll_by(&host, pt(0.0, 100.0));
3406        // Even if the frame callback carries an earlier timestamp (100 ms),
3407        // the timer delay is measured from host.now() (200 ms), not 100 ms.
3408        assert!(!frame(&host, 100.0));
3409        assert_eq!(*host.wakes.borrow(), [INDICATOR_HOLD as u64]);
3410    }
3411
3412    #[test]
3413    fn hold_ended_clears_indicator_when_detached_and_skips_tick_when_hidden() {
3414        let mut s = scroll_state((300.0, 2000.0), false);
3415        s.indicator = true;
3416        let host = TestHost::new(s);
3417        scroll_by(&host, pt(0.0, 100.0));
3418        assert_eq!(host.state.borrow().live.alpha, 1.0);
3419        assert!(!host.tick(0.0));
3420        let starts = host.ticks_started.get();
3421        host.attached.set(false);
3422        hold_ended(&host);
3423        assert_eq!(host.state.borrow().live.alpha, 0.0);
3424        assert_eq!(host.ticks_started.get(), starts);
3425
3426        // If indicators were turned off before the timer fired, hold_ended
3427        // does not wake the frame clock unnecessarily.
3428        let mut s = scroll_state((300.0, 2000.0), false);
3429        s.indicator = true;
3430        let host = TestHost::new(s);
3431        scroll_by(&host, pt(0.0, 100.0));
3432        assert_eq!(host.state.borrow().live.alpha, 1.0);
3433        assert!(!host.tick(0.0));
3434        let starts = host.ticks_started.get();
3435        config(&host, false, false, false, false);
3436        assert_eq!(host.state.borrow().live.alpha, 0.0);
3437        hold_ended(&host);
3438        assert_eq!(host.ticks_started.get(), starts);
3439    }
3440
3441    #[test]
3442    fn a_reveal_leaves_a_grabbed_indicator_alone() {
3443        // nsh#3976: pointing at a menu row beside the thumb focuses it;
3444        // its reveal must not end the thumb drag.
3445        let host = TestHost::new(scroll_state((300.0, 10_000.0), false));
3446        thumb_begin(&host);
3447        assert_eq!(reveal(&host, Points(490.0), Points(32.0)), Points(0.0));
3448        assert!(matches!(
3449            host.state.borrow().live.phase,
3450            Phase::Thumb { .. }
3451        ));
3452        thumb_move(&host, pt(0.0, 100.0));
3453        assert!(host.state.borrow().y.0 > 100.0);
3454
3455        // Once released, a reveal scrolls again.
3456        thumb_end(&host);
3457        let y = host.state.borrow().y.0;
3458        assert!(reveal(&host, Points(490.0), Points(32.0)).0 > 0.0);
3459        assert!(host.state.borrow().goal() > y);
3460    }
3461
3462    #[test]
3463    fn a_key_scroll_tells_the_host_every_key_move() {
3464        let host = TestHost::new(scroll_state((300.0, 100_000.0), false));
3465        key_scroll(&host, KeyMove::End, false);
3466        key_scroll(&host, KeyMove::Pages(-1.0), false);
3467        assert_eq!(
3468            *host.key_moves.borrow(),
3469            [KeyMove::End, KeyMove::Pages(-1.0)]
3470        );
3471        assert!(matches!(
3472            host.state.borrow().live.phase,
3473            Phase::Animate { .. }
3474        ));
3475
3476        // A right-to-left row scrolls the other way, and the host still
3477        // hears the key's own move.
3478        let mut row = scroll_state((100_000.0, 500.0), true);
3479        row.mirrored = true;
3480        row.x = Points(1000.0);
3481        let host = TestHost::new(row);
3482        key_scroll(&host, KeyMove::Points(KEY_LINE), true);
3483        assert_eq!(host.state.borrow().goal(), 1000.0 - KEY_LINE.0);
3484        assert_eq!(*host.key_moves.borrow(), [KeyMove::Points(KEY_LINE)]);
3485    }
3486
3487    #[test]
3488    fn wheel_notches_glide_and_add_up_where_the_scroll_is_headed() {
3489        let host = TestHost::new(scroll_state((300.0, 10_000.0), false));
3490        let notch = |dy: f32| wheel_step(&host, pt(0.0, dy));
3491        notch(48.0);
3492        // It eases there instead of jumping.
3493        assert_eq!(host.state.borrow().y.0, 0.0);
3494        assert_eq!(host.state.borrow().goal(), 48.0);
3495        // A notch during the glide adds to its goal.
3496        notch(48.0);
3497        assert_eq!(host.state.borrow().goal(), 96.0);
3498        frame(&host, WHEEL_STEP_ANIMATION);
3499        assert_eq!(host.state.borrow().y.0, 96.0);
3500        assert!(matches!(host.state.borrow().live.phase, Phase::Idle));
3501        // The goal stays within the content.
3502        notch(-1000.0);
3503        assert_eq!(host.state.borrow().goal(), 0.0);
3504        frame(&host, WHEEL_STEP_ANIMATION);
3505        notch(-48.0);
3506        assert!(matches!(host.state.borrow().live.phase, Phase::Idle));
3507
3508        // A snapping view settles on its snap points as with an unanimated
3509        // wheel: the notch moves it at once.
3510        let mut paging = scroll_state((300.0, 10_000.0), false);
3511        paging.behavior.paging = true;
3512        let host = TestHost::new(paging);
3513        wheel_step(&host, pt(0.0, 48.0));
3514        assert_eq!(host.state.borrow().y.0, 48.0);
3515        assert!(matches!(
3516            host.state.borrow().live.phase,
3517            Phase::Wheel { gesture: false, .. }
3518        ));
3519    }
3520
3521    #[test]
3522    fn smooth_wheel_notches_glide_on_chromiums_curve() {
3523        let mut smooth = scroll_state((300.0, 10_000.0), false);
3524        smooth.behavior.smooth_wheel = true;
3525        let host = TestHost::new(smooth);
3526        assert!(smooth_wheel(&host));
3527        wheel_smooth(&host, pt(0.0, 40.0));
3528        // It eases there instead of jumping.
3529        assert_eq!(host.state.borrow().y.0, 0.0);
3530        frame(&host, 60.0);
3531        let y = host.state.borrow().y.0;
3532        assert!(y > 0.0 && y < 40.0, "{y}");
3533        // A notch during the glide goes on from where the last pointed.
3534        wheel_smooth(&host, pt(0.0, 40.0));
3535        assert!(matches!(
3536            host.state.borrow().live.phase,
3537            Phase::Wheel { gesture: false, raw, .. } if raw.y == 80.0
3538        ));
3539        // It arrives, then rests there once the notches stop.
3540        let mut now = 60.0;
3541        while let Some(next) = deadline(&host, now) {
3542            now = next;
3543            frame(&host, now);
3544        }
3545        assert_eq!(host.state.borrow().y.0, 80.0);
3546        assert!(matches!(host.state.borrow().live.phase, Phase::Idle));
3547
3548        // Without it, or where notches step through snap points, they do
3549        // not glide.
3550        let host = TestHost::new(scroll_state((300.0, 10_000.0), false));
3551        assert!(!smooth_wheel(&host));
3552        let mut paging = scroll_state((300.0, 10_000.0), false);
3553        paging.behavior.smooth_wheel = true;
3554        paging.behavior.paging = true;
3555        assert!(!smooth_wheel(&TestHost::new(paging)));
3556    }
3557
3558    #[test]
3559    fn wheel_line_height_rescales_a_notch() {
3560        let mut lines = scroll_state((300.0, 10_000.0), false);
3561        let host = TestHost::new(lines.clone());
3562        // The platform's own line by default.
3563        assert_eq!(
3564            wheel_line(&host, pt(0.0, 30.0), pt(10.0, 10.0)),
3565            pt(0.0, 30.0)
3566        );
3567        lines.behavior.wheel_line_height = Points(40.0);
3568        let host = TestHost::new(lines);
3569        // Three lines of 10 points become three of 40.
3570        assert_eq!(
3571            wheel_line(&host, pt(0.0, 30.0), pt(10.0, 10.0)),
3572            pt(0.0, 120.0)
3573        );
3574        // Each axis by its own line (Linux's grow with the view).
3575        assert_eq!(
3576            wheel_line(&host, pt(25.0, 30.0), pt(25.0, 15.0)),
3577            pt(40.0, 80.0)
3578        );
3579    }
3580
3581    #[test]
3582    fn a_settled_touchpad_scroll_snaps_to_the_nearest_page() {
3583        // Pages of 500 pt; the view rests on the second.
3584        let paged = || {
3585            let mut s = scroll_state((300.0, 5000.0), false);
3586            s.behavior.paging = true;
3587            s.y = Points(500.0);
3588            let host = TestHost::new(s);
3589            wheel_begin(&host);
3590            // A little back toward the first.
3591            wheel(&host, pt(0.0, -60.0));
3592            host
3593        };
3594        let settle = |host: &TestHost| {
3595            let mut now = 0.0;
3596            while let Some(next) = deadline(host, now) {
3597                now = next;
3598                frame(host, now);
3599            }
3600            host.state.borrow().y.0
3601        };
3602        // At rest, its momentum spent: back to the page it is mostly on.
3603        let host = paged();
3604        wheel_settle(&host);
3605        assert_eq!(settle(&host), 500.0);
3606        // A gesture ended without a velocity moves on in its direction.
3607        let host = paged();
3608        wheel_end(&host, 0.0, 0.0);
3609        assert_eq!(settle(&host), 0.0);
3610    }
3611
3612    #[test]
3613    fn a_glide_and_an_eased_move_end_at_their_deadlines() {
3614        let host = TestHost::new(scroll_state((300.0, 100_000.0), false));
3615        assert_eq!(deadline(&host, 0.0), None);
3616        for phase in [
3617            Phase::Glide {
3618                velocity: Offset::new(0.0, 2.0),
3619                last: 0.0,
3620            },
3621            Phase::Animate {
3622                from: Offset::default(),
3623                to: Offset::new(0.0, 400.0),
3624                start: 0.0,
3625                duration: ANIMATION,
3626                momentum: false,
3627                end: true,
3628            },
3629        ] {
3630            host.state.borrow_mut().y = Points(0.0);
3631            host.state.borrow_mut().live.phase = phase;
3632            let mut now = 0.0;
3633            let mut frames = 0;
3634            while let Some(next) = deadline(&host, now) {
3635                now = next;
3636                frame(&host, now);
3637                frames += 1;
3638                assert!(frames < 5, "{:?}", host.state.borrow().live.phase);
3639            }
3640            assert!(matches!(host.state.borrow().live.phase, Phase::Idle));
3641            let y = host.state.borrow().y.0;
3642            match phase {
3643                // Where frames would have taken it.
3644                Phase::Glide { .. } => assert!(
3645                    (y - projected(Points(0.0), 2.0, 0.998).0).abs() < 6.0,
3646                    "{y}"
3647                ),
3648                _ => assert_eq!(y, 400.0),
3649            }
3650        }
3651    }
3652
3653    #[test]
3654    fn indicator_follows_the_view_on_either_axis() {
3655        let host = TestHost::new(scroll_state((300.0, 1000.0), false));
3656        for horizontal in [false, true] {
3657            config(&host, horizontal, true, false, false);
3658            assert!(host.state.borrow().indicator);
3659            // `scrollbar={false}` hides it, a horizontal view's too.
3660            config(&host, horizontal, false, false, false);
3661            assert!(!host.state.borrow().indicator);
3662            // A built-in bar of the app's takes its place.
3663            config(&host, horizontal, true, true, false);
3664            assert!(!host.state.borrow().indicator);
3665        }
3666    }
3667
3668    #[test]
3669    fn switching_indicators_while_refreshing_keeps_the_new_room() {
3670        let host = TestHost::new(scroll_state((300.0, 1000.0), false));
3671        let own = ScrollBehavior {
3672            refresh_indicator: Some(Points(72.0)),
3673            ..Default::default()
3674        };
3675        behavior(&host, &own);
3676        refreshing(&host, true);
3677        frame(&host, 1000.0);
3678        assert_eq!(host.state.borrow().y, Points(-72.0));
3679        // The app drops its own indicator: the spinner draws, in its room.
3680        let redraws = host.redraws.get();
3681        behavior(&host, &ScrollBehavior::default());
3682        assert!(host.redraws.get() > redraws);
3683        frame(&host, 1000.0);
3684        assert_eq!(host.state.borrow().y, Points(-56.0));
3685        // Unchanged props leave it where it is.
3686        behavior(&host, &ScrollBehavior::default());
3687        assert!(matches!(host.state.borrow().live.phase, Phase::Idle));
3688    }
3689
3690    /// A view 300 × 500 over content of `content`, zooming from 0.5 to 4
3691    /// on a backend that draws it.
3692    fn zooming(content: (f32, f32)) -> TestHost {
3693        let mut s = scroll_state(content, false);
3694        s.can_zoom = true;
3695        s.behavior.min_zoom = 0.5;
3696        s.behavior.max_zoom = 4.0;
3697        TestHost::new(s)
3698    }
3699
3700    fn zoom_and_offset(host: &TestHost) -> (f32, f32, f32) {
3701        let s = host.state.borrow();
3702        (s.zoom, s.x.0, s.y.0)
3703    }
3704
3705    fn zoom_to(scale: f32, center: Option<Point<Points>>, animated: bool) -> Command {
3706        Command::ZoomTo {
3707            scale,
3708            center,
3709            animated,
3710        }
3711    }
3712
3713    #[test]
3714    fn only_a_backend_that_draws_zoomed_content_zooms() {
3715        let host = zooming((300.0, 500.0));
3716        host.state.borrow_mut().can_zoom = false;
3717        command(&host, &zoom_to(2.0, None, false));
3718        assert_eq!(zoom_and_offset(&host), (1.0, 0.0, 0.0));
3719        assert!(host.reports.borrow().is_empty());
3720        // Zoomed around the middle, the zoom reported before the offset.
3721        host.state.borrow_mut().can_zoom = true;
3722        command(&host, &zoom_to(2.0, None, false));
3723        assert_eq!(zoom_and_offset(&host), (2.0, 150.0, 250.0));
3724        assert_eq!(*host.reports.borrow(), ["zoom 2", "scroll 150 250"]);
3725    }
3726
3727    #[test]
3728    fn a_pinch_keeps_the_content_under_the_pointer_and_springs_back() {
3729        let host = zooming((300.0, 500.0));
3730        let size = sz(300.0, 500.0);
3731        let at = pt(100.0, 120.0);
3732        pinch_begin(&host);
3733        pinch(&host, 2.0, at);
3734        assert_eq!(zoom_and_offset(&host), (2.0, 100.0, 120.0));
3735        {
3736            let s = host.state.borrow();
3737            assert_eq!(s.to_viewport(size, at), at);
3738            assert_eq!(s.to_content(size, at), at);
3739        }
3740        // Past the limit with fingers: a rubber band, then back to 4.
3741        pinch(&host, 6.0, at);
3742        let banded = host.state.borrow().zoom;
3743        assert!(banded > 4.0 && banded < 6.0, "{banded}");
3744        pinch_end(&host, at);
3745        frame(&host, ANIMATION);
3746        // Content point (100, 120) stays at the pointer.
3747        assert_eq!(zoom_and_offset(&host), (4.0, 300.0, 360.0));
3748        assert!(matches!(host.state.borrow().live.phase, Phase::Idle));
3749    }
3750
3751    #[test]
3752    fn zoomed_content_pans_both_ways_without_a_bar() {
3753        let host = zooming((300.0, 500.0));
3754        host.state.borrow_mut().indicator = true;
3755        let size = sz(300.0, 500.0);
3756        assert!(!host.state.borrow().can_scroll(size, pt(10.0, 10.0)));
3757        command(&host, &zoom_to(2.0, Some(pt(0.0, 0.0)), false));
3758        // The top left corner as near the middle as the edges let it.
3759        assert_eq!(zoom_and_offset(&host), (2.0, 0.0, 0.0));
3760        let s = host.state.borrow().clone();
3761        assert!(s.can_scroll(size, pt(10.0, 0.0)) && s.can_scroll(size, pt(0.0, 10.0)));
3762        assert!(!s.can_scroll(size, pt(-10.0, -10.0)));
3763        assert!(s.thumb(size).is_none());
3764        wheel(&host, pt(30.0, 40.0));
3765        assert_eq!(zoom_and_offset(&host), (2.0, 30.0, 40.0));
3766        // It stops at the edges: 600 × 1000 of content in 300 × 500.
3767        wheel(&host, pt(1000.0, 1000.0));
3768        assert_eq!(zoom_and_offset(&host), (2.0, 300.0, 500.0));
3769        // A fling glides along both axes.
3770        wheel_begin(&host);
3771        wheel(&host, pt(-10.0, -10.0));
3772        wheel_end(&host, -1000.0, -500.0);
3773        let mut now = 0.0;
3774        while let Some(next) = deadline(&host, now) {
3775            now = next;
3776            frame(&host, now);
3777        }
3778        let (_, x, y) = zoom_and_offset(&host);
3779        assert!(x < 280.0 && y < 480.0 && x < y, "{x} {y}");
3780    }
3781
3782    #[test]
3783    fn zoom_to_eases_to_the_point_it_centers() {
3784        let host = zooming((300.0, 500.0));
3785        command(&host, &zoom_to(2.0, Some(pt(100.0, 200.0)), true));
3786        assert!(matches!(host.state.borrow().live.phase, Phase::Zoom { .. }));
3787        assert_eq!(deadline(&host, 0.0), Some(ANIMATION + 1.0));
3788        frame(&host, ANIMATION / 2.0);
3789        let half = host.state.borrow().zoom;
3790        assert!(half > 1.0 && half < 2.0, "{half}");
3791        frame(&host, ANIMATION);
3792        // (100, 200) at 2× is (200, 400): the middle (150, 250) less.
3793        assert_eq!(zoom_and_offset(&host), (2.0, 50.0, 150.0));
3794        // Beyond the limits: the limit.
3795        command(&host, &zoom_to(10.0, None, false));
3796        assert_eq!(host.state.borrow().zoom, 4.0);
3797    }
3798
3799    #[test]
3800    fn small_content_is_centered() {
3801        let host = zooming((300.0, 500.0));
3802        host.state.borrow_mut().behavior.center_content = true;
3803        command(&host, &zoom_to(0.5, None, false));
3804        let s = host.state.borrow();
3805        let size = sz(300.0, 500.0);
3806        assert_eq!(s.centered(size), pt(75.0, 125.0));
3807        assert_eq!(s.to_viewport(size, pt(0.0, 0.0)), pt(75.0, 125.0));
3808        assert_eq!(s.to_content(size, pt(75.0, 125.0)), pt(0.0, 0.0));
3809        assert_eq!((s.x.0, s.y.0), (0.0, 0.0));
3810    }
3811
3812    #[test]
3813    fn new_limits_clamp_the_zoom_and_a_view_that_zooms_no_more_is_back_at_1() {
3814        let host = zooming((300.0, 500.0));
3815        command(&host, &zoom_to(3.0, None, false));
3816        let mut b = host.state.borrow().behavior.clone();
3817        b.max_zoom = 2.0;
3818        behavior(&host, &b);
3819        assert_eq!(host.state.borrow().zoom, 2.0);
3820        b.max_zoom = 0.5;
3821        behavior(&host, &b);
3822        assert_eq!(zoom_and_offset(&host), (1.0, 0.0, 0.0));
3823        frame(&host, 0.0);
3824        let reports = host.reports.borrow();
3825        assert_eq!(reports[reports.len() - 2..], ["zoom 1", "scroll 0 0"]);
3826    }
3827
3828    #[test]
3829    fn cancel_input_clamps_overzoom_and_overscroll_without_refresh_or_duplicate_ticker() {
3830        let host = zooming((300.0, 500.0));
3831        host.state.borrow_mut().behavior.max_zoom = 2.0;
3832        host.state.borrow_mut().behavior.bounces_zoom = true;
3833        pinch_begin(&host);
3834        pinch(&host, 3.0, pt(150.0, 250.0));
3835        assert!(host.state.borrow().zoom > 2.0);
3836        assert_eq!(host.ticks_started.get(), 1);
3837
3838        cancel_input(&host);
3839        assert_eq!(host.state.borrow().zoom, 2.0);
3840        assert!(matches!(host.state.borrow().live.phase, Phase::Idle));
3841        assert!(host.state.borrow().live.ticking);
3842        assert_eq!(host.ticks_started.get(), 1);
3843
3844        let pull = TestHost::new(scroll_state((300.0, 1000.0), false));
3845        drag_begin(&pull);
3846        drag_move(&pull, pt(0.0, 250.0));
3847        assert!(pull.state.borrow().y.0 < 0.0);
3848        assert_eq!(pull.ticks_started.get(), 1);
3849
3850        cancel_input(&pull);
3851        assert_eq!(pull.state.borrow().y.0, 0.0);
3852        assert!(matches!(pull.state.borrow().live.phase, Phase::Idle));
3853        assert!(!pull.state.borrow().live.refreshing);
3854        assert!(!pull.events.borrow().contains(&EventKind::Refresh));
3855        assert_eq!(pull.ticks_started.get(), 1);
3856    }
3857}