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