use std::rc::Rc;
use std::time::Duration;
use waft_animation::Curve;
use waft_foundation::{
App, ChangeNotifier, ChangeNotifierData, CompleterFuture, Handle, Listener, OptionRetained,
};
use waft_gestures::{Drag, DragStartDetails};
use waft_painting::AxisDirection;
use waft_physics::near_equal;
use waft_rendering::{ScrollDirection, ViewportOffset};
use crate::widgets::scroll_activity::{
BallisticScrollActivity, DragScrollActivity, DrivenScrollActivity, HoldScrollActivity,
IdleScrollActivity, ScrollActivityDelegate, ScrollActivityRef, ScrollDragController,
ScrollHoldController,
};
use crate::widgets::scroll_context::ScrollContext;
use crate::widgets::scroll_physics::ScrollPhysicsRef;
use crate::widgets::scroll_position::{
AnyScrollPosition, ScrollPosition, ScrollPositionBase, ScrollPositionData,
};
use waft_foundation::Ref;
pub struct ScrollPositionWithSingleContextData {
held_previous_velocity: f64,
user_scroll_direction: ScrollDirection,
current_drag: Option<Ref<ScrollDragController>>,
}
impl ScrollPositionWithSingleContextData {
pub fn new() -> ScrollPositionWithSingleContextData {
ScrollPositionWithSingleContextData {
held_previous_velocity: 0.0,
user_scroll_direction: ScrollDirection::Idle,
current_drag: None,
}
}
}
impl Default for ScrollPositionWithSingleContextData {
fn default() -> ScrollPositionWithSingleContextData {
ScrollPositionWithSingleContextData::new()
}
}
#[macro_export]
macro_rules! scroll_position_with_single_context_accessors {
() => {
fn single_context_data(
self: ::waft_foundation::Handle<Self>,
app: &::waft_foundation::App,
) -> &$crate::ScrollPositionWithSingleContextData {
&app.get(self).single_context
}
fn single_context_data_mut(
self: ::waft_foundation::Handle<Self>,
app: &mut ::waft_foundation::App,
) -> &mut $crate::ScrollPositionWithSingleContextData {
&mut app.get_mut(self).single_context
}
};
}
pub trait ScrollPositionWithSingleContextLeaf: ScrollPosition + ScrollActivityDelegate {
fn single_context_data(self: Handle<Self>, app: &App) -> &ScrollPositionWithSingleContextData;
fn single_context_data_mut(
self: Handle<Self>,
app: &mut App,
) -> &mut ScrollPositionWithSingleContextData;
fn axis_direction(self: Handle<Self>, app: &App) -> AxisDirection {
ScrollPositionWithSingleContext::axis_direction(self, app)
}
fn set_pixels(self: Handle<Self>, app: &mut App, new_pixels: f64) -> f64 {
ScrollPositionWithSingleContext::set_pixels(self, app, new_pixels)
}
fn absorb(self: Handle<Self>, app: &mut App, other: AnyScrollPosition) {
ScrollPositionWithSingleContext::absorb(self, app, other);
}
fn apply_new_dimensions(self: Handle<Self>, app: &mut App) {
ScrollPositionWithSingleContext::apply_new_dimensions(self, app);
}
fn begin_activity(self: Handle<Self>, app: &mut App, new_activity: Option<ScrollActivityRef>) {
ScrollPositionWithSingleContext::begin_activity(self, app, new_activity);
}
fn apply_user_offset(self: Handle<Self>, app: &mut App, delta: f64) {
ScrollPositionWithSingleContext::apply_user_offset(self, app, delta);
}
fn go_idle(self: Handle<Self>, app: &mut App) {
ScrollPositionWithSingleContext::go_idle(self, app);
}
fn go_ballistic(self: Handle<Self>, app: &mut App, velocity: f64) {
ScrollPositionWithSingleContext::go_ballistic(self, app, velocity);
}
fn user_scroll_direction(self: Handle<Self>, app: &App) -> ScrollDirection {
self.single_context_data(app).user_scroll_direction
}
fn update_user_scroll_direction(self: Handle<Self>, app: &mut App, value: ScrollDirection) {
if ScrollPositionWithSingleContextLeaf::user_scroll_direction(self, app) == value {
return;
}
self.single_context_data_mut(app).user_scroll_direction = value;
self.did_update_scroll_direction(app, value);
}
fn animate_to(
self: Handle<Self>,
app: &mut App,
to: f64,
duration: Duration,
curve: Rc<dyn Curve>,
) -> CompleterFuture<()> {
ScrollPositionWithSingleContext::animate_to(self, app, to, duration, curve)
}
fn jump_to(self: Handle<Self>, app: &mut App, value: f64) {
ScrollPositionWithSingleContext::jump_to(self, app, value);
}
fn pointer_scroll(self: Handle<Self>, app: &mut App, delta: f64) {
ScrollPositionWithSingleContext::pointer_scroll(self, app, delta);
}
fn jump_to_without_settling(self: Handle<Self>, app: &mut App, value: f64) {
ScrollPositionWithSingleContext::jump_to_without_settling(self, app, value);
}
fn hold(
self: Handle<Self>,
app: &mut App,
hold_cancel_callback: Listener,
) -> Rc<dyn ScrollHoldController> {
ScrollPositionWithSingleContext::hold(self, app, hold_cancel_callback)
}
fn drag(
self: Handle<Self>,
app: &mut App,
details: DragStartDetails,
drag_cancel_callback: Listener,
) -> Rc<dyn Drag> {
ScrollPositionWithSingleContext::drag(self, app, details, drag_cancel_callback)
}
fn dispose(self: Handle<Self>, app: &mut App) {
ScrollPositionWithSingleContext::dispose(self, app);
}
fn debug_fill_description(self: Handle<Self>, app: &App, description: &mut Vec<String>) {
ScrollPositionWithSingleContext::debug_fill_description(self, app, description);
}
}
#[macro_export]
macro_rules! scroll_position_with_single_context_viewport_offset_overrides {
() => {
fn pixels(self: ::waft_foundation::Handle<Self>, app: &::waft_foundation::App) -> f64 {
$crate::ScrollPositionBase::pixels(self, app)
}
fn has_pixels(self: ::waft_foundation::Handle<Self>, app: &::waft_foundation::App) -> bool {
$crate::ScrollPositionBase::has_pixels(self, app)
}
fn apply_viewport_dimension(
self: ::waft_foundation::Handle<Self>,
app: &mut ::waft_foundation::App,
viewport_dimension: f64,
) -> bool {
$crate::ScrollPositionBase::apply_viewport_dimension(self, app, viewport_dimension)
}
fn apply_content_dimensions(
self: ::waft_foundation::Handle<Self>,
app: &mut ::waft_foundation::App,
min_scroll_extent: f64,
max_scroll_extent: f64,
) -> bool {
$crate::ScrollPositionBase::apply_content_dimensions(
self,
app,
min_scroll_extent,
max_scroll_extent,
)
}
fn correct_by(
self: ::waft_foundation::Handle<Self>,
app: &mut ::waft_foundation::App,
correction: f64,
) {
$crate::ScrollPositionBase::correct_by(self, app, correction);
}
fn jump_to(
self: ::waft_foundation::Handle<Self>,
app: &mut ::waft_foundation::App,
value: f64,
) {
$crate::ScrollPositionWithSingleContextLeaf::jump_to(self, app, value);
}
fn animate_to(
self: ::waft_foundation::Handle<Self>,
app: &mut ::waft_foundation::App,
to: f64,
duration: ::std::time::Duration,
curve: ::std::rc::Rc<dyn ::waft_animation::Curve>,
) -> ::waft_foundation::CompleterFuture<()> {
$crate::ScrollPositionWithSingleContextLeaf::animate_to(self, app, to, duration, curve)
}
fn move_to(
self: ::waft_foundation::Handle<Self>,
app: &mut ::waft_foundation::App,
to: f64,
duration: ::std::option::Option<::std::time::Duration>,
curve: ::std::option::Option<::std::rc::Rc<dyn ::waft_animation::Curve>>,
clamp: ::std::option::Option<bool>,
) -> ::waft_foundation::CompleterFuture<()> {
$crate::ScrollPositionBase::move_to(self, app, to, duration, curve, clamp)
}
fn user_scroll_direction(
self: ::waft_foundation::Handle<Self>,
app: &::waft_foundation::App,
) -> ::waft_rendering::ScrollDirection {
$crate::ScrollPositionWithSingleContextLeaf::user_scroll_direction(self, app)
}
fn allow_implicit_scrolling(
self: ::waft_foundation::Handle<Self>,
app: &::waft_foundation::App,
) -> bool {
$crate::ScrollPositionBase::allow_implicit_scrolling(self, app)
}
};
}
#[macro_export]
macro_rules! scroll_position_with_single_context_overrides {
() => {
$crate::scroll_position_accessors!();
fn axis_direction(
self: ::waft_foundation::Handle<Self>,
app: &::waft_foundation::App,
) -> ::waft_painting::AxisDirection {
$crate::ScrollPositionWithSingleContextLeaf::axis_direction(self, app)
}
fn set_pixels(
self: ::waft_foundation::Handle<Self>,
app: &mut ::waft_foundation::App,
new_pixels: f64,
) -> f64 {
$crate::ScrollPositionWithSingleContextLeaf::set_pixels(self, app, new_pixels)
}
fn absorb(
self: ::waft_foundation::Handle<Self>,
app: &mut ::waft_foundation::App,
other: $crate::AnyScrollPosition,
) {
$crate::ScrollPositionWithSingleContextLeaf::absorb(self, app, other);
}
fn apply_new_dimensions(
self: ::waft_foundation::Handle<Self>,
app: &mut ::waft_foundation::App,
) {
$crate::ScrollPositionWithSingleContextLeaf::apply_new_dimensions(self, app);
}
fn begin_activity(
self: ::waft_foundation::Handle<Self>,
app: &mut ::waft_foundation::App,
new_activity: ::std::option::Option<$crate::ScrollActivityRef>,
) {
$crate::ScrollPositionWithSingleContextLeaf::begin_activity(self, app, new_activity);
}
fn pointer_scroll(
self: ::waft_foundation::Handle<Self>,
app: &mut ::waft_foundation::App,
delta: f64,
) {
$crate::ScrollPositionWithSingleContextLeaf::pointer_scroll(self, app, delta);
}
fn jump_to_without_settling(
self: ::waft_foundation::Handle<Self>,
app: &mut ::waft_foundation::App,
value: f64,
) {
$crate::ScrollPositionWithSingleContextLeaf::jump_to_without_settling(self, app, value);
}
fn hold(
self: ::waft_foundation::Handle<Self>,
app: &mut ::waft_foundation::App,
hold_cancel_callback: ::waft_foundation::Listener,
) -> ::std::rc::Rc<dyn $crate::ScrollHoldController> {
$crate::ScrollPositionWithSingleContextLeaf::hold(self, app, hold_cancel_callback)
}
fn drag(
self: ::waft_foundation::Handle<Self>,
app: &mut ::waft_foundation::App,
details: ::waft_gestures::DragStartDetails,
drag_cancel_callback: ::waft_foundation::Listener,
) -> ::std::rc::Rc<dyn ::waft_gestures::Drag> {
$crate::ScrollPositionWithSingleContextLeaf::drag(
self,
app,
details,
drag_cancel_callback,
)
}
fn dispose(self: ::waft_foundation::Handle<Self>, app: &mut ::waft_foundation::App) {
$crate::ScrollPositionWithSingleContextLeaf::dispose(self, app);
}
fn debug_fill_description(
self: ::waft_foundation::Handle<Self>,
app: &::waft_foundation::App,
description: &mut ::std::vec::Vec<::std::string::String>,
) {
$crate::ScrollPositionWithSingleContextLeaf::debug_fill_description(
self,
app,
description,
);
}
};
}
#[macro_export]
macro_rules! scroll_position_with_single_context_delegate_overrides {
() => {
fn axis_direction(
self: ::waft_foundation::Handle<Self>,
app: &::waft_foundation::App,
) -> ::waft_painting::AxisDirection {
$crate::ScrollPositionWithSingleContextLeaf::axis_direction(self, app)
}
fn set_pixels(
self: ::waft_foundation::Handle<Self>,
app: &mut ::waft_foundation::App,
pixels: f64,
) -> f64 {
$crate::ScrollPositionWithSingleContextLeaf::set_pixels(self, app, pixels)
}
fn apply_user_offset(
self: ::waft_foundation::Handle<Self>,
app: &mut ::waft_foundation::App,
delta: f64,
) {
$crate::ScrollPositionWithSingleContextLeaf::apply_user_offset(self, app, delta);
}
fn go_idle(self: ::waft_foundation::Handle<Self>, app: &mut ::waft_foundation::App) {
$crate::ScrollPositionWithSingleContextLeaf::go_idle(self, app);
}
fn go_ballistic(
self: ::waft_foundation::Handle<Self>,
app: &mut ::waft_foundation::App,
velocity: f64,
) {
$crate::ScrollPositionWithSingleContextLeaf::go_ballistic(self, app, velocity);
}
};
}
pub struct ScrollPositionWithSingleContext {
change_notifier: ChangeNotifierData,
scroll_position: ScrollPositionData,
single_context: ScrollPositionWithSingleContextData,
}
impl ScrollPositionWithSingleContext {
pub fn new(
app: &mut App,
physics: ScrollPhysicsRef,
context: Rc<dyn ScrollContext>,
initial_pixels: Option<f64>,
keep_scroll_offset: bool,
old_position: Option<AnyScrollPosition>,
debug_label: Option<String>,
) -> Ref<ScrollPositionWithSingleContext> {
let scroll_position =
ScrollPositionData::new(app, physics, context, keep_scroll_offset, debug_label);
let this = app.create(ScrollPositionWithSingleContext {
change_notifier: ChangeNotifierData::new(),
scroll_position,
single_context: ScrollPositionWithSingleContextData::new(),
});
ScrollPositionWithSingleContext::init(this.handle(), app, initial_pixels, old_position);
this
}
pub fn init<P: ScrollPositionWithSingleContextLeaf>(
this: Handle<P>,
app: &mut App,
initial_pixels: Option<f64>,
old_position: Option<AnyScrollPosition>,
) {
ScrollPositionBase::init(this, app, old_position);
if !ViewportOffset::has_pixels(this, app)
&& let Some(initial_pixels) = initial_pixels
{
this.correct_pixels(app, initial_pixels);
}
if this.activity(app).is_none() {
ScrollActivityDelegate::go_idle(this, app);
}
debug_assert!(this.activity(app).is_some());
}
pub fn axis_direction<P: ScrollPositionWithSingleContextLeaf>(
this: Handle<P>,
app: &App,
) -> AxisDirection {
this.context(app).axis_direction(app)
}
pub fn set_pixels<P: ScrollPositionWithSingleContextLeaf>(
this: Handle<P>,
app: &mut App,
new_pixels: f64,
) -> f64 {
debug_assert!(
this.activity(app)
.expect("a position has an activity")
.is_scrolling(app)
);
ScrollPositionBase::set_pixels(this, app, new_pixels)
}
pub fn absorb<P: ScrollPositionWithSingleContextLeaf>(
this: Handle<P>,
app: &mut App,
other: AnyScrollPosition,
) {
ScrollPositionBase::absorb(this, app, other);
let Some(other) = other.downcast::<P>(app) else {
ScrollActivityDelegate::go_idle(this, app);
return;
};
let delegate = this.as_scroll_activity_delegate();
this.activity(app)
.expect("absorb adopts the other activity")
.update_delegate(app, delegate);
this.single_context_data_mut(app).user_scroll_direction =
other.single_context_data(app).user_scroll_direction;
debug_assert!(this.single_context_data(app).current_drag.is_none());
if let Some(current_drag) = other.single_context_data_mut(app).current_drag.take() {
current_drag.update_delegate(app, delegate);
this.single_context_data_mut(app).current_drag = Some(current_drag);
}
}
pub fn apply_new_dimensions<P: ScrollPositionWithSingleContextLeaf>(
this: Handle<P>,
app: &mut App,
) {
ScrollPositionBase::apply_new_dimensions(this, app);
let physics = this.physics(app);
let metrics = this.copy_with(app);
let can_drag = physics.should_accept_user_offset(&*metrics);
this.context(app).set_can_drag(app, can_drag);
}
pub fn begin_activity<P: ScrollPositionWithSingleContextLeaf>(
this: Handle<P>,
app: &mut App,
new_activity: Option<ScrollActivityRef>,
) {
this.single_context_data_mut(app).held_previous_velocity = 0.0;
let Some(new_activity) = new_activity else {
return;
};
debug_assert!(new_activity.delegate(app) == this.as_scroll_activity_delegate());
ScrollPositionBase::begin_activity(this, app, Some(new_activity));
if let Some(current_drag) = this.single_context_data(app).current_drag.handle() {
current_drag.dispose(app);
}
this.single_context_data_mut(app).current_drag = None;
if !this
.activity(app)
.expect("a position has an activity")
.is_scrolling(app)
{
this.update_user_scroll_direction(app, ScrollDirection::Idle);
}
}
pub fn apply_user_offset<P: ScrollPositionWithSingleContextLeaf>(
this: Handle<P>,
app: &mut App,
delta: f64,
) {
let direction = if delta > 0.0 {
ScrollDirection::Forward
} else {
ScrollDirection::Reverse
};
this.update_user_scroll_direction(app, direction);
let physics = this.physics(app);
let metrics = this.copy_with(app);
let new_pixels = ViewportOffset::pixels(this, app)
- physics.apply_physics_to_user_offset(&*metrics, delta);
ScrollPosition::set_pixels(this, app, new_pixels);
}
pub fn go_idle<P: ScrollPositionWithSingleContextLeaf>(this: Handle<P>, app: &mut App) {
let activity = IdleScrollActivity::new(app, this.as_scroll_activity_delegate());
ScrollPosition::begin_activity(this, app, Some(activity.into_erased()));
}
pub fn go_ballistic<P: ScrollPositionWithSingleContextLeaf>(
this: Handle<P>,
app: &mut App,
velocity: f64,
) {
debug_assert!(ViewportOffset::has_pixels(this, app));
let physics = this.physics(app);
let metrics = this.copy_with(app);
match physics.create_ballistic_simulation(&*metrics, velocity) {
Some(simulation) => {
let vsync = this.context(app).vsync();
let should_ignore_pointer = this.should_ignore_pointer(app);
let activity = BallisticScrollActivity::new(
app,
this.as_scroll_activity_delegate(),
simulation,
vsync,
should_ignore_pointer,
);
ScrollPosition::begin_activity(this, app, Some(activity.into_erased()));
}
None => ScrollActivityDelegate::go_idle(this, app),
}
}
pub fn animate_to<P: ScrollPositionWithSingleContextLeaf>(
this: Handle<P>,
app: &mut App,
to: f64,
duration: Duration,
curve: Rc<dyn Curve>,
) -> CompleterFuture<()> {
let physics = this.physics(app);
let metrics = this.copy_with(app);
if near_equal(
Some(to),
Some(ViewportOffset::pixels(this, app)),
physics.tolerance_for(&*metrics).distance,
) {
ViewportOffset::jump_to(this, app, to);
return CompleterFuture::ready(());
}
let from = ViewportOffset::pixels(this, app);
let vsync = this.context(app).vsync();
let activity = DrivenScrollActivity::new(
app,
this.as_scroll_activity_delegate(),
from,
to,
duration,
curve,
vsync,
);
ScrollPosition::begin_activity(this, app, Some(activity.erase()));
activity.done(app)
}
pub fn jump_to<P: ScrollPositionWithSingleContextLeaf>(
this: Handle<P>,
app: &mut App,
value: f64,
) {
ScrollActivityDelegate::go_idle(this, app);
if ViewportOffset::pixels(this, app) != value {
let old_pixels = ViewportOffset::pixels(this, app);
this.force_pixels(app, value);
this.did_start_scroll(app);
let delta = ViewportOffset::pixels(this, app) - old_pixels;
this.did_update_scroll_position_by(app, delta);
this.did_end_scroll(app);
}
ScrollActivityDelegate::go_ballistic(this, app, 0.0);
}
pub fn pointer_scroll<P: ScrollPositionWithSingleContextLeaf>(
this: Handle<P>,
app: &mut App,
delta: f64,
) {
if delta == 0.0 {
ScrollActivityDelegate::go_ballistic(this, app, 0.0);
return;
}
let target_pixels = (ViewportOffset::pixels(this, app) + delta)
.max(this.min_scroll_extent(app))
.min(this.max_scroll_extent(app));
if target_pixels != ViewportOffset::pixels(this, app) {
ScrollActivityDelegate::go_idle(this, app);
let direction = if -delta > 0.0 {
ScrollDirection::Forward
} else {
ScrollDirection::Reverse
};
this.update_user_scroll_direction(app, direction);
let old_pixels = ViewportOffset::pixels(this, app);
this.is_scrolling_notifier(app).set_value(app, true);
this.force_pixels(app, target_pixels);
this.did_start_scroll(app);
let moved = ViewportOffset::pixels(this, app) - old_pixels;
this.did_update_scroll_position_by(app, moved);
this.did_end_scroll(app);
ScrollActivityDelegate::go_ballistic(this, app, 0.0);
}
}
pub fn jump_to_without_settling<P: ScrollPositionWithSingleContextLeaf>(
this: Handle<P>,
app: &mut App,
value: f64,
) {
ScrollActivityDelegate::go_idle(this, app);
if ViewportOffset::pixels(this, app) != value {
let old_pixels = ViewportOffset::pixels(this, app);
this.force_pixels(app, value);
this.did_start_scroll(app);
let delta = ViewportOffset::pixels(this, app) - old_pixels;
this.did_update_scroll_position_by(app, delta);
this.did_end_scroll(app);
}
}
pub fn hold<P: ScrollPositionWithSingleContextLeaf>(
this: Handle<P>,
app: &mut App,
hold_cancel_callback: Listener,
) -> Rc<dyn ScrollHoldController> {
let previous_velocity = this
.activity(app)
.expect("a position has an activity")
.velocity(app);
let hold_activity = HoldScrollActivity::new(
app,
this.as_scroll_activity_delegate(),
Some(hold_cancel_callback),
);
ScrollPosition::begin_activity(this, app, Some(hold_activity.erase()));
this.single_context_data_mut(app).held_previous_velocity = previous_velocity;
Rc::new(hold_activity)
}
pub fn drag<P: ScrollPositionWithSingleContextLeaf>(
this: Handle<P>,
app: &mut App,
details: DragStartDetails,
drag_cancel_callback: Listener,
) -> Rc<dyn Drag> {
let physics = this.physics(app);
let held_previous_velocity = this.single_context_data(app).held_previous_velocity;
let drag = ScrollDragController::new(
app,
this.as_scroll_activity_delegate(),
details,
Some(drag_cancel_callback),
Some(physics.carried_momentum(held_previous_velocity)),
physics.drag_start_distance_motion_threshold(),
);
let activity =
DragScrollActivity::new(app, this.as_scroll_activity_delegate(), drag.clone());
ScrollPosition::begin_activity(this, app, Some(activity.into_erased()));
debug_assert!(this.single_context_data(app).current_drag.is_none());
this.single_context_data_mut(app).current_drag = Some(drag.clone());
Rc::new(drag)
}
pub fn dispose<P: ScrollPositionWithSingleContextLeaf>(this: Handle<P>, app: &mut App) {
if let Some(current_drag) = this.single_context_data(app).current_drag.handle() {
current_drag.dispose(app);
}
this.single_context_data_mut(app).current_drag = None;
ScrollPositionBase::dispose(this, app);
}
pub fn debug_fill_description<P: ScrollPositionWithSingleContextLeaf>(
this: Handle<P>,
app: &App,
description: &mut Vec<String>,
) {
ScrollPositionBase::debug_fill_description(this, app, description);
description.push(this.context(app).type_name().to_string());
description.push(format!("{:?}", this.physics(app)));
description.push(
this.activity(app)
.map_or_else(|| "null".to_string(), |activity| activity.describe(app)),
);
description.push(format!(
"{:?}",
ViewportOffset::user_scroll_direction(this, app)
));
}
}
impl ChangeNotifier for ScrollPositionWithSingleContext {
fn change_notifier_data(&self) -> &ChangeNotifierData {
&self.change_notifier
}
fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
&mut self.change_notifier
}
}
impl ViewportOffset for ScrollPositionWithSingleContext {
crate::scroll_position_with_single_context_viewport_offset_overrides!();
}
impl ScrollPosition for ScrollPositionWithSingleContext {
crate::scroll_position_with_single_context_overrides!();
}
impl ScrollActivityDelegate for ScrollPositionWithSingleContext {
crate::scroll_position_with_single_context_delegate_overrides!();
}
impl ScrollPositionWithSingleContextLeaf for ScrollPositionWithSingleContext {
crate::scroll_position_with_single_context_accessors!();
}
#[cfg(test)]
mod tests {
use std::cell::Cell;
use waft_foundation::AppCell;
use waft_animation::Curves;
use waft_embedder::Offset;
use waft_foundation::ListenableObject;
use waft_gestures::{DragEndDetails, DragUpdateDetails, Velocity};
use waft_scheduler::SchedulerBinding;
use super::*;
use crate::test_harness::pump_every_view;
use crate::test_harness::{ScrollHarness, mount_scroll_harness};
use crate::widgets::scroll_physics::{BouncingScrollPhysics, ClampingScrollPhysics};
fn position(
app: &mut App,
harness: &ScrollHarness,
physics: ScrollPhysicsRef,
) -> Ref<ScrollPositionWithSingleContext> {
ScrollPositionWithSingleContext::new(
app,
physics,
Rc::clone(&harness.scroll_context),
Some(0.0),
true,
None,
None,
)
}
fn lay_out(app: &mut App, position: Handle<ScrollPositionWithSingleContext>) {
assert!(position.apply_viewport_dimension(app, 100.0));
assert!(position.apply_content_dimensions(app, 0.0, 400.0));
app.drain_microtasks();
}
fn drag_by(delta: f64) -> DragUpdateDetails {
DragUpdateDetails::new(
Offset::ZERO,
None,
Some(Duration::ZERO),
Offset::new(0.0, delta),
Some(delta),
None,
)
}
fn is_scrolling(app: &App, position: Handle<ScrollPositionWithSingleContext>) -> bool {
*app.get(position.is_scrolling_notifier(app)).value()
}
#[test]
fn applying_dimensions_makes_the_metrics_available_and_move_to_clamps() {
let cell = AppCell::new();
let mut app = cell.borrow_mut();
let harness = mount_scroll_harness(&mut app);
let kept = position(&mut app, &harness, Rc::new(ClampingScrollPhysics::new()));
let position = kept.handle();
assert!(!position.have_dimensions(&app));
assert_eq!(ViewportOffset::pixels(position, &app), 0.0);
lay_out(&mut app, position);
assert!(position.have_dimensions(&app));
assert_eq!(position.min_scroll_extent(&app), 0.0);
assert_eq!(position.max_scroll_extent(&app), 400.0);
assert_eq!(position.viewport_dimension(&app), 100.0);
assert_eq!(position.extent_inside(&app), 100.0);
assert_eq!(position.extent_after(&app), 400.0);
assert_eq!(app.get(&harness.context).can_drag, vec![true]);
position.move_to(&mut app, 500.0, None, None, None);
assert_eq!(ViewportOffset::pixels(position, &app), 400.0);
position.move_to(&mut app, -50.0, None, None, None);
assert_eq!(ViewportOffset::pixels(position, &app), 0.0);
assert!(!position.out_of_range(&app));
}
#[test]
fn jump_to_notifies_listeners_and_dispatches_start_update_end() {
let cell = AppCell::new();
let mut app = cell.borrow_mut();
let harness = mount_scroll_harness(&mut app);
let kept = position(&mut app, &harness, Rc::new(ClampingScrollPhysics::new()));
let position = kept.handle();
lay_out(&mut app, position);
harness.notifications.borrow_mut().clear();
let notified = Rc::new(Cell::new(0));
let counter = notified.clone();
ListenableObject::add_listener(
position,
&mut app,
Listener::new(move |_app| counter.set(counter.get() + 1)),
);
ViewportOffset::jump_to(position, &mut app, 120.0);
assert_eq!(ViewportOffset::pixels(position, &app), 120.0);
assert_eq!(notified.get(), 1);
assert_eq!(
*harness.notifications.borrow(),
["start", "update 120.0", "end"]
);
assert_eq!(app.get(&harness.context).saved_offsets, vec![120.0]);
assert!(!is_scrolling(&app, position));
}
#[test]
fn animate_to_drives_the_position_through_the_ticker() {
let cell = AppCell::new();
let mut app = cell.borrow_mut();
let harness = mount_scroll_harness(&mut app);
let kept = position(&mut app, &harness, Rc::new(ClampingScrollPhysics::new()));
let position = kept.handle();
lay_out(&mut app, position);
ViewportOffset::animate_to(
position,
&mut app,
200.0,
Duration::from_millis(100),
Curves::linear(),
);
assert!(is_scrolling(&app, position));
pump_every_view(&mut app, Duration::ZERO);
assert_eq!(ViewportOffset::pixels(position, &app), 0.0);
pump_every_view(&mut app, Duration::from_millis(50));
assert!((ViewportOffset::pixels(position, &app) - 100.0).abs() < 0.001);
pump_every_view(&mut app, Duration::from_millis(100));
assert_eq!(ViewportOffset::pixels(position, &app), 200.0);
}
#[test]
fn animate_to_resolves_its_future_when_the_activity_ends() {
let cell = AppCell::new();
let mut app = cell.borrow_mut();
let harness = mount_scroll_harness(&mut app);
let kept = position(&mut app, &harness, Rc::new(ClampingScrollPhysics::new()));
let position = kept.handle();
lay_out(&mut app, position);
let done = ViewportOffset::animate_to(
position,
&mut app,
200.0,
Duration::from_millis(100),
Curves::linear(),
);
assert!(!done.is_completed());
let heard = Rc::new(Cell::new(false));
let flag = Rc::clone(&heard);
done.clone().then(&mut app, move |_app, ()| flag.set(true));
pump_every_view(&mut app, Duration::ZERO);
pump_every_view(&mut app, Duration::from_millis(50));
assert!(!done.is_completed(), "still animating");
pump_every_view(&mut app, Duration::from_millis(100));
assert_eq!(ViewportOffset::pixels(position, &app), 200.0);
assert!(
!done.is_completed(),
"at the target, but the simulation ends after it"
);
SchedulerBinding::handle_begin_frame(&mut app, &[], Some(Duration::from_millis(150)));
assert!(
!done.is_completed(),
"the activity ends on the microtask queue, after the frame"
);
app.drain_microtasks();
assert!(done.is_completed());
assert!(heard.get(), "the listener ran in the same drain");
assert!(!is_scrolling(&app, position));
}
#[test]
fn a_task_awaiting_animate_to_resumes_at_the_checkpoint() {
let cell = AppCell::new();
let mut app = cell.borrow_mut();
let harness = mount_scroll_harness(&mut app);
let kept = position(&mut app, &harness, Rc::new(ClampingScrollPhysics::new()));
let position = kept.handle();
lay_out(&mut app, position);
let done = ViewportOffset::animate_to(
position,
&mut app,
200.0,
Duration::from_millis(100),
Curves::linear(),
);
let resumed = Rc::new(Cell::new(false));
let flag = Rc::clone(&resumed);
app.spawn(async move |_cx| {
done.await;
flag.set(true);
});
pump_every_view(&mut app, Duration::ZERO);
drop(app);
cell.checkpoint();
assert!(!resumed.get(), "pending: the animation is still running");
pump_every_view(&mut cell.borrow_mut(), Duration::from_millis(100));
pump_every_view(&mut cell.borrow_mut(), Duration::from_millis(150));
assert!(!resumed.get(), "a task resumes only at the checkpoint");
cell.checkpoint();
assert!(resumed.get());
}
#[test]
fn an_interrupted_animation_resolves_animate_to_as_well() {
let cell = AppCell::new();
let mut app = cell.borrow_mut();
let harness = mount_scroll_harness(&mut app);
let kept = position(&mut app, &harness, Rc::new(ClampingScrollPhysics::new()));
let position = kept.handle();
lay_out(&mut app, position);
let done = ViewportOffset::animate_to(
position,
&mut app,
200.0,
Duration::from_millis(100),
Curves::linear(),
);
pump_every_view(&mut app, Duration::ZERO);
pump_every_view(&mut app, Duration::from_millis(50));
assert!(!done.is_completed());
ViewportOffset::jump_to(position, &mut app, 0.0);
assert!(done.is_completed(), "the driven activity was disposed");
assert_eq!(ViewportOffset::pixels(position, &app), 0.0);
pump_every_view(&mut app, Duration::from_millis(100));
assert_eq!(
ViewportOffset::pixels(position, &app),
0.0,
"the animation is gone"
);
}
#[test]
fn animate_to_within_the_tolerance_jumps_instead() {
let cell = AppCell::new();
let mut app = cell.borrow_mut();
let harness = mount_scroll_harness(&mut app);
let kept = position(&mut app, &harness, Rc::new(ClampingScrollPhysics::new()));
let position = kept.handle();
lay_out(&mut app, position);
harness.notifications.borrow_mut().clear();
let done = ViewportOffset::animate_to(
position,
&mut app,
0.000_001,
Duration::from_millis(100),
Curves::linear(),
);
assert_eq!(ViewportOffset::pixels(position, &app), 0.000_001);
assert!(!is_scrolling(&app, position));
assert!(done.is_completed(), "a jump hands back a resolved future");
}
#[test]
fn a_clamping_drag_scrolls_the_position_and_settles_at_once() {
let cell = AppCell::new();
let mut app = cell.borrow_mut();
let harness = mount_scroll_harness(&mut app);
let kept = position(&mut app, &harness, Rc::new(ClampingScrollPhysics::new()));
let position = kept.handle();
lay_out(&mut app, position);
harness.notifications.borrow_mut().clear();
let _hold = ScrollPosition::hold(position, &mut app, Listener::new(|_app| {}));
let drag = ScrollPosition::drag(
position,
&mut app,
DragStartDetails::default(),
Listener::new(|_app| {}),
);
drag.update(&mut app, drag_by(-30.0));
assert_eq!(ViewportOffset::pixels(position, &app), 30.0);
assert_eq!(
ViewportOffset::user_scroll_direction(position, &app),
ScrollDirection::Reverse
);
assert!(is_scrolling(&app, position));
drag.end(
&mut app,
DragEndDetails::new(Offset::ZERO, None, Velocity::ZERO, Some(0.0)),
);
assert_eq!(ViewportOffset::pixels(position, &app), 30.0);
assert!(!is_scrolling(&app, position));
assert_eq!(
ViewportOffset::user_scroll_direction(position, &app),
ScrollDirection::Idle
);
assert_eq!(
*harness.notifications.borrow(),
["start", "user Reverse", "update 30.0", "end", "user Idle"]
);
}
#[test]
fn a_bouncing_drag_overscrolls_and_springs_back_over_frames() {
let cell = AppCell::new();
let mut app = cell.borrow_mut();
let harness = mount_scroll_harness(&mut app);
let kept = position(&mut app, &harness, Rc::new(BouncingScrollPhysics::new()));
let position = kept.handle();
lay_out(&mut app, position);
let drag = ScrollPosition::drag(
position,
&mut app,
DragStartDetails::default(),
Listener::new(|_app| {}),
);
drag.update(&mut app, drag_by(-500.0));
assert!(ViewportOffset::pixels(position, &app) > 400.0);
assert!(position.out_of_range(&app));
drag.end(
&mut app,
DragEndDetails::new(Offset::ZERO, None, Velocity::ZERO, Some(0.0)),
);
assert!(position.out_of_range(&app));
assert!(is_scrolling(&app, position));
for frame in 0..200 {
pump_every_view(&mut app, Duration::from_millis(16 * frame));
if !is_scrolling(&app, position) {
break;
}
}
assert!(!is_scrolling(&app, position));
assert!((ViewportOffset::pixels(position, &app) - 400.0).abs() < 1.0);
}
#[test]
fn a_new_position_absorbs_the_old_one() {
let cell = AppCell::new();
let mut app = cell.borrow_mut();
let harness = mount_scroll_harness(&mut app);
let kept_old = position(&mut app, &harness, Rc::new(ClampingScrollPhysics::new()));
let old = kept_old.handle();
lay_out(&mut app, old);
ViewportOffset::jump_to(old, &mut app, 75.0);
let kept_new = ScrollPositionWithSingleContext::new(
&mut app,
Rc::new(ClampingScrollPhysics::new()),
Rc::clone(&harness.scroll_context),
Some(0.0),
true,
Some(old.as_scroll_position()),
None,
);
let new = kept_new.handle();
assert_eq!(ViewportOffset::pixels(new, &app), 75.0);
assert_eq!(new.max_scroll_extent(&app), 400.0);
assert!(new.activity(&app).is_some());
assert!(old.activity(&app).is_none());
}
#[test]
fn a_pointer_scroll_moves_the_position_within_the_extents() {
let cell = AppCell::new();
let mut app = cell.borrow_mut();
let harness = mount_scroll_harness(&mut app);
let kept = position(&mut app, &harness, Rc::new(ClampingScrollPhysics::new()));
let position = kept.handle();
lay_out(&mut app, position);
harness.notifications.borrow_mut().clear();
ScrollPosition::pointer_scroll(position, &mut app, 60.0);
assert_eq!(ViewportOffset::pixels(position, &app), 60.0);
assert_eq!(
*harness.notifications.borrow(),
["user Reverse", "start", "update 60.0", "end", "user Idle"]
);
ScrollPosition::pointer_scroll(position, &mut app, 1000.0);
assert_eq!(ViewportOffset::pixels(position, &app), 400.0);
}
#[test]
fn the_description_names_the_context_the_physics_and_the_activity() {
let cell = AppCell::new();
let mut app = cell.borrow_mut();
let harness = mount_scroll_harness(&mut app);
let kept = position(&mut app, &harness, Rc::new(ClampingScrollPhysics::new()));
let position = kept.handle();
lay_out(&mut app, position);
let description = position.to_string(&app);
assert!(description.contains("offset: 0.0"), "{description}");
assert!(description.contains("range: 0.0..400.0"), "{description}");
assert!(description.contains("viewport: 100.0"), "{description}");
assert!(description.contains("TestScrollContext"), "{description}");
assert!(
description.contains("ClampingScrollPhysics"),
"{description}"
);
assert!(description.contains("IdleScrollActivity"), "{description}");
}
}