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