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