pub use self::{
area::{Scroll, ScrollBar, ScrollContent},
list::{Rows, ScrollList, ScrollListState},
};
mod area;
mod list;
use core::time::Duration;
use blit::{
Animation, AnimationOptions, Axis, Id, Layout, LayoutCx, NodeId, Point, Scalar, Scope, Ui,
internal::animator::Animator, state::Local,
};
use crate::{Context, interact};
#[derive(Debug, Default)]
pub struct ScrollState<T> {
pub offset: T,
pub content_extent: T,
pub viewport_extent: T,
inertia: Inertia,
request: Request<T>,
}
#[derive(Debug, Default)]
struct Inertia {
velocity: f32,
tracking: bool,
last_frame: Option<Duration>,
remainder: f32,
sample_time: Option<Duration>,
pending_delta: f32,
}
impl<T: Scalar> ScrollState<T> {
pub fn new() -> Self {
Self::default()
}
pub fn maximum_offset(&self) -> T {
(self.content_extent - self.viewport_extent).max(T::ZERO)
}
pub fn scroll_by(&mut self, amount: T) {
self.scroll_to(self.offset.endpoint(amount));
}
pub fn scroll_to(&mut self, offset: T) {
self.inertia.stop();
self.request.target = Goal::Offset(offset);
}
pub fn reveal(&mut self, target: Id) {
self.inertia.stop();
self.request.target = Goal::Node(target);
self.request.missed = false;
}
pub fn jump_to(&mut self, offset: T) {
self.stop();
self.offset = offset;
}
pub fn stop(&mut self) {
self.inertia.stop();
self.request = Request::default();
}
pub fn is_moving(&self) -> bool {
match self.request.target {
Goal::None => self.inertia.velocity != 0.0,
Goal::Offset(_) | Goal::Node(_) => true,
}
}
}
impl Inertia {
fn stop(&mut self) {
self.remainder = 0.0;
self.velocity = 0.0;
self.tracking = false;
self.sample_time = None;
self.pending_delta = 0.0;
}
fn pixel_delta<T: Scalar>(&mut self, amount: f32) -> T {
let delta = amount + self.remainder;
let whole = if amount == 0.0 { T::ZERO } else { T::from_f32(delta) };
self.remainder = delta - whole.to_f32();
whole
}
}
#[derive(Debug, Default)]
struct Request<T> {
target: Goal<T>,
animator: Option<Animator<T, 1>>,
missed: bool,
}
#[derive(Clone, Copy, Debug, Default)]
enum Goal<T> {
#[default]
None,
Offset(T),
Node(Id),
}
#[derive(Clone, Copy)]
struct ScrollLayout<T> {
axis: Axis,
offset: T,
viewport_extent: T,
scrollbar: Scrollbar<T>,
}
#[derive(Clone, Copy)]
struct ThumbProgress {
position: f32,
visible_fraction: f32,
}
#[derive(Clone, Copy, Default)]
enum ScrollItem {
#[default]
Content,
Track,
Thumb,
}
impl<C: Context<Scalar = T>, T: Scalar> Layout<C> for ScrollLayout<T> {
type Item = ScrollItem;
fn fit(&self, ui: &mut LayoutCx<'_, C, Self::Item>, axis: Axis) -> blit::Fit<T> {
let (Some(content), bars) = scroll_parts(ui) else {
return blit::Fit::ZERO;
};
let mut extent = ui.fit(content, axis);
if axis == self.axis {
extent.min = T::ZERO;
} else if !self.scrollbar.floating
&& let Some((track, _)) = bars
{
let track_fit = ui.fit(track, axis);
extent.min = extent.min.endpoint(track_fit.min);
extent.natural = extent.natural.endpoint(track_fit.natural);
}
extent
}
fn distribute(&self, ui: &mut LayoutCx<'_, C, Self::Item>, axis: Axis, extent: T) {
let (Some(content), bars) = scroll_parts(ui) else {
return;
};
if axis == self.axis {
let content_extent = ui.set_extent(content, ui.fit(content, axis).natural);
let maximum = (content_extent - extent).max(T::ZERO);
let offset = self.offset.clamp(T::ZERO, maximum);
if extent != self.viewport_extent || offset != self.offset {
ui.request_frame();
}
ui.set_offset(content, -offset);
if let Some((track, thumb)) = bars {
if maximum > T::ZERO {
let progress = ThumbProgress {
position: offset.to_f32() / maximum.to_f32(),
visible_fraction: if content_extent > T::ZERO {
extent.to_f32() / content_extent.to_f32()
} else {
1.0
},
};
self.scrollbar.distribute_main(ui, extent, progress, track, thumb);
} else {
ui.set_extent(track, T::ZERO);
ui.set_offset(track, extent);
ui.set_extent(thumb, T::ZERO);
ui.set_offset(thumb, extent);
}
}
} else {
let thickness = bars.map_or(T::ZERO, |(track, _)| ui.fit(track, axis).natural.min(extent));
let gutter = if self.scrollbar.floating { T::ZERO } else { thickness };
ui.set_extent(content, (extent - gutter).max(T::ZERO));
ui.set_offset(content, T::ZERO);
if let Some((track, thumb)) = bars {
self.scrollbar.distribute_cross(ui, extent, thickness, track, thumb);
}
}
}
}
fn scroll_parts<C: Context>(ui: &LayoutCx<'_, C, ScrollItem>) -> (Option<NodeId>, Option<(NodeId, NodeId)>) {
let (mut content, mut track, mut thumb) = (None, None, None);
for child in ui.children() {
match *ui.item(child) {
ScrollItem::Content => content = Some(child),
ScrollItem::Track => track = Some(child),
ScrollItem::Thumb => thumb = Some(child),
}
}
(content, track.zip(thumb))
}
#[derive(Clone, Copy)]
struct Scrollbar<T> {
minimum: T,
floating: bool,
}
impl<T: Scalar> Scrollbar<T> {
fn distribute_main<C: Context<Scalar = T>, I: 'static>(
&self,
ui: &mut LayoutCx<'_, C, I>,
extent: T,
progress: ThumbProgress,
track: NodeId,
thumb: NodeId,
) {
ui.set_extent(track, extent);
ui.set_offset(track, T::ZERO);
let thumb_extent = T::from_f32(extent.to_f32() * progress.visible_fraction)
.max(self.minimum.max(T::ZERO))
.min(extent);
let thumb_extent = ui.set_extent(thumb, thumb_extent);
let thumb_offset = T::from_f32(progress.position * (extent - thumb_extent).max(T::ZERO).to_f32());
ui.set_offset(thumb, thumb_offset);
}
fn distribute_cross<C: Context<Scalar = T>, I: 'static>(
&self,
ui: &mut LayoutCx<'_, C, I>,
extent: T,
thickness: T,
track: NodeId,
thumb: NodeId,
) {
let thickness = ui.set_extent(track, thickness);
ui.set_offset(track, extent - thickness);
ui.set_extent(thumb, thickness);
ui.set_offset(thumb, extent - thickness);
}
}
fn update<C: Context, S: Local>(
state: &mut ScrollState<C::Scalar>,
ui: &mut Ui<'_, C, S>,
parts: Scope,
axis: Axis,
scroll_speed: f32,
inertia_friction: f32,
) -> (bool, bool) {
let viewport_known = if let Some(area) = ui.area() {
state.viewport_extent = axis.extent(area.size());
true
} else {
false
};
let content_id = ui.resolve(parts, CONTENT);
if let Some(area) = ui.node(content_id).area() {
state.content_extent = axis.extent(area.size());
}
let motion = content_input(ui, axis);
if motion.active || motion.deactivated || motion.delta != Point::ZERO {
state.request = Request::default();
}
let maximum = state.maximum_offset();
let (thumb_active, scrollbar) = scrollbar_input(&mut state.inertia, ui, parts, axis, state.viewport_extent);
if let Some(action) = scrollbar {
state.request = Request::default();
match action {
ScrollbarInput::Thumb(delta) => move_by(state, delta * maximum.to_f32()),
ScrollbarInput::Track(position) => {
state.offset = C::Scalar::from_f32(position * maximum.to_f32()).clamp(C::Scalar::ZERO, maximum);
state.inertia.remainder = 0.0;
}
ScrollbarInput::Idle => {}
}
} else {
let delta = content_motion(&mut state.inertia, ui, axis, scroll_speed, inertia_friction, motion);
move_by(state, delta);
}
(thumb_active, viewport_known)
}
enum ScrollbarInput {
Thumb(f32),
Track(f32),
Idle,
}
fn scrollbar_input<C: Context, S: Local>(
state: &mut Inertia,
ui: &mut Ui<'_, C, S>,
scroll: Scope,
axis: Axis,
viewport_extent: C::Scalar,
) -> (bool, Option<ScrollbarInput>) {
let thumb_id = ui.resolve(scroll, THUMB);
let track_id = ui.resolve(scroll, TRACK);
let (thumb_area, thumb, thumb_drag) = {
let mut part = ui.node(thumb_id);
(
part.area(),
part.interact(interact::press()),
part.interact(interact::drag()),
)
};
let (track_area, track, track_drag) = {
let mut part = ui.node(track_id);
(
part.area(),
part.interact(interact::press()),
part.interact(interact::drag()),
)
};
let active = thumb.active || track.active || thumb_drag.active || track_drag.active;
let thumb_moved = thumb_drag.active || thumb_drag.released;
let track_delta = match axis {
Axis::Horizontal => track_drag.delta.x,
Axis::Vertical => track_drag.delta.y,
};
let track_moved = track_drag.active || track_drag.released && track_delta != C::Scalar::ZERO;
if !thumb_moved && !track.activated && !track_moved {
return (active, None);
}
state.last_frame = Some(ui.time());
let extent = thumb_area.map_or(C::Scalar::ZERO, |area| axis.extent(area.size()));
let travel = viewport_extent - extent;
state.velocity = 0.0;
state.tracking = false;
if travel <= C::Scalar::ZERO {
return (active, Some(ScrollbarInput::Idle));
}
let travel = travel.to_f32();
let action = if thumb_moved {
let delta = match axis {
Axis::Horizontal => thumb_drag.delta.x,
Axis::Vertical => thumb_drag.delta.y,
};
ScrollbarInput::Thumb(delta.to_f32() / travel)
} else {
let pointer = if track_moved {
Some(track_drag.position)
} else {
track.contact.and_then(|id| ui.contact_position(id))
};
match (track_area, pointer) {
(Some(track), Some(pointer)) => {
let position = match axis {
Axis::Horizontal => pointer.x - track.x,
Axis::Vertical => pointer.y - track.y,
};
ScrollbarInput::Track(((position.to_f32() - extent.to_f32() / 2.0) / travel).clamp(0.0, 1.0))
}
_ => ScrollbarInput::Idle,
}
};
(active, Some(action))
}
fn content_input<C: Context, S: Local>(ui: &mut Ui<'_, C, S>, axis: Axis) -> interact::scroll::Response {
let scroll = ui.interact(interact::scroll().axis(axis));
let pan = ui.interact(interact::drag().axis(axis).touch_only(true));
if !pan.active && !pan.deactivated {
return scroll;
}
interact::scroll::Response {
active: pan.active,
activated: pan.activated,
deactivated: pan.deactivated,
released: pan.released,
delta: Point::new(-pan.delta.x.to_f32(), -pan.delta.y.to_f32()),
continuous: true,
}
}
fn content_motion<C: Context, S: Local>(
state: &mut Inertia,
ui: &mut Ui<'_, C, S>,
axis: Axis,
scroll_speed: f32,
inertia_friction: f32,
motion: interact::scroll::Response,
) -> f32 {
let now = ui.time();
let previous = state.last_frame.replace(now);
let elapsed = previous.map_or(0.0, |previous| now.saturating_sub(previous).as_secs_f32());
if matches!(ui.input(), blit::input::Input::Touch { phase: blit::input::TouchPhase::Down, position, .. }
if ui.area().is_some_and(|area| area.contains(*position)))
{
state.stop();
state.sample_time = Some(now);
return 0.0;
}
let moving = motion.active || motion.deactivated || motion.delta != Point::ZERO;
let delta = match axis {
Axis::Horizontal => motion.delta.x,
Axis::Vertical => motion.delta.y,
};
let mut direct_delta = delta * scroll_speed;
if motion.continuous {
if motion.activated || motion.deactivated && !motion.released {
state.velocity = 0.0;
state.pending_delta = 0.0;
}
if motion.activated {
if matches!(ui.input(), blit::input::Input::Touch { .. }) {
let distance = libm::hypotf(motion.delta.x, motion.delta.y);
if distance > 0.0 {
direct_delta *= (1.0 - C::SLOP.to_f32() / distance).max(0.0);
}
} else {
state.sample_time = previous;
}
}
state.tracking = motion.active;
} else if moving {
state.velocity = 0.0;
state.tracking = false;
}
if motion.continuous && (motion.active || motion.released) {
let sample_time = state.sample_time.get_or_insert(previous.unwrap_or(now));
let sample_elapsed = now.saturating_sub(*sample_time).as_secs_f32();
if delta != 0.0 {
state.pending_delta += delta * scroll_speed;
if sample_elapsed > 0.0 {
let velocity = (state.pending_delta / sample_elapsed).clamp(-MAX_SCROLL_VELOCITY, MAX_SCROLL_VELOCITY);
state.velocity = if state.velocity == 0.0 {
velocity
} else {
(state.velocity + velocity) * 0.5
};
state.pending_delta = 0.0;
*sample_time = now;
}
} else if sample_elapsed >= 0.1 {
state.velocity = 0.0;
}
}
if !state.tracking && state.velocity != 0.0 {
let elapsed = if moving { 0.0 } else { elapsed };
let decay = libm::expf(-inertia_friction * elapsed);
let delta = state.velocity * (1.0 - decay) / inertia_friction;
state.velocity *= decay;
direct_delta += delta;
if state.velocity.abs() < MIN_SCROLL_VELOCITY {
state.velocity = 0.0;
} else {
ui.request_frame();
}
}
direct_delta
}
fn animate<C: Context, S: Local>(
state: &mut ScrollState<C::Scalar>,
ui: &mut Ui<'_, C, S>,
animation: Animation,
viewport_known: bool,
) {
let request = &mut state.request;
let target = match request.target {
Goal::None | Goal::Node(_) => return,
_ if !viewport_known => {
ui.request_frame();
return;
}
Goal::Offset(offset) => offset,
};
request.target = Goal::Offset(target);
let maximum = (state.content_extent - state.viewport_extent).max(C::Scalar::ZERO);
let goal = if target.is_finite() {
target
} else {
target.clamp(C::Scalar::ZERO, maximum)
};
let animator = request
.animator
.get_or_insert_with(|| Animator::new([state.offset], Animation::default()));
animator.advance([goal], [true], animation, AnimationOptions::default(), ui.time(), true);
let offset = animator.clamp(0, C::Scalar::ZERO, maximum, ui.time());
if animator.is_active() {
state.offset = offset;
ui.request_frame();
} else {
state.offset = target;
*request = Request::default();
}
}
fn move_by<T: Scalar>(state: &mut ScrollState<T>, amount: f32) {
let maximum = state.maximum_offset();
let whole = state.inertia.pixel_delta(amount);
let offset = state.offset.endpoint(whole);
state.offset = offset.clamp(T::ZERO, maximum);
if state.offset != offset
|| (state.offset == T::ZERO && state.inertia.remainder < 0.0)
|| (state.offset == maximum && state.inertia.remainder > 0.0)
{
state.inertia.remainder = 0.0;
state.inertia.velocity = 0.0;
}
}
const CONTENT: u8 = 0;
const TRACK: u8 = 1;
const THUMB: u8 = 2;
const MIN_SCROLL_VELOCITY: f32 = 5.0;
const MAX_SCROLL_VELOCITY: f32 = 12_000.0;
#[cfg(test)]
mod tests {
use std::cell::Cell;
use blit::{Constraints, FrameInfo, Size, Spring, Tree, input::Input};
use super::*;
use crate::test::TestContext;
#[test]
fn release_preserves_recent_velocity() {
for gap in [0, 16, 33, 100, 500] {
let mut tree = Tree::default();
let mut inertia = Inertia {
velocity: 1000.0,
tracking: true,
last_frame: Some(Duration::from_millis(64)),
sample_time: Some(Duration::from_millis(64)),
..Inertia::default()
};
tree.build(
&mut TestContext,
FrameInfo::new(Size::uniform(200.0)),
Duration::from_millis(64 + gap),
Input::None,
|mut ui: Ui<'_, TestContext>| {
content_motion(
&mut inertia,
&mut ui,
Axis::Vertical,
1.0,
2.5,
interact::scroll::Response {
continuous: true,
released: true,
deactivated: true,
..Default::default()
},
);
},
);
assert_eq!(inertia.velocity, if gap < 100 { 1000.0 } else { 0.0 });
}
}
#[test]
fn touch_motion_stops_and_survives_batched_release() {
use blit::input::TouchPhase;
for held in [false, true] {
let mut tree = Tree::default();
let mut state = ScrollState::<f32>::new();
let mut step = |millis, phase: Option<TouchPhase>, y| {
tree.build(
&mut TestContext,
FrameInfo::new(Size::uniform(200.0)),
Duration::from_millis(millis),
phase.map_or(Input::None, |phase| Input::Touch {
id: 1,
position: Point::new(50.0, y),
phase,
}),
|ui: Ui<'_, TestContext>| {
Scroll::new(&mut state)
.begin(ui)
.content(|mut ui| {
ui.measure(|_, bounds| bounds.constrain(Size::new(200.0, 4000.0)));
})
.scrollbar(|_| {}, |_, _| {})
},
);
tree.layout(&mut TestContext);
(state.offset, state.is_moving())
};
step(0, None, 0.0);
step(16, None, 0.0);
step(32, Some(TouchPhase::Down), 180.0);
let (offset, _) = step(48, Some(TouchPhase::Move), 150.0);
assert!((offset - 24.0).abs() < 0.001);
if held {
assert!(!step(500, Some(TouchPhase::Up), 150.0).1);
assert_eq!(step(516, None, 0.0).0, offset);
} else {
assert!(step(48, Some(TouchPhase::Up), 130.0).1);
let (coasting, _) = step(64, None, 0.0);
assert!(coasting > offset + 20.0);
assert_eq!(step(80, Some(TouchPhase::Down), 100.0), (coasting, false));
assert_eq!(step(96, None, 0.0), (coasting, false));
}
}
}
#[test]
fn scrollbars_appear_on_overflow_and_floating_ones_leave_the_content_width() {
for (floating, height, width) in [(false, 400.0, 199.0), (true, 400.0, 200.0), (false, 100.0, 199.0)] {
let mut tree = Tree::default();
let mut state = ScrollState::<f32>::new();
let mut step = || {
crate::test::step(&mut tree, Input::None, |ui: Ui<'_, TestContext>| {
let (area, track) = (Cell::new(None), Cell::new(None));
Scroll::new(&mut state)
.floating(floating)
.begin(ui)
.content(|mut ui| {
area.set(ui.area());
ui.measure(move |_, bounds| Size::new(bounds.max.width, height))
})
.scrollbar(
|ui| {
track.set(ui.area());
ui.constrain(Constraints {
min: Size::uniform(1.0),
max: Size::uniform(f32::INFINITY),
});
},
|_, _| {},
);
(area.get(), track.get())
})
};
step();
let (area, track) = step();
assert_eq!(area.unwrap().width, width);
let track = track.unwrap();
assert_eq!(track.y < 200.0 && track.height > 0.0, height > 200.0);
}
}
#[test]
fn requests_and_focus_reveal_content() {
let mut tree = Tree::default();
let mut state = ScrollState::<f32>::new();
let focused = Cell::new(None);
let target = Cell::new(None);
let mut step = |state: &mut ScrollState<f32>| {
for _ in 0..3 {
crate::test::step(&mut tree, Input::None, |ui: Ui<'_, TestContext>| {
Scroll::new(state)
.begin(ui)
.content(|ui| {
let mut rows = ui.layout(crate::layout::flex::column());
for index in 10..20u8 {
let mut row = rows.child_in(Scope::ROOT, index);
if index == 17 {
target.set(Some(row.id()));
}
row.interact(interact::focus());
if focused.get() == Some(index) {
row.focus();
}
row.measure(|_, bounds| bounds.constrain(Size::new(200.0, 100.0)));
}
})
.scrollbar(|_| {}, |_, _| {})
});
}
state.offset
};
step(&mut state);
state.reveal(target.get().unwrap());
assert_eq!(step(&mut state), 600.0);
assert!(!state.is_moving());
state.scroll_to(0.0);
step(&mut state);
focused.set(Some(17));
assert_eq!(step(&mut state), 600.0);
state.scroll_to(0.0);
assert_eq!(step(&mut state), 0.0);
}
#[test]
fn animated_requests_retarget_bound_and_settle() {
let mut tree = Tree::default();
let mut state = ScrollState {
content_extent: 1000.0,
viewport_extent: 100.0,
..ScrollState::default()
};
let spring = Spring::new(0.500, 0.3).rest(0.01, 0.01);
let mut step = |state: &mut ScrollState<f32>, animation: Animation, millis| {
tree.build(
&mut TestContext,
FrameInfo::new(Size::uniform(100.0)),
Duration::from_millis(millis),
Input::None,
|mut ui: Ui<'_, TestContext>| animate(state, &mut ui, animation, true),
);
tree.layout(&mut TestContext);
};
state.scroll_to(500.0);
step(&mut state, spring.into(), 0);
step(&mut state, spring.into(), 30);
let moving = state.offset;
assert!(moving > 0.0 && moving < 500.0);
state.scroll_to(0.0);
step(&mut state, spring.into(), 30);
assert_eq!(state.offset, moving);
step(&mut state, spring.into(), 31);
assert!(state.offset > moving);
state.scroll_to(10_000.0);
step(&mut state, spring.into(), 31);
step(&mut state, spring.into(), 2000);
move_by(&mut state, 0.0);
assert_eq!(state.offset, 900.0);
assert!(!state.is_moving());
assert!(state.request.animator.is_none());
state.scroll_to(300.0);
step(&mut state, Animation::default(), 2000);
assert_eq!(state.offset, 300.0);
assert!(!tree.has_pending_redraw());
}
}