use std::f32::consts::PI;
use crate::{
Bounds, Command, EventKind, EventPayload, NodeId, Point, Points, ScrollBehavior, Size,
StickyCell,
geometry::{Axis, Percentage, Radians, point},
};
const MIN_GLIDE: f32 = 0.05;
const STOP: f32 = 0.01;
const WHEEL_IDLE: f64 = 150.0;
const INDICATOR_HOLD: f64 = 700.0;
const INDICATOR_FADE: f64 = 300.0;
const ANIMATION: f64 = 300.0;
const WHEEL_SNAP: f32 = 0.6;
const INDICATOR_MARGIN: f32 = 2.0;
pub const INDICATOR_THICK: Points = Points(3.0);
const THUMB_GRAB: f32 = 12.0;
const THUMB_SLOP: f32 = 4.0;
#[derive(Debug, Default, Clone, Copy, PartialEq)]
struct Offset {
x: f32,
y: f32,
}
impl Offset {
const fn new(x: f32, y: f32) -> Self {
Self { x, y }
}
fn along(self, horizontal: bool) -> f32 {
if horizontal { self.x } else { self.y }
}
fn with(self, horizontal: bool, v: f32) -> Self {
if horizontal {
Self::new(v, self.y)
} else {
Self::new(self.x, v)
}
}
fn lerp(self, to: Self, k: f32) -> Self {
Self::new(self.x + (to.x - self.x) * k, self.y + (to.y - self.y) * k)
}
fn distance(self, to: Self) -> f32 {
(to.x - self.x).abs().max((to.y - self.y).abs())
}
fn clamp(self, (min, max): (Self, Self)) -> Self {
Self::new(
self.x.clamp(min.x, max.x.max(min.x)),
self.y.clamp(min.y, max.y.max(min.y)),
)
}
}
impl std::ops::Add for Offset {
type Output = Self;
fn add(self, o: Self) -> Self {
Self::new(self.x + o.x, self.y + o.y)
}
}
#[derive(Debug, Default, Clone, Copy, PartialEq)]
enum Phase {
#[default]
Idle,
Drag { start: Offset, moved: Offset },
Thumb { start: f32 },
Wheel {
last: f64,
total: f32,
gesture: bool,
},
Glide { velocity: Offset, last: f64 },
Animate {
from: Offset,
to: Offset,
start: f64,
duration: f64,
momentum: bool,
end: bool,
},
Zoom {
from: f32,
to: f32,
from_c: Offset,
to_c: Offset,
at: Offset,
start: f64,
duration: f64,
},
}
#[derive(Debug, Default, Clone)]
#[non_exhaustive]
pub struct Live {
phase: Phase,
ticking: bool,
report: bool,
shown: f64,
pub alpha: f32,
pub refreshing: bool,
pub spin: Radians,
pub dark: bool,
pinch_from: f32,
reported_zoom: f32,
rezoomed: bool,
}
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct ScrollState {
pub x: Points,
pub y: Points,
pub content: Size<Points>,
pub zoom: f32,
pub can_zoom: bool,
pub horizontal: bool,
pub indicator: bool,
pub behavior: ScrollBehavior,
pub applied: u32,
pub sticky: Vec<StickyCell>,
pub mirrored: bool,
pub live: Live,
}
impl Default for ScrollState {
fn default() -> Self {
Self {
x: Points::ZERO,
y: Points::ZERO,
content: Size::default(),
zoom: 1.0,
can_zoom: false,
horizontal: false,
indicator: false,
behavior: ScrollBehavior::default(),
applied: 0,
sticky: Vec::new(),
mirrored: false,
live: Live::default(),
}
}
}
pub trait ScrollHost {
fn scroll<R>(&self, f: impl FnOnce(&ScrollState, Size<Points>) -> R) -> Option<R>;
fn scroll_mut<R>(&self, f: impl FnOnce(&mut ScrollState, Size<Points>) -> R) -> Option<R>;
fn now(&self) -> f64;
fn listens(&self, kind: EventKind) -> bool;
fn event(&self, kind: EventKind, payload: EventPayload);
fn report(&self, offset: Point<Points>, applied: u32);
fn report_zoom(&self, scale: f32) {
let _ = scale;
}
fn key_scrolled(&self, key_move: KeyMove) {
let _ = key_move;
}
fn moved(&self, offset: Point<Points>);
fn pulled(&self, distance: Points);
fn relayout(&self);
fn redraw(&self);
fn attached(&self) -> bool;
fn start_ticking(&self);
fn settled(&self) {}
fn dark(&self) -> bool {
false
}
}
fn rubber(over: f32, dim: f32) -> f32 {
let dim = dim.max(1.0);
(1.0 - 1.0 / (over * 0.55 / dim + 1.0)) * dim
}
pub fn dragged(raw: Points, min: Points, max: Points, dim: Points, bounces: bool) -> Points {
Points(drag_position(raw.0, min.0, max.0, dim.0, bounces))
}
fn drag_position(raw: f32, min: f32, max: f32, dim: f32, bounces: bool) -> f32 {
if raw < min {
if bounces {
min - rubber(min - raw, dim)
} else {
min
}
} else if raw > max {
if bounces {
max + rubber(raw - max, dim)
} else {
max
}
} else {
raw
}
}
pub fn rate(behavior: &ScrollBehavior) -> f32 {
if behavior.deceleration > 0.0 && behavior.deceleration < 1.0 {
behavior.deceleration
} else if behavior.snaps() || behavior.paging {
0.99
} else {
0.998
}
}
fn glide_step(v: f32, rate: f32, dt: f32) -> (f32, f32) {
let k = rate.powf(dt);
(v * (k - 1.0) / rate.ln(), v * k)
}
pub fn projected(offset: Points, velocity: f32, rate: f32) -> Points {
Points(offset.0 - velocity / rate.ln())
}
pub fn sticky_shift(offset: Points, start: Points, end: Points) -> Points {
Points((offset.0 - start.0).clamp(0.0, (end.0 - start.0).max(0.0)))
}
pub fn ease_out(t: f64) -> f32 {
let t = t.clamp(0.0, 1.0);
(1.0 - (1.0 - t).powi(3)) as f32
}
pub fn snap_duration(distance: Points, velocity: f32) -> f64 {
let (distance, v) = (distance.0, velocity);
if distance.abs() < 0.5 {
return 0.0;
}
if v * distance > 0.0 {
(3.0 * distance.abs() / v.abs()).clamp(180.0, 600.0) as f64
} else {
ANIMATION
}
}
pub fn indicator_alpha(since: f64) -> f32 {
if since < INDICATOR_HOLD {
1.0
} else {
(1.0 - (since - INDICATOR_HOLD) / INDICATOR_FADE).max(0.0) as f32
}
}
pub fn indicator_span(viewport: Points, total: Points, offset: Points) -> Option<(Points, Points)> {
span(viewport.0, total.0, offset.0).map(|(start, len)| (Points(start), Points(len)))
}
fn span(viewport: f32, total: f32, offset: f32) -> Option<(f32, f32)> {
const MIN_LENGTH: f32 = 32.0;
if total <= viewport + 0.5 || viewport <= 4.0 * INDICATOR_MARGIN {
return None;
}
let track = viewport - 2.0 * INDICATOR_MARGIN;
let max = total - viewport;
let over = if offset < 0.0 {
-offset
} else {
(offset - max).max(0.0)
};
let len = (track * viewport / total - over).max(MIN_LENGTH).min(track);
let t = (offset / max).clamp(0.0, 1.0);
Some((INDICATOR_MARGIN + (track - len) * t, len))
}
pub fn thumb_scroll(d: Points, range: Points, travel: Points) -> Points {
if travel.0 > 0.0 {
Points(d.0 * range.0 / travel.0)
} else {
Points(0.0)
}
}
fn shifted(phase: Phase, d: Offset, horizontal: bool) -> Phase {
match phase {
Phase::Drag { start, moved } => Phase::Drag {
start: start + d,
moved,
},
Phase::Thumb { start } => Phase::Thumb {
start: start + d.along(horizontal),
},
Phase::Animate {
from,
to,
start,
duration,
momentum,
end,
} => Phase::Animate {
from: from + d,
to: to + d,
start,
duration,
momentum,
end,
},
other => other,
}
}
pub fn spokes(progress: Percentage, spin: Radians) -> impl Iterator<Item = (Radians, f32)> {
const SPOKES: usize = 8;
let (progress, spin) = (progress.0, spin.0);
let shown = ((progress * SPOKES as f32).ceil() as usize).min(SPOKES);
let step = 2.0 * PI / SPOKES as f32;
let lead = (spin / step) as usize % SPOKES;
(0..shown).map(move |i| {
let fade = if progress < 1.0 {
0.8
} else {
1.0 - ((lead + SPOKES - i) % SPOKES) as f32 / SPOKES as f32 * 0.85
};
(Radians(i as f32 * step), fade)
})
}
pub fn reading_order<T>(axis: Axis, children: &mut [T], origin: impl Fn(&T) -> Point<Points>) {
if children.len() < 2 {
return;
}
let key = |child: &T| {
let at = origin(child);
match axis {
Axis::Horizontal => (at.x.0, at.y.0),
Axis::Vertical => (at.y.0, at.x.0),
}
};
children.sort_by(|a, b| {
let (a, b) = (key(a), key(b));
a.0.total_cmp(&b.0).then(a.1.total_cmp(&b.1))
});
}
impl ScrollState {
pub fn max(&self, size: Size<Points>) -> Point<Points> {
let (x, y) = self.max_f(size);
point(Points(x), Points(y))
}
fn max_f(&self, size: Size<Points>) -> (f32, f32) {
let inset = self.behavior.content_inset;
let z = self.zoom;
(
(self.content.width.0 * z + inset.left.0 + inset.right.0 - size.width.0).max(0.0),
(self.content.height.0 * z + inset.top.0 + inset.bottom.0 - size.height.0).max(0.0),
)
}
pub fn origin(&self) -> Point<Points> {
let inset = self.behavior.content_inset;
point(self.x - inset.left, self.y - inset.top)
}
pub fn zooms(&self) -> bool {
self.can_zoom && self.behavior.zooms()
}
pub fn centered(&self, size: Size<Points>) -> Point<Points> {
if !self.zooms() || !self.behavior.center_content {
return Point::default();
}
let inset = self.behavior.content_inset;
let free = |viewport: f32, content: f32| ((viewport - content * self.zoom) / 2.0).max(0.0);
point(
Points(free(
size.width.0 - inset.left.0 - inset.right.0,
self.content.width.0,
)),
Points(free(
size.height.0 - inset.top.0 - inset.bottom.0,
self.content.height.0,
)),
)
}
pub fn to_viewport(&self, size: Size<Points>, content: Point<Points>) -> Point<Points> {
let (o, room) = (self.origin(), self.centered(size));
point(
Points(content.x.0 * self.zoom - o.x.0 + room.x.0),
Points(content.y.0 * self.zoom - o.y.0 + room.y.0),
)
}
pub fn to_content(&self, size: Size<Points>, at: Point<Points>) -> Point<Points> {
let (o, room) = (self.origin(), self.centered(size));
point(
Points((at.x.0 + o.x.0 - room.x.0) / self.zoom),
Points((at.y.0 + o.y.0 - room.y.0) / self.zoom),
)
}
fn offset(&self) -> f32 {
if self.horizontal { self.x.0 } else { self.y.0 }
}
fn pos(&self) -> Offset {
Offset::new(self.x.0, self.y.0)
}
fn range(&self, size: Size<Points>) -> (Offset, Offset) {
let (min, max) = self.limits(size);
if self.zooms() {
let (mx, my) = self.max_f(size);
let top = if self.horizontal { 0.0 } else { min };
(Offset::new(0.0, top), Offset::new(mx, my))
} else {
let zero = Offset::default();
(
zero.with(self.horizontal, min),
zero.with(self.horizontal, max),
)
}
}
fn content_at(&self, size: Size<Points>, at: Offset) -> Offset {
let c = self.to_content(size, point(Points(at.x), Points(at.y)));
Offset::new(c.x.0, c.y.0)
}
fn showing(&self, size: Size<Points>, c: Offset, at: Offset) -> Offset {
let inset = self.behavior.content_inset;
let room = self.centered(size);
Offset::new(
c.x * self.zoom + room.x.0 - at.x + inset.left.0,
c.y * self.zoom + room.y.0 - at.y + inset.top.0,
)
.clamp(self.range(size))
}
fn goal(&self) -> f32 {
match self.live.phase {
Phase::Animate { to, .. } => to.along(self.horizontal),
_ => self.offset(),
}
}
fn viewport(&self, size: Size<Points>) -> f32 {
if self.horizontal {
size.width.0
} else {
size.height.0
}
}
fn lead(&self) -> f32 {
if self.horizontal {
self.behavior.content_inset.left.0
} else {
self.behavior.content_inset.top.0
}
}
fn limits(&self, size: Size<Points>) -> (f32, f32) {
let max = self.max_f(size);
let min = if !self.horizontal && self.live.refreshing {
-self.behavior.refresh_inset().0
} else {
0.0
};
(min, if self.horizontal { max.0 } else { max.1 })
}
pub fn reported(&self, size: Size<Points>) -> Point<Points> {
let (mx, my) = self.max_f(size);
let inset = self.behavior.content_inset;
point(
Points(self.x.0.clamp(0.0, mx) - inset.left.0),
Points(self.y.0.clamp(0.0, my) - inset.top.0),
)
}
pub fn can_scroll(&self, size: Size<Points>, delta: Point<Points>) -> bool {
let (dx, dy) = (delta.x.0, delta.y.0);
if !self.behavior.enabled {
return false;
}
if self.zooms() {
let ((min, max), p) = (self.range(size), self.pos());
let can = |d: f32, p: f32, min: f32, max: f32| {
(d > 0.0 && p < max - 0.5) || (d < 0.0 && p > min + 0.5)
};
return can(dx, p.x, min.x, max.x) || can(dy, p.y, min.y, max.y);
}
let (min, max) = self.limits(size);
if max <= min {
return false;
}
let d = if self.horizontal {
let d = if dx != 0.0 { dx } else { dy };
if self.mirrored && dx != 0.0 { -d } else { d }
} else {
dy
};
let pos = self.offset();
(d > 0.0 && pos < max - 0.5) || (d < 0.0 && pos > min + 0.5)
}
pub fn thumb(&self, size: Size<Points>) -> Option<(Bounds<Points>, Points)> {
self.thumb_within(
size,
Bounds {
origin: Point::default(),
size,
},
)
}
pub fn thumb_within(
&self,
size: Size<Points>,
visible: Bounds<Points>,
) -> Option<(Bounds<Points>, Points)> {
let (rect, travel) = self.thumb_f(size, visible)?;
Some((rect, Points(travel)))
}
fn visible_edges(size: Size<Points>, visible: Bounds<Points>) -> Option<(f32, f32)> {
let (w, h) = (size.width.0, size.height.0);
let left = visible.origin.x.0.max(0.0);
let top = visible.origin.y.0.max(0.0);
let right = (visible.origin.x.0 + visible.size.width.0).min(w);
let bottom = (visible.origin.y.0 + visible.size.height.0).min(h);
(right > left && bottom > top).then_some((right, bottom))
}
fn thumb_f(
&self,
size: Size<Points>,
visible: Bounds<Points>,
) -> Option<(Bounds<Points>, f32)> {
const EDGE: f32 = 2.0;
if self.zooms() {
return None;
}
let thick = INDICATOR_THICK.0;
let (w, h) = (size.width.0, size.height.0);
let (right, bottom) = Self::visible_edges(size, visible)?;
let inset = self.behavior.content_inset;
let (dim, total, offset) = if self.horizontal {
(
w,
self.content.width.0 + inset.left.0 + inset.right.0,
self.x.0,
)
} else {
(
h,
self.content.height.0 + inset.top.0 + inset.bottom.0,
self.y.0,
)
};
let (start, len) = span(dim, total, offset)?;
let (x, y, rw, rh) = if self.horizontal {
let x = if self.mirrored {
w - start - len
} else {
start
};
(x, bottom - thick - EDGE, len, thick)
} else {
(right - thick - EDGE, start, thick, len)
};
let rect = Bounds {
origin: point(Points(x), Points(y)),
size: Size {
width: Points(rw),
height: Points(rh),
},
};
Some((rect, dim - 2.0 * INDICATOR_MARGIN - len))
}
pub fn grabs_thumb(&self, size: Size<Points>, at: Point<Points>) -> bool {
self.grabs_thumb_within(
size,
Bounds {
origin: Point::default(),
size,
},
at,
)
}
pub fn grabs_thumb_within(
&self,
size: Size<Points>,
visible: Bounds<Points>,
at: Point<Points>,
) -> bool {
let (x, y) = (at.x.0, at.y.0);
if !self.indicator || !self.behavior.enabled {
return false;
}
let Some((rect, _)) = self.thumb_f(size, visible) else {
return false;
};
let Some((right, bottom)) = Self::visible_edges(size, visible) else {
return false;
};
let (along, across, start, len, edge) = if self.horizontal {
(x, y, rect.origin.x.0, rect.size.width.0, bottom)
} else {
(y, x, rect.origin.y.0, rect.size.height.0, right)
};
(edge - THUMB_GRAB..=edge).contains(&across)
&& (start - THUMB_SLOP..=start + len + THUMB_SLOP).contains(&along)
}
pub fn indicates(&self) -> bool {
(self.indicator && self.live.alpha > 0.0) || self.y.0 < 0.0
}
pub fn spinner(&self, width: Points, refresh: bool) -> Option<(Point<Points>, Percentage)> {
let y = self.y.0;
let b = &self.behavior;
if self.horizontal
|| y >= 0.0
|| b.refresh_indicator.is_some()
|| !(self.live.refreshing || refresh)
{
return None;
}
let progress = if self.live.refreshing {
1.0
} else {
(-y / b.refresh_threshold().0).min(1.0)
};
let cy = b.content_inset.top.0 - y - b.refresh_inset().0 / 2.0;
Some((point(width / 2.0, Points(cy)), Percentage(progress)))
}
pub fn sticky_shifts(&self) -> impl Iterator<Item = (NodeId, Point<Points>)> + '_ {
self.sticky_shifts_with(|_| 0.0)
}
pub fn sticky_shifts_with<'a>(
&'a self,
value: impl Fn(crate::animation::NodeId) -> f32 + 'a,
) -> impl Iterator<Item = (NodeId, Point<Points>)> + 'a {
let offset = Points(self.offset() - self.lead());
self.sticky.iter().map(move |c| {
let extra = c.offset.map_or(0.0, &value);
let t = sticky_shift(Points(offset.0 + extra), c.start, c.end);
let zero = Points(0.0);
(
c.cell,
if self.horizontal {
point(t, zero)
} else {
point(zero, t)
},
)
})
}
}
fn phase(host: &impl ScrollHost) -> Phase {
host.scroll(|s, _| s.live.phase).unwrap_or(Phase::Idle)
}
fn set_phase(host: &impl ScrollHost, phase: Phase) {
host.scroll_mut(|s, _| s.live.phase = phase);
}
fn enabled(host: &impl ScrollHost) -> bool {
host.scroll(|s, _| s.behavior.enabled).unwrap_or(false)
}
fn emit(host: &impl ScrollHost, kind: EventKind) {
if kind == EventKind::ScrollEnd {
host.settled();
}
if !host.listens(kind) {
return;
}
let offset = host.scroll(|s, size| s.reported(size)).unwrap_or_default();
host.event(kind, EventPayload::Scroll(offset));
}
fn interrupt(host: &impl ScrollHost) {
let momentum = matches!(
phase(host),
Phase::Glide { .. } | Phase::Animate { momentum: true, .. }
);
set_phase(host, Phase::Idle);
if momentum {
emit(host, EventKind::MomentumEnd);
}
}
fn moved_to(host: &impl ScrollHost, to: Offset) {
let moved = host.scroll_mut(|s, size| {
let rezoomed = std::mem::take(&mut s.live.rezoomed);
if s.pos() == to && !rezoomed {
return None;
}
let pulled =
(!s.horizontal && (s.y.0 < 0.0 || to.y < 0.0)).then(|| Points((-to.y).max(0.0)));
(s.x, s.y) = (Points(to.x), Points(to.y));
if s.indicator {
s.live.shown = host.now();
s.live.alpha = 1.0;
s.live.dark = host.dark();
}
s.live.report = true;
Some((s.reported(size), pulled))
});
let Some(Some((offset, pulled))) = moved else {
return;
};
host.moved(offset);
if let Some(distance) = pulled {
host.pulled(distance);
}
if host.attached() {
ensure_ticking(host);
} else {
report(host);
}
}
fn moved_along(host: &impl ScrollHost, pos: f32) {
if let Some(to) = host.scroll(|s, _| s.pos().with(s.horizontal, pos)) {
moved_to(host, to);
}
}
fn report(host: &impl ScrollHost) {
let pending = host.scroll_mut(|s, size| {
if !std::mem::take(&mut s.live.report) {
return None;
}
let known = s.zooms() || s.live.reported_zoom != 0.0;
let zoom = (known && s.zoom != s.live.reported_zoom).then(|| {
s.live.reported_zoom = s.zoom;
s.zoom
});
Some((s.reported(size), s.applied, zoom))
});
if let Some(Some((offset, applied, zoom))) = pending {
if let Some(zoom) = zoom {
host.report_zoom(zoom);
}
host.report(offset, applied);
}
}
fn animate_to(host: &impl ScrollHost, to: Offset, duration: f64, momentum: bool, end: bool) {
let Some((from, to)) = host.scroll(|s, size| (s.pos(), to.clamp(s.range(size)))) else {
return;
};
if from.distance(to) < 0.5 || duration <= 0.0 {
set_phase(host, Phase::Idle);
moved_to(host, to);
if momentum {
emit(host, EventKind::MomentumEnd);
}
if end {
emit(host, EventKind::ScrollEnd);
}
return;
}
set_phase(
host,
Phase::Animate {
from,
to,
start: host.now(),
duration,
momentum,
end,
},
);
ensure_ticking(host);
}
fn animate_along(host: &impl ScrollHost, to: f32, duration: f64, momentum: bool, end: bool) {
if let Some(to) = host.scroll(|s, _| s.pos().with(s.horizontal, to)) {
animate_to(host, to, duration, momentum, end);
}
}
fn release(host: &impl ScrollHost, v: Offset, snap_velocity: f32) {
let Some((pos, (min, max), main, target)) = host.scroll(|s, size| {
let range = s.range(size);
let pos = s.pos();
let main = v.along(s.horizontal);
let lead = s.lead();
let dim = s.viewport(size);
let snap_velocity = if snap_velocity == 0.0 {
main
} else {
snap_velocity
};
let max = range.1.along(s.horizontal);
let target = s
.behavior
.snap_target(
Points(s.offset() - lead),
projected(Points(s.offset()), main, rate(&s.behavior)) - Points(lead),
snap_velocity,
Points(dim),
Points(max + dim - lead),
)
.filter(|_| !s.zooms())
.map(|t| (pos.with(s.horizontal, t.0 + lead), t.0 + lead - s.offset()));
(pos, range, main, target)
}) else {
return;
};
let past = |p: f32, min: f32, max: f32| p < min - 0.5 || p > max + 0.5;
let room = |v: f32, p: f32, min: f32, max: f32| v > 0.0 && p < max || v < 0.0 && p > min;
if past(pos.x, min.x, max.x) || past(pos.y, min.y, max.y) {
animate_to(host, pos.clamp((min, max)), ANIMATION, false, true);
} else if let Some((target, distance)) = target {
let duration = snap_duration(Points(distance), main);
if duration > 0.0 {
emit(host, EventKind::MomentumStart);
}
animate_to(host, target, duration, duration > 0.0, true);
} else if v.x.abs().max(v.y.abs()) > MIN_GLIDE
&& (room(v.x, pos.x, min.x, max.x) || room(v.y, pos.y, min.y, max.y))
{
set_phase(
host,
Phase::Glide {
velocity: v,
last: host.now(),
},
);
emit(host, EventKind::MomentumStart);
ensure_ticking(host);
} else {
set_phase(host, Phase::Idle);
emit(host, EventKind::ScrollEnd);
}
}
fn ensure_ticking(host: &impl ScrollHost) {
let start = host.scroll_mut(|s, _| !std::mem::replace(&mut s.live.ticking, true));
if start == Some(true) {
host.start_ticking();
}
}
pub fn frame(host: &impl ScrollHost, now: f64) -> bool {
let busy = tick(host, now);
if !busy {
host.scroll_mut(|s, _| s.live.ticking = false);
}
busy
}
pub fn deadline(host: &impl ScrollHost, now: f64) -> Option<f64> {
let (phase, rate) = host.scroll(|s, _| (s.live.phase, rate(&s.behavior)))?;
let end = match phase {
Phase::Glide { velocity, last } => {
let speed = velocity.x.abs().max(velocity.y.abs());
if speed < STOP || !(0.0..1.0).contains(&rate) {
last
} else {
last + ((STOP / speed).ln() / rate.ln()).max(0.0) as f64
}
}
Phase::Animate {
start, duration, ..
}
| Phase::Zoom {
start, duration, ..
} => start + duration,
Phase::Wheel {
last,
gesture: false,
..
} => last + WHEEL_IDLE,
_ => return None,
};
Some(end.max(now) + 1.0)
}
pub fn detached(host: &impl ScrollHost) {
set_phase(host, Phase::Idle);
report(host);
host.scroll_mut(|s, _| s.live.ticking = false);
}
fn tick(host: &impl ScrollHost, now: f64) -> bool {
let Some((phase, pos, rate, (min, max))) =
host.scroll(|s, size| (s.live.phase, s.pos(), rate(&s.behavior), s.range(size)))
else {
return false;
};
match phase {
Phase::Glide { velocity, last } => {
let dt = (now - last).max(0.0) as f32;
let axis = |v: f32, p: f32, min: f32, max: f32| {
let (d, v) = glide_step(v, rate, dt);
let next = p + d;
let stopped = v.abs() < STOP || next <= min || next >= max;
(next, if stopped { 0.0 } else { v }, stopped)
};
let (x, vx, stop_x) = axis(velocity.x, pos.x, min.x, max.x);
let (y, vy, stop_y) = axis(velocity.y, pos.y, min.y, max.y);
moved_to(host, Offset::new(x, y).clamp((min, max)));
if stop_x && stop_y {
set_phase(host, Phase::Idle);
emit(host, EventKind::MomentumEnd);
emit(host, EventKind::ScrollEnd);
} else {
set_phase(
host,
Phase::Glide {
velocity: Offset::new(vx, vy),
last: now,
},
);
}
}
Phase::Animate {
from,
to,
start,
duration,
momentum,
end,
} => {
let t = (now - start) / duration;
moved_to(host, from.lerp(to, ease_out(t)));
if t >= 1.0 {
set_phase(host, Phase::Idle);
if momentum {
emit(host, EventKind::MomentumEnd);
}
if end {
emit(host, EventKind::ScrollEnd);
}
}
}
Phase::Zoom {
from,
to,
from_c,
to_c,
at,
start,
duration,
} => {
let t = (now - start) / duration;
let k = ease_out(t);
zoom_at(host, from + (to - from) * k, from_c.lerp(to_c, k), at);
if t >= 1.0 {
set_phase(host, Phase::Idle);
}
}
Phase::Wheel {
last,
total,
gesture: false,
} if now - last > WHEEL_IDLE => {
set_phase(host, Phase::Idle);
let snaps = host
.scroll(|s, _| s.behavior.snaps() || s.behavior.paging)
.unwrap_or(false);
if snaps {
let v = if total.abs() >= 1.0 {
total.signum() * WHEEL_SNAP
} else {
0.0
};
release(host, Offset::default(), v);
} else {
emit(host, EventKind::ScrollEnd);
}
}
Phase::Idle if pos.x > max.x.max(min.x) + 0.5 || pos.y > max.y.max(min.y) + 0.5 => {
moved_to(
host,
Offset::new(pos.x.min(max.x.max(min.x)), pos.y.min(max.y.max(min.y))),
)
}
_ => {}
}
report(host);
let Some((busy, redraw)) = host.scroll_mut(|s, _| {
let mut redraw = false;
let mut busy = !matches!(
s.live.phase,
Phase::Idle
| Phase::Drag { .. }
| Phase::Thumb { .. }
| Phase::Wheel { gesture: true, .. }
);
if matches!(s.live.phase, Phase::Thumb { .. }) {
s.live.shown = now;
} else if s.live.alpha > 0.0 {
let alpha = indicator_alpha(now - s.live.shown);
if alpha != s.live.alpha {
s.live.alpha = alpha;
redraw = true;
}
busy |= alpha > 0.0;
}
if !s.horizontal
&& s.offset() < 0.0
&& s.live.refreshing
&& s.behavior.refresh_indicator.is_none()
{
s.live.spin = Radians(((now / 1000.0) as f32 * 2.0 * PI) % (2.0 * PI));
redraw = true;
busy = true;
}
(busy, redraw)
}) else {
return false;
};
if redraw {
host.redraw();
}
busy
}
pub fn config(
host: &impl ScrollHost,
horizontal: bool,
indicator: bool,
replaced: bool,
mirrored: bool,
) {
let changed = host.scroll_mut(|s, _| {
s.horizontal = horizontal;
s.indicator = indicator && !replaced;
if !indicator {
s.live.alpha = 0.0;
}
let mirrored = mirrored && horizontal;
std::mem::replace(&mut s.mirrored, mirrored) != mirrored
});
if changed == Some(true) {
host.relayout();
}
}
pub fn content(host: &impl ScrollHost, content: Size<Points>) {
let Some((past, zooms)) = host.scroll_mut(|s, size| {
s.content = content;
let (p, (min, max)) = (s.pos(), s.range(size));
(
p.x > max.x.max(min.x) + 0.5 || p.y > max.y.max(min.y) + 0.5,
s.zooms(),
)
}) else {
return;
};
if zooms {
host.relayout();
}
if past {
ensure_ticking(host);
}
host.redraw();
}
pub fn scroll_by(host: &impl ScrollHost, delta: Point<Points>) {
let (dx, dy) = (delta.x.0, delta.y.0);
let Some((pos, d)) = host.scroll_mut(|s, _| {
s.applied = s.applied.wrapping_add(1);
let d = if s.zooms() {
Offset::new(dx, dy)
} else {
Offset::default().with(s.horizontal, if s.horizontal { dx } else { dy })
};
s.live.phase = shifted(s.live.phase, d, s.horizontal);
s.live.report = true;
(s.pos(), d)
}) else {
return;
};
if d != Offset::default() {
moved_to(host, pos + d);
}
report(host);
}
pub fn behavior(host: &impl ScrollHost, behavior: &ScrollBehavior) {
let Some((inset, refresh, held, zoom)) = host.scroll_mut(|s, _| {
let inset = s.behavior.content_inset != behavior.content_inset
|| s.can_zoom
&& (s.behavior.zooms() != behavior.zooms()
|| s.behavior.center_content != behavior.center_content);
let refresh = s.behavior.refresh_indicator != behavior.refresh_indicator;
s.behavior = behavior.clone();
let zoom = if s.zooms() {
limit_zoom(behavior, s.zoom, false)
} else {
1.0
};
if !behavior.enabled
&& matches!(
s.live.phase,
Phase::Drag { .. } | Phase::Thumb { .. } | Phase::Wheel { .. }
)
{
s.live.phase = Phase::Idle;
}
let held = (refresh
&& !s.horizontal
&& s.live.refreshing
&& s.offset() < 0.0
&& !matches!(s.live.phase, Phase::Drag { .. }))
.then(|| behavior.refresh_inset().0);
(inset, refresh, held, (zoom != s.zoom).then_some(zoom))
}) else {
return;
};
if let Some(zoom) = zoom {
zoom_to(host, zoom, None, false);
}
if inset {
host.relayout();
}
if refresh {
host.redraw();
}
if let Some(room) = held {
animate_along(host, -room, ANIMATION, false, false);
}
}
pub fn refreshing(host: &impl ScrollHost, refreshing: bool) {
let Some(Some((pos, dragging, inset))) = host.scroll_mut(|s, _| {
if s.horizontal || s.live.refreshing == refreshing {
return None;
}
s.live.refreshing = refreshing;
Some((
s.offset(),
matches!(s.live.phase, Phase::Drag { .. }),
s.behavior.refresh_inset().0,
))
}) else {
return;
};
host.redraw();
if dragging {
return;
}
if refreshing && pos <= 0.5 {
animate_along(host, -inset, ANIMATION, false, false);
} else if !refreshing && pos < 0.0 {
animate_along(host, 0.0, ANIMATION, false, false);
}
}
pub fn command(host: &impl ScrollHost, command: &Command) {
if let Command::ZoomTo {
scale,
center,
animated,
} = *command
{
let center = center.map(|c| Offset::new(c.x.0, c.y.0));
return zoom_to(host, scale, center, animated);
}
let Some(Some((target, animated))) = host.scroll_mut(|s, size| {
let range = s.range(size);
let inset = s.behavior.content_inset;
let (target, animated) = match *command {
Command::ScrollTo { x, y, animated } => (
if s.zooms() {
Offset::new(x.0 + inset.left.0, y.0 + inset.top.0)
} else if s.horizontal {
s.pos().with(true, x.0 + inset.left.0)
} else {
s.pos().with(false, y.0 + inset.top.0)
},
animated,
),
Command::ScrollToEnd { animated } => (
s.pos().with(s.horizontal, range.1.along(s.horizontal)),
animated,
),
Command::ScrollToIndex { .. } => {
log::debug!("scroll: {command:?} is not supported");
return None;
}
_ => return None,
};
s.applied = s.applied.wrapping_add(1);
s.live.report = true;
Some((target.clamp(range), animated))
}) else {
return;
};
interrupt(host);
if animated {
animate_to(host, target, ANIMATION, false, true);
} else {
moved_to(host, target);
}
report(host);
}
fn limit_zoom(b: &ScrollBehavior, scale: f32, rubber: bool) -> f32 {
let (min, max) = (b.min_zoom, b.max_zoom.max(b.min_zoom));
let band = |limit: f32| limit * (scale / limit).powf(0.3);
if scale > max {
if rubber && b.bounces_zoom {
band(max)
} else {
max
}
} else if scale < min {
if rubber && b.bounces_zoom {
band(min)
} else {
min
}
} else {
scale
}
}
fn zoom_at(host: &impl ScrollHost, scale: f32, c: Offset, at: Offset) {
let to = host.scroll_mut(|s, size| {
if s.zoom != scale {
s.zoom = scale;
s.live.rezoomed = true;
}
s.showing(size, c, at)
});
if let Some(to) = to {
moved_to(host, to);
}
}
fn zoom_to(host: &impl ScrollHost, scale: f32, center: Option<Offset>, animated: bool) {
let Some(Some((from, to, at, now_c))) = host.scroll(|s, size| {
if !s.zooms() && s.zoom == 1.0 {
log::debug!("scroll: zoomTo on a scroll view that does not zoom");
return None;
}
let to = if s.zooms() {
limit_zoom(&s.behavior, scale, false)
} else {
1.0
};
let at = Offset::new(size.width.0 / 2.0, size.height.0 / 2.0);
Some((s.zoom, to, at, s.content_at(size, at)))
}) else {
return;
};
interrupt(host);
let c = center.unwrap_or(now_c);
if animated && host.attached() && (to - from).abs() > 1e-4 {
zoom_eased(host, from, to, now_c, c, at);
} else {
zoom_at(host, to, c, at);
report(host);
}
}
fn zoom_eased(
host: &impl ScrollHost,
from: f32,
to: f32,
from_c: Offset,
to_c: Offset,
at: Offset,
) {
set_phase(
host,
Phase::Zoom {
from,
to,
from_c,
to_c,
at,
start: host.now(),
duration: ANIMATION,
},
);
ensure_ticking(host);
}
pub fn pinches(host: &impl ScrollHost) -> bool {
host.scroll(|s, _| s.zooms() && s.behavior.pinch)
.unwrap_or(false)
}
pub fn pinch_begin(host: &impl ScrollHost) {
interrupt(host);
host.scroll_mut(|s, _| s.live.pinch_from = s.zoom);
}
pub fn pinch(host: &impl ScrollHost, scale: f32, at: Point<Points>) {
let at = Offset::new(at.x.0, at.y.0);
let Some((to, c)) = host.scroll_mut(|s, size| {
let raw = s.live.pinch_from * scale;
let to = limit_zoom(&s.behavior, raw, true);
(to, s.content_at(size, at))
}) else {
return;
};
zoom_at(host, to, c, at);
}
pub fn pinch_end(host: &impl ScrollHost, at: Point<Points>) {
let at = Offset::new(at.x.0, at.y.0);
let Some((from, to, c)) = host.scroll(|s, size| {
(
s.zoom,
limit_zoom(&s.behavior, s.zoom, false),
s.content_at(size, at),
)
}) else {
return;
};
if (to - from).abs() > 1e-4 {
zoom_eased(host, from, to, c, c, at);
}
}
pub fn drag_begin(host: &impl ScrollHost) {
if !enabled(host) {
return;
}
interrupt(host);
let start = host.scroll(|s, _| s.pos()).unwrap_or_default();
set_phase(
host,
Phase::Drag {
start,
moved: Offset::default(),
},
);
emit(host, EventKind::ScrollDragStart);
}
pub fn drag_move(host: &impl ScrollHost, delta: Point<Points>) {
drag(host, delta.x.0, delta.y.0, false);
}
pub fn drag_to(host: &impl ScrollHost, moved: Point<Points>) {
drag(host, moved.x.0, moved.y.0, true);
}
fn drag(host: &impl ScrollHost, dx: f32, dy: f32, since_begin: bool) {
let Phase::Drag { start, moved } = phase(host) else {
return;
};
let Some((pos, moved)) = host.scroll(|s, size| {
let (min, max) = s.range(size);
let d = if s.zooms() {
Offset::new(-dx, -dy)
} else if !s.horizontal {
Offset::new(0.0, -dy)
} else if s.mirrored {
Offset::new(dx, 0.0)
} else {
Offset::new(-dx, 0.0)
};
let moved = if since_begin { d } else { moved + d };
let raw = start + moved;
let bounces = s.behavior.bounces;
let pos = Offset::new(
drag_position(raw.x, min.x, max.x.max(min.x), size.width.0, bounces),
drag_position(raw.y, min.y, max.y.max(min.y), size.height.0, bounces),
);
(pos, moved)
}) else {
return;
};
set_phase(host, Phase::Drag { start, moved });
moved_to(host, pos);
}
pub fn drag_end(host: &impl ScrollHost, vx: f32, vy: f32) {
if !matches!(phase(host), Phase::Drag { .. }) {
return;
}
let listens = host.listens(EventKind::Refresh);
let Some((v, refresh)) = host.scroll(|s, _| {
let v = if s.zooms() {
Offset::new(-vx / 1000.0, -vy / 1000.0)
} else {
let v = if !s.horizontal {
-vy
} else if s.mirrored {
vx
} else {
-vx
} / 1000.0;
Offset::default().with(s.horizontal, v)
};
let refresh = !s.horizontal
&& !s.live.refreshing
&& listens
&& s.behavior.refreshes(Points(s.offset()));
(v, refresh)
}) else {
return;
};
set_phase(host, Phase::Idle);
emit(host, EventKind::ScrollDragEnd);
if refresh {
host.scroll_mut(|s, _| s.live.refreshing = true);
host.event(EventKind::Refresh, EventPayload::None);
}
release(host, v, 0.0);
}
pub fn hovered(host: &impl ScrollHost) {
let shown = host.scroll_mut(|s, size| {
if s.thumb(size).is_none() || !s.indicator || !s.behavior.enabled {
return false;
}
s.live.shown = host.now();
if s.live.alpha == 1.0 {
return false;
}
s.live.alpha = 1.0;
s.live.dark = host.dark();
true
});
if shown != Some(true) {
return;
}
host.redraw();
ensure_ticking(host);
}
pub fn thumb_begin(host: &impl ScrollHost) {
interrupt(host);
let grabbed = host.scroll_mut(|s, _| {
s.live.phase = Phase::Thumb { start: s.offset() };
s.live.shown = host.now();
s.live.alpha = 1.0;
s.live.dark = host.dark();
});
if grabbed.is_none() {
return;
}
host.redraw();
emit(host, EventKind::ScrollDragStart);
}
pub fn thumb_move(host: &impl ScrollHost, moved: Point<Points>) {
let (dx, dy) = (moved.x.0, moved.y.0);
let Phase::Thumb { start } = phase(host) else {
return;
};
let Some(Some(pos)) = host.scroll(|s, size| {
let (_, travel) = s.thumb(size)?;
let (min, max) = s.limits(size);
let d = if !s.horizontal {
dy
} else if s.mirrored {
-dx
} else {
dx
};
let d = thumb_scroll(Points(d), Points(max), travel).0;
Some((start + d).clamp(min, max.max(min)))
}) else {
return;
};
moved_along(host, pos);
}
pub fn thumb_end(host: &impl ScrollHost) {
if !matches!(phase(host), Phase::Thumb { .. }) {
return;
}
set_phase(host, Phase::Idle);
host.scroll_mut(|s, _| s.live.shown = host.now());
ensure_ticking(host);
emit(host, EventKind::ScrollDragEnd);
release(host, Offset::default(), 0.0);
}
pub fn wheel_begin(host: &impl ScrollHost) {
if !enabled(host) {
return;
}
interrupt(host);
set_phase(
host,
Phase::Wheel {
last: host.now(),
total: 0.0,
gesture: true,
},
);
emit(host, EventKind::ScrollDragStart);
}
pub fn wheel(host: &impl ScrollHost, delta: Point<Points>) {
let (dx, dy) = (delta.x.0, delta.y.0);
if !enabled(host) {
return;
}
let (gesture, total) = match phase(host) {
Phase::Wheel { gesture, total, .. } => (gesture, total),
_ => {
interrupt(host);
(false, 0.0)
}
};
let Some((pos, total)) = host.scroll(|s, size| {
let (min, max) = s.range(size);
let d = if s.zooms() {
Offset::new(dx, dy)
} else if !s.horizontal {
Offset::new(0.0, dy)
} else if dx != 0.0 {
Offset::new(if s.mirrored { -dx } else { dx }, 0.0)
} else {
Offset::new(dy, 0.0)
};
let pos = s.pos();
let one =
|p: f32, d: f32, min: f32, max: f32| (p + d).clamp(min.min(p), max.max(min).max(p));
(
Offset::new(one(pos.x, d.x, min.x, max.x), one(pos.y, d.y, min.y, max.y)),
total + d.along(s.horizontal),
)
}) else {
return;
};
set_phase(
host,
Phase::Wheel {
last: host.now(),
total,
gesture,
},
);
moved_to(host, pos);
ensure_ticking(host);
}
pub fn wheel_end(host: &impl ScrollHost, vx: f32, vy: f32) {
let Phase::Wheel { gesture, total, .. } = phase(host) else {
return;
};
let Some(v) = host.scroll(|s, _| {
let v = if s.zooms() {
return Offset::new(vx / 1000.0, vy / 1000.0);
} else if !s.horizontal {
vy
} else if vx != 0.0 {
if s.mirrored { -vx } else { vx }
} else {
vy
};
Offset::default().with(s.horizontal, v / 1000.0)
}) else {
return;
};
set_phase(host, Phase::Idle);
if gesture {
emit(host, EventKind::ScrollDragEnd);
}
let snap = if v == Offset::default() && total.abs() >= 1.0 {
total.signum() * WHEEL_SNAP
} else {
0.0
};
release(host, v, snap);
}
pub const KEY_LINE: Points = Points(40.0);
const KEY_PAGE: f32 = 0.875;
const KEY_ANIMATION: f64 = 200.0;
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum KeyMove {
Points(Points),
Pages(f32),
Start,
End,
}
impl KeyMove {
pub fn sign(self) -> f32 {
match self {
KeyMove::Points(d) => d.0.signum(),
KeyMove::Pages(n) => n.signum(),
KeyMove::Start => -1.0,
KeyMove::End => 1.0,
}
}
}
pub fn vk_key_move(vk: u16, shift: bool, ctrl: bool) -> Option<(bool, KeyMove)> {
const VK_SPACE: u16 = 0x20;
const VK_PRIOR: u16 = 0x21;
const VK_NEXT: u16 = 0x22;
const VK_END: u16 = 0x23;
const VK_HOME: u16 = 0x24;
const VK_LEFT: u16 = 0x25;
const VK_UP: u16 = 0x26;
const VK_RIGHT: u16 = 0x27;
const VK_DOWN: u16 = 0x28;
if ctrl {
return match vk {
VK_HOME => Some((false, KeyMove::Start)),
VK_END => Some((false, KeyMove::End)),
_ => None,
};
}
Some(match vk {
VK_UP => (false, KeyMove::Points(-KEY_LINE)),
VK_DOWN => (false, KeyMove::Points(KEY_LINE)),
VK_LEFT => (true, KeyMove::Points(-KEY_LINE)),
VK_RIGHT => (true, KeyMove::Points(KEY_LINE)),
VK_PRIOR => (false, KeyMove::Pages(-1.0)),
VK_NEXT => (false, KeyMove::Pages(1.0)),
VK_SPACE if shift => (false, KeyMove::Pages(-1.0)),
VK_SPACE => (false, KeyMove::Pages(1.0)),
VK_HOME => (false, KeyMove::Start),
VK_END => (false, KeyMove::End),
_ => return None,
})
}
fn key_target(m: KeyMove, base: f32, viewport: f32, min: f32, max: f32) -> f32 {
let max = max.max(min);
match m {
KeyMove::Points(d) => base + d.0,
KeyMove::Pages(n) => base + n * (viewport * KEY_PAGE).max(KEY_LINE.0),
KeyMove::Start => min,
KeyMove::End => max,
}
.clamp(min, max)
}
pub fn key_scroll(host: &impl ScrollHost, m: KeyMove, flip: bool) {
let Some((base, viewport, min, max, flip)) = host.scroll(|s, size| {
let (min, max) = s.limits(size);
(s.goal(), s.viewport(size), min, max, flip && s.mirrored)
}) else {
return;
};
let moved = match m {
KeyMove::Points(d) if flip => KeyMove::Points(-d),
m => m,
};
let to = key_target(moved, base, viewport, min, max);
interrupt(host);
animate_along(host, to, KEY_ANIMATION, false, true);
host.key_scrolled(m);
}
const REVEAL_MARGIN: f32 = 16.0;
pub fn reveal_delta(start: Points, end: Points, viewport: Points) -> Points {
Points(reveal_by(start.0, end.0, viewport.0))
}
pub fn reveal_focus_delta(start: Points, end: Points, viewport: Points) -> Points {
Points(reveal_focus_by(start.0, end.0, viewport.0))
}
fn reveal_by(start: f32, end: f32, viewport: f32) -> f32 {
let margin = REVEAL_MARGIN.min(viewport / 4.0);
if start < margin {
start - margin
} else if end > viewport - margin {
(end - (viewport - margin)).min(start - margin)
} else {
0.0
}
}
fn reveal_focus_by(start: f32, end: f32, viewport: f32) -> f32 {
if end - start > viewport && end > 0.0 && start < viewport {
0.0
} else {
reveal_by(start, end, viewport)
}
}
pub fn reveal(host: &impl ScrollHost, start: Points, len: Points) -> Points {
let (start, len) = (start.0, len.0);
let Some((base, pos, dim, min, max)) = host.scroll(|s, size| {
let (min, max) = s.limits(size);
(s.goal(), s.offset(), s.viewport(size), min, max)
}) else {
return Points(0.0);
};
let start = start - (base - pos);
let delta = reveal_focus_by(start, start + len, dim);
let to = (base + delta).clamp(min, max.max(min));
if (to - base).abs() < 0.5 {
return Points(0.0);
}
interrupt(host);
animate_along(host, to, ANIMATION, false, true);
Points(to - base)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::EdgeInsets;
#[test]
fn content_is_read_in_the_order_it_is_on_screen() {
let cells = [(0, 160.0), (1, 200.0), (2, 80.0), (3, 120.0)];
let mut vertical = cells;
reading_order(Axis::Vertical, &mut vertical, |c| {
point(Points(0.0), Points(c.1))
});
assert_eq!(vertical.map(|c| c.0), [2, 3, 0, 1]);
let grid = [
(0, (50.0, 0.0)),
(1, (0.0, 40.0)),
(2, (0.0, 0.0)),
(3, (50.0, 40.0)),
];
let at = |c: &(i32, (f32, f32))| point(Points(c.1.0), Points(c.1.1));
let mut rows = grid;
reading_order(Axis::Vertical, &mut rows, at);
assert_eq!(rows.map(|c| c.0), [2, 0, 1, 3]);
let mut columns = grid;
reading_order(Axis::Horizontal, &mut columns, at);
assert_eq!(columns.map(|c| c.0), [2, 1, 0, 3]);
}
fn scroll_state(content: (f32, f32), horizontal: bool) -> ScrollState {
ScrollState {
content: sz(content.0, content.1),
horizontal,
..Default::default()
}
}
fn sz(w: f32, h: f32) -> Size<Points> {
crate::geometry::size(Points(w), Points(h))
}
fn pt(x: f32, y: f32) -> Point<Points> {
point(Points(x), Points(y))
}
#[test]
fn rubber_band_resists() {
assert_eq!(drag_position(50.0, 0.0, 100.0, 400.0, true), 50.0);
let over = drag_position(-100.0, 0.0, 100.0, 400.0, true);
assert!(over < 0.0 && over > -100.0, "{over}");
let more = drag_position(-400.0, 0.0, 100.0, 400.0, true);
assert!(more < over && more > -400.0 * 0.55);
assert_eq!(drag_position(-100.0, 0.0, 100.0, 400.0, false), 0.0);
assert_eq!(drag_position(300.0, 0.0, 100.0, 400.0, false), 100.0);
assert!(drag_position(150.0, 0.0, 100.0, 400.0, true) > 100.0);
let p = Points;
assert_eq!(dragged(p(50.0), p(0.0), p(100.0), p(400.0), true), p(50.0));
assert!(rubber(1e6, 400.0) < 400.0);
}
#[test]
fn glide_integrates_to_projection() {
let rate = 0.998;
let (mut pos, mut v) = (0.0f32, 2.0f32);
for _ in 0..2000 {
let (d, nv) = glide_step(v, rate, 16.0);
pos += d;
v = nv;
}
let end = projected(Points(0.0), 2.0, rate).0;
assert!((pos - end).abs() < 1.0, "{pos} vs {end}");
let (a, _) = glide_step(2.0, rate, 32.0);
let (b1, v1) = glide_step(2.0, rate, 16.0);
let (b2, _) = glide_step(v1, rate, 16.0);
assert!((a - (b1 + b2)).abs() < 1e-3);
}
#[test]
fn animated_sticky_offsets_stick_further_in() {
let mut s = scroll_state((320.0, 2000.0), false);
s.y = Points(150.0);
s.sticky = vec![
crate::StickyCell {
cell: 1,
start: Points(100.0),
end: Points(300.0),
offset: None,
},
crate::StickyCell {
cell: 2,
start: Points(100.0),
end: Points(300.0),
offset: Some(7),
},
];
let shifts: Vec<_> = s
.sticky_shifts_with(|n| if n == 7 { 56.0 } else { 0.0 })
.map(|(c, p)| (c, p.y.0))
.collect();
assert_eq!(shifts, [(1, 50.0), (2, 106.0)]);
}
#[test]
fn sticky_shift_clamps() {
let p = Points;
assert_eq!(sticky_shift(p(0.0), p(100.0), p(300.0)), p(0.0));
assert_eq!(sticky_shift(p(150.0), p(100.0), p(300.0)), p(50.0));
assert_eq!(sticky_shift(p(500.0), p(100.0), p(300.0)), p(200.0));
assert_eq!(sticky_shift(p(500.0), p(100.0), p(f32::INFINITY)), p(400.0));
}
#[test]
fn rates_follow_behavior() {
let mut b = ScrollBehavior::default();
assert_eq!(rate(&b), 0.998);
b.paging = true;
assert_eq!(rate(&b), 0.99);
b.deceleration = 0.95;
assert_eq!(rate(&b), 0.95);
}
#[test]
fn snapping_and_paging_targets() {
let b = ScrollBehavior {
paging: true,
..Default::default()
};
let r = rate(&b);
let pt = Points;
let t = b.snap_target(
pt(250.0),
projected(pt(250.0), 0.0, r),
0.0,
pt(400.0),
pt(1600.0),
);
assert_eq!(t, Some(pt(400.0)));
let t = b.snap_target(
pt(100.0),
projected(pt(100.0), 1.0, r),
1.0,
pt(400.0),
pt(1600.0),
);
assert_eq!(t, Some(pt(400.0)));
let t = b.snap_target(
pt(300.0),
projected(pt(300.0), -1.0, r),
-1.0,
pt(400.0),
pt(1600.0),
);
assert_eq!(t, Some(pt(0.0)));
let b = ScrollBehavior {
snap_interval: pt(100.0),
..Default::default()
};
let t = b.snap_target(pt(140.0), pt(140.0), 0.0, pt(400.0), pt(1600.0));
assert_eq!(t, Some(pt(100.0)));
assert_eq!(
ScrollBehavior::default().snap_target(pt(140.0), pt(140.0), 0.0, pt(400.0), pt(1600.0)),
None
);
}
#[test]
fn indicator_geometry() {
assert_eq!(span(400.0, 400.0, 0.0), None);
let (s0, l0) = span(400.0, 1600.0, 0.0).unwrap();
assert_eq!(s0, 2.0);
assert!((l0 - 99.0).abs() < 0.01);
let (s1, l1) = span(400.0, 1600.0, 1200.0).unwrap();
assert!((s1 + l1 - 398.0).abs() < 0.01);
let (_, l2) = span(400.0, 1600.0, -50.0).unwrap();
assert!(l2 < l0);
assert_eq!(
indicator_span(Points(400.0), Points(1600.0), Points(0.0)),
Some((Points(s0), Points(l0)))
);
assert_eq!(indicator_alpha(0.0), 1.0);
assert_eq!(indicator_alpha(INDICATOR_HOLD + INDICATOR_FADE), 0.0);
}
#[test]
fn snap_durations() {
let p = Points;
assert_eq!(snap_duration(p(0.2), 1.0), 0.0);
assert_eq!(snap_duration(p(100.0), -1.0), ANIMATION);
assert_eq!(snap_duration(p(300.0), 1.0), 600.0);
assert_eq!(snap_duration(p(300.0), 3.0), 300.0);
assert_eq!(ease_out(1.0), 1.0);
assert_eq!(ease_out(2.0), 1.0);
}
#[test]
fn insets_clamp_and_report() {
let mut s = scroll_state((300.0, 1000.0), false);
let size = sz(300.0, 400.0);
s.behavior.content_inset = EdgeInsets {
top: Points(50.0),
bottom: Points(20.0),
..Default::default()
};
assert_eq!(s.limits(size), (0.0, 670.0));
assert_eq!(s.max(size), pt(0.0, 670.0));
assert_eq!(s.reported(size), pt(0.0, -50.0));
s.y = Points(900.0);
assert_eq!(s.reported(size), pt(0.0, 620.0));
assert_eq!(s.origin(), pt(0.0, 850.0));
s.live.refreshing = true;
assert_eq!(s.limits(size).0, -56.0);
s.behavior.refresh_indicator = Some(Points(80.0));
assert_eq!(s.limits(size).0, -80.0);
}
#[test]
fn can_scroll_follows_edges_and_mirroring() {
let size = sz(300.0, 400.0);
let mut s = scroll_state((300.0, 1000.0), false);
s.behavior.enabled = true;
assert!(s.can_scroll(size, pt(0.0, 10.0)));
assert!(!s.can_scroll(size, pt(0.0, -10.0)));
s.y = Points(600.0);
assert!(!s.can_scroll(size, pt(0.0, 10.0)));
s.behavior.enabled = false;
assert!(!s.can_scroll(size, pt(0.0, -10.0)));
let size = sz(300.0, 100.0);
let mut row = scroll_state((1000.0, 100.0), true);
row.behavior.enabled = true;
row.mirrored = true;
assert!(row.can_scroll(size, pt(-10.0, 0.0)));
assert!(!row.can_scroll(size, pt(10.0, 0.0)));
assert!(row.can_scroll(size, pt(0.0, 10.0)));
}
#[test]
fn scroll_by_moves_gestures_along() {
let y = |v: f32| Offset::new(0.0, v);
let drag = shifted(
Phase::Drag {
start: y(10.0),
moved: y(5.0),
},
y(30.0),
false,
);
assert_eq!(
drag,
Phase::Drag {
start: y(40.0),
moved: y(5.0)
}
);
let anim = Phase::Animate {
from: y(0.0),
to: y(100.0),
start: 1.0,
duration: 300.0,
momentum: false,
end: true,
};
let Phase::Animate { from, to, .. } = shifted(anim, y(-20.0), false) else {
panic!()
};
assert_eq!((from, to), (y(-20.0), y(80.0)));
assert_eq!(shifted(Phase::Idle, y(5.0), false), Phase::Idle);
assert_eq!(
shifted(Phase::Thumb { start: 10.0 }, y(30.0), false),
Phase::Thumb { start: 40.0 }
);
}
#[test]
fn thumb_follows_the_pointer() {
let p = Points;
let (s0, l0) = span(400.0, 1600.0, 0.0).unwrap();
let travel = 400.0 - 2.0 * INDICATOR_MARGIN - l0;
let end = thumb_scroll(p(travel), p(1200.0), p(travel)).0;
assert!((end - 1200.0).abs() < 0.01);
let (s1, _) = span(400.0, 1600.0, end).unwrap();
assert!((s1 - s0 - travel).abs() < 0.01);
assert!(thumb_scroll(p(-10.0), p(1200.0), p(travel)).0 < 0.0);
assert_eq!(thumb_scroll(p(10.0), p(1200.0), p(0.0)), p(0.0));
}
#[test]
fn thumb_is_grabbed_at_the_edge() {
let mut s = scroll_state((300.0, 1600.0), false);
s.indicator = true;
s.behavior.enabled = true;
let size = sz(300.0, 400.0);
let (rect, _) = s.thumb(size).unwrap();
assert_eq!(rect.origin.x.0, 300.0 - INDICATOR_THICK.0 - 2.0);
assert!(s.grabs_thumb(size, pt(295.0, 10.0)));
assert!(!s.grabs_thumb(size, pt(200.0, 10.0)));
assert!(!s.grabs_thumb(size, pt(295.0, 300.0)));
}
#[test]
fn thumb_stays_in_the_visible_part() {
let mut s = scroll_state((900.0, 2000.0), true);
s.indicator = true;
s.behavior.enabled = true;
let size = sz(300.0, 2000.0);
let visible = Bounds::new(pt(0.0, 600.0), sz(300.0, 400.0));
let (rect, _) = s.thumb_within(size, visible).unwrap();
assert_eq!(rect.origin.y.0, 1000.0 - INDICATOR_THICK.0 - 2.0);
assert!(s.grabs_thumb_within(size, visible, pt(20.0, 997.0)));
assert!(!s.grabs_thumb_within(size, visible, pt(20.0, 1997.0)));
let (rect, _) = s.thumb(size).unwrap();
assert_eq!(rect.origin.y.0, 2000.0 - INDICATOR_THICK.0 - 2.0);
let hidden = Bounds::new(pt(0.0, 2100.0), sz(300.0, 400.0));
assert!(s.thumb_within(size, hidden).is_none());
}
#[test]
fn scroll_keys() {
assert_eq!(
vk_key_move(0x28, false, false),
Some((false, KeyMove::Points(KEY_LINE)))
);
assert_eq!(
vk_key_move(0x25, false, false),
Some((true, KeyMove::Points(-KEY_LINE)))
);
assert_eq!(
vk_key_move(0x20, true, false),
Some((false, KeyMove::Pages(-1.0)))
);
assert_eq!(
vk_key_move(0x24, false, true),
Some((false, KeyMove::Start))
);
assert_eq!(vk_key_move(0x28, false, true), None);
assert_eq!(vk_key_move(b'A' as u16, false, false), None);
assert_eq!(KeyMove::Start.sign(), -1.0);
assert_eq!(KeyMove::Pages(1.0).sign(), 1.0);
assert_eq!(
key_target(KeyMove::Points(Points(40.0)), 10.0, 400.0, 0.0, 1000.0),
50.0
);
assert_eq!(
key_target(KeyMove::Pages(1.0), 0.0, 400.0, 0.0, 1000.0),
350.0
);
assert_eq!(
key_target(KeyMove::Pages(-1.0), 100.0, 400.0, 0.0, 1000.0),
0.0
);
assert_eq!(key_target(KeyMove::End, 0.0, 400.0, 0.0, 1000.0), 1000.0);
assert_eq!(
key_target(KeyMove::Start, 500.0, 400.0, -56.0, 1000.0),
-56.0
);
}
#[test]
fn reveal_deltas() {
assert_eq!(reveal_by(100.0, 140.0, 400.0), 0.0);
assert_eq!(reveal_by(-30.0, 10.0, 400.0), -46.0);
assert_eq!(reveal_by(380.0, 420.0, 400.0), 36.0);
assert_eq!(reveal_by(200.0, 900.0, 400.0), 184.0);
assert_eq!(reveal_focus_by(500.0, 1200.0, 400.0), 484.0);
assert_eq!(reveal_focus_by(-1200.0, -500.0, 400.0), -1216.0);
assert_eq!(reveal_focus_by(200.0, 900.0, 400.0), 0.0);
assert_eq!(reveal_focus_by(-2000.0, 300.0, 400.0), 0.0);
assert_eq!(reveal_focus_by(-2000.0, 900.0, 400.0), 0.0);
assert_eq!(reveal_focus_by(-100.0, 290.0, 400.0), -116.0);
assert_eq!(
reveal_focus_delta(Points(200.0), Points(900.0), Points(400.0)),
Points(0.0)
);
assert_eq!(
reveal_delta(Points(-30.0), Points(10.0), Points(400.0)),
Points(-46.0)
);
}
#[test]
fn spinner_spokes() {
assert_eq!(spokes(Percentage(0.3), Radians(0.0)).count(), 3);
assert!(spokes(Percentage(0.3), Radians(0.0)).all(|(_, a)| a == 0.8));
let all: Vec<_> = spokes(Percentage(1.0), Radians(0.0)).collect();
assert_eq!(all.len(), 8);
assert_eq!(all[0].1, 1.0);
assert_eq!(all[1].0, Radians(PI / 4.0));
}
#[test]
fn refresh_follows_its_props() {
let mut s = scroll_state((300.0, 1000.0), false);
assert!(!s.behavior.refreshes(Points(-63.0)));
assert!(s.behavior.refreshes(Points(-64.0)));
s.y = Points(-32.0);
assert_eq!(
s.spinner(Points(300.0), true),
Some((pt(150.0, 4.0), Percentage(0.5)))
);
s.behavior.refresh_indicator = Some(Points(100.0));
assert!(!s.behavior.refreshes(Points(-64.0)));
assert!(s.behavior.refreshes(Points(-100.0)));
assert_eq!(s.behavior.refresh_inset(), Points(100.0));
assert_eq!(s.spinner(Points(300.0), true), None);
}
struct TestHost {
state: std::cell::RefCell<ScrollState>,
redraws: std::cell::Cell<u32>,
reports: std::cell::RefCell<Vec<String>>,
key_moves: std::cell::RefCell<Vec<KeyMove>>,
}
impl TestHost {
fn new(state: ScrollState) -> Self {
Self {
state: std::cell::RefCell::new(state),
redraws: std::cell::Cell::new(0),
reports: Default::default(),
key_moves: Default::default(),
}
}
}
impl ScrollHost for TestHost {
fn scroll<R>(&self, f: impl FnOnce(&ScrollState, Size<Points>) -> R) -> Option<R> {
Some(f(&self.state.borrow(), sz(300.0, 500.0)))
}
fn scroll_mut<R>(&self, f: impl FnOnce(&mut ScrollState, Size<Points>) -> R) -> Option<R> {
Some(f(&mut self.state.borrow_mut(), sz(300.0, 500.0)))
}
fn now(&self) -> f64 {
0.0
}
fn listens(&self, _: EventKind) -> bool {
true
}
fn event(&self, _: EventKind, _: EventPayload) {}
fn report(&self, offset: Point<Points>, _: u32) {
let line = format!("scroll {} {}", offset.x.0, offset.y.0);
self.reports.borrow_mut().push(line);
}
fn report_zoom(&self, scale: f32) {
self.reports.borrow_mut().push(format!("zoom {scale}"));
}
fn key_scrolled(&self, key_move: KeyMove) {
self.key_moves.borrow_mut().push(key_move);
}
fn moved(&self, _: Point<Points>) {}
fn pulled(&self, _: Points) {}
fn relayout(&self) {}
fn redraw(&self) {
self.redraws.set(self.redraws.get() + 1);
}
fn attached(&self) -> bool {
true
}
fn start_ticking(&self) {}
}
#[test]
fn a_key_scroll_tells_the_host_every_key_move() {
let host = TestHost::new(scroll_state((300.0, 100_000.0), false));
key_scroll(&host, KeyMove::End, false);
key_scroll(&host, KeyMove::Pages(-1.0), false);
assert_eq!(
*host.key_moves.borrow(),
[KeyMove::End, KeyMove::Pages(-1.0)]
);
assert!(matches!(
host.state.borrow().live.phase,
Phase::Animate { .. }
));
let mut row = scroll_state((100_000.0, 500.0), true);
row.mirrored = true;
row.x = Points(1000.0);
let host = TestHost::new(row);
key_scroll(&host, KeyMove::Points(KEY_LINE), true);
assert_eq!(host.state.borrow().goal(), 1000.0 - KEY_LINE.0);
assert_eq!(*host.key_moves.borrow(), [KeyMove::Points(KEY_LINE)]);
}
#[test]
fn a_glide_and_an_eased_move_end_at_their_deadlines() {
let host = TestHost::new(scroll_state((300.0, 100_000.0), false));
assert_eq!(deadline(&host, 0.0), None);
for phase in [
Phase::Glide {
velocity: Offset::new(0.0, 2.0),
last: 0.0,
},
Phase::Animate {
from: Offset::default(),
to: Offset::new(0.0, 400.0),
start: 0.0,
duration: ANIMATION,
momentum: false,
end: true,
},
] {
host.state.borrow_mut().y = Points(0.0);
host.state.borrow_mut().live.phase = phase;
let mut now = 0.0;
let mut frames = 0;
while let Some(next) = deadline(&host, now) {
now = next;
frame(&host, now);
frames += 1;
assert!(frames < 5, "{:?}", host.state.borrow().live.phase);
}
assert!(matches!(host.state.borrow().live.phase, Phase::Idle));
let y = host.state.borrow().y.0;
match phase {
Phase::Glide { .. } => assert!(
(y - projected(Points(0.0), 2.0, 0.998).0).abs() < 6.0,
"{y}"
),
_ => assert_eq!(y, 400.0),
}
}
}
#[test]
fn indicator_follows_the_view_on_either_axis() {
let host = TestHost::new(scroll_state((300.0, 1000.0), false));
for horizontal in [false, true] {
config(&host, horizontal, true, false, false);
assert!(host.state.borrow().indicator);
config(&host, horizontal, false, false, false);
assert!(!host.state.borrow().indicator);
config(&host, horizontal, true, true, false);
assert!(!host.state.borrow().indicator);
}
}
#[test]
fn switching_indicators_while_refreshing_keeps_the_new_room() {
let host = TestHost::new(scroll_state((300.0, 1000.0), false));
let own = ScrollBehavior {
refresh_indicator: Some(Points(72.0)),
..Default::default()
};
behavior(&host, &own);
refreshing(&host, true);
frame(&host, 1000.0);
assert_eq!(host.state.borrow().y, Points(-72.0));
let redraws = host.redraws.get();
behavior(&host, &ScrollBehavior::default());
assert!(host.redraws.get() > redraws);
frame(&host, 1000.0);
assert_eq!(host.state.borrow().y, Points(-56.0));
behavior(&host, &ScrollBehavior::default());
assert!(matches!(host.state.borrow().live.phase, Phase::Idle));
}
fn zooming(content: (f32, f32)) -> TestHost {
let mut s = scroll_state(content, false);
s.can_zoom = true;
s.behavior.min_zoom = 0.5;
s.behavior.max_zoom = 4.0;
TestHost::new(s)
}
fn zoom_and_offset(host: &TestHost) -> (f32, f32, f32) {
let s = host.state.borrow();
(s.zoom, s.x.0, s.y.0)
}
fn zoom_to(scale: f32, center: Option<Point<Points>>, animated: bool) -> Command {
Command::ZoomTo {
scale,
center,
animated,
}
}
#[test]
fn only_a_backend_that_draws_zoomed_content_zooms() {
let host = zooming((300.0, 500.0));
host.state.borrow_mut().can_zoom = false;
command(&host, &zoom_to(2.0, None, false));
assert_eq!(zoom_and_offset(&host), (1.0, 0.0, 0.0));
assert!(host.reports.borrow().is_empty());
host.state.borrow_mut().can_zoom = true;
command(&host, &zoom_to(2.0, None, false));
assert_eq!(zoom_and_offset(&host), (2.0, 150.0, 250.0));
assert_eq!(*host.reports.borrow(), ["zoom 2", "scroll 150 250"]);
}
#[test]
fn a_pinch_keeps_the_content_under_the_pointer_and_springs_back() {
let host = zooming((300.0, 500.0));
let size = sz(300.0, 500.0);
let at = pt(100.0, 120.0);
pinch_begin(&host);
pinch(&host, 2.0, at);
assert_eq!(zoom_and_offset(&host), (2.0, 100.0, 120.0));
{
let s = host.state.borrow();
assert_eq!(s.to_viewport(size, at), at);
assert_eq!(s.to_content(size, at), at);
}
pinch(&host, 6.0, at);
let banded = host.state.borrow().zoom;
assert!(banded > 4.0 && banded < 6.0, "{banded}");
pinch_end(&host, at);
frame(&host, ANIMATION);
assert_eq!(zoom_and_offset(&host), (4.0, 300.0, 360.0));
assert!(matches!(host.state.borrow().live.phase, Phase::Idle));
}
#[test]
fn zoomed_content_pans_both_ways_without_a_bar() {
let host = zooming((300.0, 500.0));
host.state.borrow_mut().indicator = true;
let size = sz(300.0, 500.0);
assert!(!host.state.borrow().can_scroll(size, pt(10.0, 10.0)));
command(&host, &zoom_to(2.0, Some(pt(0.0, 0.0)), false));
assert_eq!(zoom_and_offset(&host), (2.0, 0.0, 0.0));
let s = host.state.borrow().clone();
assert!(s.can_scroll(size, pt(10.0, 0.0)) && s.can_scroll(size, pt(0.0, 10.0)));
assert!(!s.can_scroll(size, pt(-10.0, -10.0)));
assert!(s.thumb(size).is_none());
wheel(&host, pt(30.0, 40.0));
assert_eq!(zoom_and_offset(&host), (2.0, 30.0, 40.0));
wheel(&host, pt(1000.0, 1000.0));
assert_eq!(zoom_and_offset(&host), (2.0, 300.0, 500.0));
wheel_begin(&host);
wheel(&host, pt(-10.0, -10.0));
wheel_end(&host, -1000.0, -500.0);
let mut now = 0.0;
while let Some(next) = deadline(&host, now) {
now = next;
frame(&host, now);
}
let (_, x, y) = zoom_and_offset(&host);
assert!(x < 280.0 && y < 480.0 && x < y, "{x} {y}");
}
#[test]
fn zoom_to_eases_to_the_point_it_centers() {
let host = zooming((300.0, 500.0));
command(&host, &zoom_to(2.0, Some(pt(100.0, 200.0)), true));
assert!(matches!(host.state.borrow().live.phase, Phase::Zoom { .. }));
assert_eq!(deadline(&host, 0.0), Some(ANIMATION + 1.0));
frame(&host, ANIMATION / 2.0);
let half = host.state.borrow().zoom;
assert!(half > 1.0 && half < 2.0, "{half}");
frame(&host, ANIMATION);
assert_eq!(zoom_and_offset(&host), (2.0, 50.0, 150.0));
command(&host, &zoom_to(10.0, None, false));
assert_eq!(host.state.borrow().zoom, 4.0);
}
#[test]
fn small_content_is_centered() {
let host = zooming((300.0, 500.0));
host.state.borrow_mut().behavior.center_content = true;
command(&host, &zoom_to(0.5, None, false));
let s = host.state.borrow();
let size = sz(300.0, 500.0);
assert_eq!(s.centered(size), pt(75.0, 125.0));
assert_eq!(s.to_viewport(size, pt(0.0, 0.0)), pt(75.0, 125.0));
assert_eq!(s.to_content(size, pt(75.0, 125.0)), pt(0.0, 0.0));
assert_eq!((s.x.0, s.y.0), (0.0, 0.0));
}
#[test]
fn new_limits_clamp_the_zoom_and_a_view_that_zooms_no_more_is_back_at_1() {
let host = zooming((300.0, 500.0));
command(&host, &zoom_to(3.0, None, false));
let mut b = host.state.borrow().behavior.clone();
b.max_zoom = 2.0;
behavior(&host, &b);
assert_eq!(host.state.borrow().zoom, 2.0);
b.max_zoom = 0.5;
behavior(&host, &b);
assert_eq!(zoom_and_offset(&host), (1.0, 0.0, 0.0));
frame(&host, 0.0);
let reports = host.reports.borrow();
assert_eq!(reports[reports.len() - 2..], ["zoom 1", "scroll 0 0"]);
}
}