use std::cell::Cell;
use std::fmt::{self, Debug};
use std::rc::Rc;
use std::time::Duration;
use waft_animation::{
Animation, AnimationBehavior, AnimationController, AnimationRef, AnimationStatus,
AnimationStatusListener, AnyAnimation, CurvedAnimation, Curves, Drive, Tween,
};
use waft_embedder::{Canvas, Clip, ClipOp, Color, Offset, Paint, Rect, Size, clamp_double};
use waft_foundation::{
App, ChangeNotifier, ChangeNotifierData, DiagnosticPropertiesBuilder, EnumProperty, Handle,
Listenable, ListenableObject, Listener, MessageProperty, OptionRetained, Timer, ValueNotifier,
};
use waft_painting::{Axis, AxisDirection, ColorProperty, axis_direction_to_axis};
use waft_physics::{Simulation, SpringDescription, SpringSimulation, Tolerance, near_equal};
use waft_rendering::{
CustomPainter, GrowthDirection, TickerProviderRef, apply_growth_direction_to_axis_direction,
};
use waft_scheduler::{FrameCallback, Ticker, TickerCallback, TickerProvider, TickerProviderObject};
use crate::framework::{
BuildContext, IntoWidget, KeyRef, Notification, State, StateData, StatefulWidget, WidgetRef,
};
use crate::widgets::basic::{ClipRect, CustomPaint, RepaintBoundary, SizedBox};
use crate::widgets::media_query::MediaQuery;
use crate::widgets::notification_listener::NotificationListener;
use crate::widgets::scroll_notification::{
OverscrollNotification, ScrollEndNotification, ScrollNotification, ScrollNotificationPredicate,
ScrollStartNotification, ScrollUpdateNotification, ViewportNotificationData,
ViewportNotificationMixin, default_scroll_notification_predicate,
};
use crate::widgets::stretch_effect::StretchEffect;
use crate::widgets::ticker_provider::{TickerProviderStateMixin, TickerProviderStateMixinData};
use crate::widgets::transitions::AnimatedBuilder;
use waft_foundation::Ref;
pub struct GlowingOverscrollIndicator {
pub key: Option<KeyRef>,
pub show_leading: bool,
pub show_trailing: bool,
pub axis_direction: AxisDirection,
pub color: Color,
pub notification_predicate: ScrollNotificationPredicate,
pub child: Option<WidgetRef>,
}
impl GlowingOverscrollIndicator {
pub fn new(axis_direction: AxisDirection, color: Color) -> GlowingOverscrollIndicator {
GlowingOverscrollIndicator {
key: None,
show_leading: true,
show_trailing: true,
axis_direction,
color,
notification_predicate: Rc::new(default_scroll_notification_predicate),
child: None,
}
}
pub fn key(mut self, key: KeyRef) -> GlowingOverscrollIndicator {
self.key = Some(key);
self
}
pub fn show_leading(mut self, show_leading: bool) -> GlowingOverscrollIndicator {
self.show_leading = show_leading;
self
}
pub fn show_trailing(mut self, show_trailing: bool) -> GlowingOverscrollIndicator {
self.show_trailing = show_trailing;
self
}
pub fn notification_predicate(
mut self,
notification_predicate: ScrollNotificationPredicate,
) -> GlowingOverscrollIndicator {
self.notification_predicate = notification_predicate;
self
}
#[cfg_attr(debug_assertions, track_caller)]
pub fn child<K>(mut self, child: impl IntoWidget<K>) -> GlowingOverscrollIndicator {
self.child = Some(child.into_widget());
self
}
pub fn axis(&self) -> Axis {
axis_direction_to_axis(self.axis_direction)
}
}
impl Debug for GlowingOverscrollIndicator {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let show_description = match (self.show_leading, self.show_trailing) {
(true, true) => "both sides",
(true, false) => "leading side only",
(false, true) => "trailing side only",
(false, false) => "neither side (!)",
};
f.debug_struct("GlowingOverscrollIndicator")
.field("axisDirection", &self.axis_direction)
.field("show", &show_description)
.field("color", &self.color)
.finish_non_exhaustive()
}
}
impl StatefulWidget for GlowingOverscrollIndicator {
type State = GlowingOverscrollIndicatorState;
fn key(&self) -> Option<&KeyRef> {
self.key.as_ref()
}
fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
properties.add(EnumProperty::new("axisDirection", self.axis_direction));
let show_description = match (self.show_leading, self.show_trailing) {
(true, true) => "both sides",
(true, false) => "leading side only",
(false, true) => "trailing side only",
(false, false) => "neither side (!)",
};
properties.add(MessageProperty::new("show", show_description));
properties.add(ColorProperty::new("color", self.color).with_show_name(false));
}
fn create_state(&self) -> GlowingOverscrollIndicatorState {
GlowingOverscrollIndicatorState {
state: StateData::new(),
ticker_provider: TickerProviderStateMixinData::new(),
leading_controller: None,
trailing_controller: None,
leading_and_trailing_listener: None,
accepted: [true, true],
}
}
}
pub struct GlowingOverscrollIndicatorState {
state: StateData<GlowingOverscrollIndicator>,
ticker_provider: TickerProviderStateMixinData,
leading_controller: Option<Ref<GlowController>>,
trailing_controller: Option<Ref<GlowController>>,
leading_and_trailing_listener: Option<Rc<dyn Listenable>>,
accepted: [bool; 2],
}
impl GlowingOverscrollIndicatorState {
fn leading_controller(self: Handle<Self>, app: &App) -> Handle<GlowController> {
app.get(self)
.leading_controller
.handle()
.expect("the controllers are made in init_state")
}
fn trailing_controller(self: Handle<Self>, app: &App) -> Handle<GlowController> {
app.get(self)
.trailing_controller
.handle()
.expect("the controllers are made in init_state")
}
fn handle_scroll_notification(
self: Handle<Self>,
app: &mut App,
notification: &dyn ScrollNotification,
) -> bool {
let widget = self.widget(app);
let notification_predicate = Rc::clone(&widget.notification_predicate);
let axis = widget.axis();
if !notification_predicate(notification) {
return false;
}
let metrics = Rc::clone(notification.metrics());
if metrics.axis() != axis {
return false;
}
let leading_controller = self.leading_controller(app);
let trailing_controller = self.trailing_controller(app);
let leading = app.get_mut(leading_controller);
leading.paint_offset_scroll_pixels = -f64::min(
metrics.pixels() - metrics.min_scroll_extent(),
leading.paint_offset,
);
let trailing = app.get_mut(trailing_controller);
trailing.paint_offset_scroll_pixels = -f64::min(
metrics.max_scroll_extent() - metrics.pixels(),
trailing.paint_offset,
);
let any = notification.as_any();
if let Some(notification) = any.downcast_ref::<OverscrollNotification>() {
let controller = if notification.overscroll < 0.0 {
Some(leading_controller)
} else if notification.overscroll > 0.0 {
Some(trailing_controller)
} else {
debug_assert!(false);
None
};
let is_leading = controller == Some(leading_controller);
let confirmation_notification = OverscrollIndicatorNotification::new(is_leading);
confirmation_notification.dispatch(app, Some(self.context(app)));
let accepted = confirmation_notification.accepted.get();
app.get_mut(self).accepted[is_leading as usize] = accepted;
if accepted {
let controller = controller.expect("an overscroll is on one side");
app.get_mut(controller).paint_offset = confirmation_notification.paint_offset.get();
}
debug_assert!(controller.is_some());
if app.get(self).accepted[is_leading as usize] {
let controller = controller.expect("an overscroll is on one side");
if notification.velocity != 0.0 {
debug_assert!(notification.drag_details.is_none());
controller.absorb_impact(app, notification.velocity.abs());
} else {
debug_assert!(notification.overscroll != 0.0);
if let Some(drag_details) = ¬ification.drag_details {
let renderer = notification
.context()
.expect("a scroll notification carries the scrollable's context")
.find_render_object(app)
.expect("the scrollable has a render object")
.as_box()
.expect("the scrollable's render object is a box");
debug_assert!(renderer.has_size(app));
let size = renderer.size(app);
let position =
renderer.global_to_local(app, drag_details.global_position, None);
match notification.metrics().axis() {
Axis::Horizontal => controller.pull(
app,
notification.overscroll.abs(),
size.width(),
clamp_double(position.dy(), 0.0, size.height()),
size.height(),
),
Axis::Vertical => controller.pull(
app,
notification.overscroll.abs(),
size.height(),
clamp_double(position.dx(), 0.0, size.width()),
size.width(),
),
}
}
}
}
} else if any
.downcast_ref::<ScrollEndNotification>()
.is_some_and(|notification| notification.drag_details.is_some())
|| any
.downcast_ref::<ScrollUpdateNotification>()
.is_some_and(|notification| notification.drag_details.is_some())
{
leading_controller.scroll_end(app);
trailing_controller.scroll_end(app);
}
false
}
}
impl Debug for GlowingOverscrollIndicatorState {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("GlowingOverscrollIndicatorState")
.finish_non_exhaustive()
}
}
impl TickerProviderStateMixin for GlowingOverscrollIndicatorState {
fn ticker_provider_data(self: Handle<Self>, app: &App) -> &TickerProviderStateMixinData {
&app.get(self).ticker_provider
}
fn ticker_provider_data_mut(
self: Handle<Self>,
app: &mut App,
) -> &mut TickerProviderStateMixinData {
&mut app.get_mut(self).ticker_provider
}
}
impl TickerProviderObject for GlowingOverscrollIndicatorState {
fn create_ticker(self: Handle<Self>, app: &mut App, on_tick: TickerCallback) -> Ref<Ticker> {
TickerProviderStateMixin::create_ticker(self, app, on_tick)
}
}
impl State for GlowingOverscrollIndicatorState {
type Widget = GlowingOverscrollIndicator;
crate::state_accessors!();
fn init_state(self: Handle<Self>, app: &mut App) {
let widget = self.widget(app);
let (color, axis) = (widget.color, widget.axis());
let leading_controller =
GlowController::new(app, TickerProviderRef::new(self), color, axis);
let trailing_controller =
GlowController::new(app, TickerProviderRef::new(self), color, axis);
let listener: Rc<dyn Listenable> = Rc::new(waft_foundation::MergingListenable::new(vec![
Some(Rc::new(leading_controller.clone())),
Some(Rc::new(trailing_controller.clone())),
]));
let state = app.get_mut(self);
state.leading_controller = Some(leading_controller);
state.trailing_controller = Some(trailing_controller);
state.leading_and_trailing_listener = Some(listener);
}
fn did_update_widget(
self: Handle<Self>,
app: &mut App,
old_widget: &GlowingOverscrollIndicator,
) {
let widget = self.widget(app);
let (color, axis) = (widget.color, widget.axis());
if old_widget.color != color || old_widget.axis() != axis {
let leading_controller = self.leading_controller(app);
let trailing_controller = self.trailing_controller(app);
leading_controller.set_color(app, color);
leading_controller.set_axis(app, axis);
trailing_controller.set_color(app, color);
trailing_controller.set_axis(app, axis);
}
}
fn activate(self: Handle<Self>, app: &mut App) {
TickerProviderStateMixin::activate(self, app);
}
fn dispose(self: Handle<Self>, app: &mut App) {
self.leading_controller(app).dispose(app);
self.trailing_controller(app).dispose(app);
TickerProviderStateMixin::dispose(self, app);
}
fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
let widget = self.widget(app);
let state = app.get(self);
let painter = GlowingOverscrollIndicatorPainter {
leading_controller: if widget.show_leading {
state.leading_controller.clone()
} else {
None
},
trailing_controller: if widget.show_trailing {
state.trailing_controller.clone()
} else {
None
},
axis_direction: widget.axis_direction,
repaint: state.leading_and_trailing_listener.clone(),
};
let mut child_boundary = RepaintBoundary::new();
if let Some(child) = widget.child.clone() {
child_boundary = child_boundary.child(child);
}
NotificationListener::<dyn ScrollNotification>::new(
RepaintBoundary::new().child(
CustomPaint::new()
.foreground_painter(painter)
.child(child_boundary),
),
)
.on_notification(
move |app: &mut App, notification: &dyn ScrollNotification| {
self.handle_scroll_notification(app, notification)
},
)
.into_widget()
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum GlowState {
Idle,
Absorb,
Pull,
Recede,
}
struct GlowController {
change_notifier: ChangeNotifierData,
state: GlowState,
glow_controller: Ref<AnimationController>,
pull_recede_timer: Option<Timer>,
paint_offset: f64,
paint_offset_scroll_pixels: f64,
decelerator: Option<Ref<CurvedAnimation>>,
glow_opacity_tween: Ref<Tween<f64>>,
glow_opacity: Option<AnimationRef<f64>>,
glow_size_tween: Ref<Tween<f64>>,
glow_size: Option<AnimationRef<f64>>,
displacement_ticker: Option<Ref<Ticker>>,
displacement_ticker_last_elapsed: Option<Duration>,
displacement_target: f64,
displacement: f64,
pull_distance: f64,
color: Color,
axis: Axis,
}
impl GlowController {
const RECEDE_TIME: Duration = Duration::from_millis(600);
const PULL_TIME: Duration = Duration::from_millis(167);
const PULL_HOLD_TIME: Duration = Duration::from_millis(167);
const PULL_DECAY_TIME: Duration = Duration::from_millis(2000);
const MAX_OPACITY: f64 = 0.5;
const PULL_OPACITY_GLOW_FACTOR: f64 = 0.8;
const VELOCITY_GLOW_FACTOR: f64 = 0.00006;
const SQRT3: f64 = 1.73205080757; const WIDTH_TO_HEIGHT_FACTOR: f64 = (3.0 / 4.0) * (2.0 - GlowController::SQRT3);
const MIN_VELOCITY: f64 = 100.0; const MAX_VELOCITY: f64 = 10000.0;
fn cross_axis_half_time() -> Duration {
Duration::from_micros((1_000_000.0_f64 / 60.0).round() as u64)
}
fn new(
app: &mut App,
vsync: TickerProviderRef,
color: Color,
axis: Axis,
) -> Ref<GlowController> {
let glow_controller = AnimationController::new(
app,
None,
None,
None,
0.0,
1.0,
AnimationBehavior::Normal,
vsync.clone(),
);
let glow_opacity_tween = Tween::new(app, Some(0.0), Some(0.0));
let glow_size_tween = Tween::new(app, Some(0.0), Some(0.0));
let this = app.create(GlowController {
change_notifier: ChangeNotifierData::new(),
state: GlowState::Idle,
glow_controller: glow_controller.clone(),
pull_recede_timer: None,
paint_offset: 0.0,
paint_offset_scroll_pixels: 0.0,
decelerator: None,
glow_opacity_tween: glow_opacity_tween.clone(),
glow_opacity: None,
glow_size_tween: glow_size_tween.clone(),
glow_size: None,
displacement_ticker: None,
displacement_ticker_last_elapsed: None,
displacement_target: 0.5,
displacement: 0.5,
pull_distance: 0.0,
color,
axis,
});
let handle = this.handle();
glow_controller.view().add_status_listener(
app,
AnimationStatusListener::handle_method(handle, GlowController::change_phase),
);
let decelerator =
CurvedAnimation::new(app, glow_controller.erase(), Curves::decelerate(), None);
decelerator.add_listener(
app,
Listener::handle_method(handle, Handle::<GlowController>::notify_listeners),
);
let glow_opacity = decelerator.drive(app, glow_opacity_tween);
let glow_size = decelerator.drive(app, glow_size_tween);
let displacement_ticker = vsync.create_ticker(
app,
FrameCallback::handle_method(handle, GlowController::tick_displacement),
);
let controller = app.get_mut(&this);
controller.decelerator = Some(decelerator);
controller.glow_opacity = Some(glow_opacity);
controller.glow_size = Some(glow_size);
controller.displacement_ticker = Some(displacement_ticker);
this
}
fn decelerator(self: Handle<Self>, app: &App) -> Handle<CurvedAnimation> {
app.get(self)
.decelerator
.handle()
.expect("set by the constructor")
}
fn glow_opacity(self: Handle<Self>, app: &App) -> AnyAnimation<f64> {
app.get(self)
.glow_opacity
.handle()
.expect("set by the constructor")
}
fn glow_size(self: Handle<Self>, app: &App) -> AnyAnimation<f64> {
app.get(self)
.glow_size
.handle()
.expect("set by the constructor")
}
fn displacement_ticker(self: Handle<Self>, app: &App) -> Handle<Ticker> {
app.get(self)
.displacement_ticker
.handle()
.expect("set by the constructor")
}
fn color(self: Handle<Self>, app: &App) -> Color {
app.get(self).color
}
fn set_color(self: Handle<Self>, app: &mut App, value: Color) {
if self.color(app) == value {
return;
}
app.get_mut(self).color = value;
self.notify_listeners(app);
}
fn axis(self: Handle<Self>, app: &App) -> Axis {
app.get(self).axis
}
fn set_axis(self: Handle<Self>, app: &mut App, value: Axis) {
if self.axis(app) == value {
return;
}
app.get_mut(self).axis = value;
self.notify_listeners(app);
}
fn cancel_pull_recede_timer(self: Handle<Self>, app: &mut App) {
if let Some(timer) = app.get(self).pull_recede_timer {
timer.cancel(app);
}
}
fn dispose(self: Handle<Self>, app: &mut App) {
app.get(self).glow_controller.dispose(app);
self.decelerator(app).dispose(app);
self.displacement_ticker(app).dispose(app);
self.cancel_pull_recede_timer(app);
ChangeNotifierData::dispose(app, self);
}
fn absorb_impact(self: Handle<Self>, app: &mut App, velocity: f64) {
debug_assert!(velocity >= 0.0);
self.cancel_pull_recede_timer(app);
app.get_mut(self).pull_recede_timer = None;
let velocity = clamp_double(velocity, Self::MIN_VELOCITY, Self::MAX_VELOCITY);
let glow_opacity_begin = if app.get(self).state == GlowState::Idle {
0.3
} else {
self.glow_opacity(app).value(app)
};
let glow_opacity_tween = app.get(self).glow_opacity_tween.handle();
glow_opacity_tween.set_begin(app, Some(glow_opacity_begin));
glow_opacity_tween.set_end(
app,
Some(clamp_double(
velocity * Self::VELOCITY_GLOW_FACTOR,
glow_opacity_begin,
Self::MAX_OPACITY,
)),
);
let glow_size_tween = app.get(self).glow_size_tween.handle();
let glow_size = self.glow_size(app).value(app);
glow_size_tween.set_begin(app, Some(glow_size));
glow_size_tween.set_end(
app,
Some(f64::min(0.025 + 7.5e-7 * velocity * velocity, 1.0)),
);
let glow_controller = app.get(self).glow_controller.handle();
app.get_mut(glow_controller).duration = Some(Duration::from_millis(
(0.15 + velocity * 0.02).round() as u64,
));
glow_controller.forward(app, Some(0.0));
let controller = app.get_mut(self);
controller.displacement = 0.5;
controller.state = GlowState::Absorb;
}
fn pull(
self: Handle<Self>,
app: &mut App,
overscroll: f64,
extent: f64,
cross_axis_offset: f64,
cross_extent: f64,
) {
self.cancel_pull_recede_timer(app);
app.get_mut(self).pull_distance += overscroll / 200.0;
let glow_opacity_tween = app.get(self).glow_opacity_tween.handle();
let glow_opacity = self.glow_opacity(app).value(app);
glow_opacity_tween.set_begin(app, Some(glow_opacity));
let glow_opacity = self.glow_opacity(app).value(app);
glow_opacity_tween.set_end(
app,
Some(f64::min(
glow_opacity + overscroll / extent * Self::PULL_OPACITY_GLOW_FACTOR,
Self::MAX_OPACITY,
)),
);
let height = f64::min(extent, cross_extent * Self::WIDTH_TO_HEIGHT_FACTOR);
let glow_size_tween = app.get(self).glow_size_tween.handle();
let glow_size = self.glow_size(app).value(app);
glow_size_tween.set_begin(app, Some(glow_size));
let pull_distance = app.get(self).pull_distance;
let glow_size = self.glow_size(app).value(app);
glow_size_tween.set_end(
app,
Some(f64::max(
1.0 - 1.0 / (0.7 * (pull_distance * height).sqrt()),
glow_size,
)),
);
app.get_mut(self).displacement_target = cross_axis_offset / cross_extent;
let displacement_ticker = self.displacement_ticker(app);
let controller = app.get(self);
if controller.displacement_target != controller.displacement {
if !displacement_ticker.is_ticking(app) {
debug_assert!(app.get(self).displacement_ticker_last_elapsed.is_none());
displacement_ticker.start(app);
}
} else {
displacement_ticker.stop(app, false);
app.get_mut(self).displacement_ticker_last_elapsed = None;
}
let glow_controller = app.get(self).glow_controller.handle();
app.get_mut(glow_controller).duration = Some(Self::PULL_TIME);
if app.get(self).state != GlowState::Pull {
glow_controller.forward(app, Some(0.0));
app.get_mut(self).state = GlowState::Pull;
} else if !glow_controller.is_animating(app) {
debug_assert!(glow_controller.value(app) == 1.0);
self.notify_listeners(app);
}
let timer = Timer::new(
app,
Self::PULL_HOLD_TIME,
Listener::new(move |app: &mut App| self.recede(app, Self::PULL_DECAY_TIME)),
);
app.get_mut(self).pull_recede_timer = Some(timer);
}
fn scroll_end(self: Handle<Self>, app: &mut App) {
if app.get(self).state == GlowState::Pull {
self.recede(app, Self::RECEDE_TIME);
}
}
fn change_phase(self: Handle<Self>, app: &mut App, status: AnimationStatus) {
if !status.is_completed() {
return;
}
match app.get(self).state {
GlowState::Absorb => self.recede(app, Self::RECEDE_TIME),
GlowState::Recede => {
let controller = app.get_mut(self);
controller.state = GlowState::Idle;
controller.pull_distance = 0.0;
}
GlowState::Pull | GlowState::Idle => {}
}
}
fn recede(self: Handle<Self>, app: &mut App, duration: Duration) {
let state = app.get(self).state;
if state == GlowState::Recede || state == GlowState::Idle {
return;
}
self.cancel_pull_recede_timer(app);
app.get_mut(self).pull_recede_timer = None;
let glow_opacity = self.glow_opacity(app).value(app);
let glow_opacity_tween = app.get(self).glow_opacity_tween.handle();
glow_opacity_tween.set_begin(app, Some(glow_opacity));
glow_opacity_tween.set_end(app, Some(0.0));
let glow_size = self.glow_size(app).value(app);
let glow_size_tween = app.get(self).glow_size_tween.handle();
glow_size_tween.set_begin(app, Some(glow_size));
glow_size_tween.set_end(app, Some(0.0));
let glow_controller = app.get(self).glow_controller.handle();
app.get_mut(glow_controller).duration = Some(duration);
glow_controller.forward(app, Some(0.0));
app.get_mut(self).state = GlowState::Recede;
}
fn tick_displacement(self: Handle<Self>, app: &mut App, elapsed: Duration) {
if let Some(last_elapsed) = app.get(self).displacement_ticker_last_elapsed {
let t = (elapsed.as_micros() as i64 - last_elapsed.as_micros() as i64) as f64;
let controller = app.get_mut(self);
controller.displacement = controller.displacement_target
- (controller.displacement_target - controller.displacement)
* 2.0_f64.powf(-t / Self::cross_axis_half_time().as_micros() as f64);
self.notify_listeners(app);
}
let controller = app.get(self);
if near_equal(
Some(controller.displacement_target),
Some(controller.displacement),
Tolerance::DEFAULT_TOLERANCE.distance,
) {
self.displacement_ticker(app).stop(app, false);
app.get_mut(self).displacement_ticker_last_elapsed = None;
} else {
app.get_mut(self).displacement_ticker_last_elapsed = Some(elapsed);
}
}
fn paint(self: Handle<Self>, app: &App, canvas: &mut Canvas, size: Size) {
let glow_opacity = self.glow_opacity(app).value(app);
if glow_opacity == 0.0 {
return;
}
let controller = app.get(self);
let base_glow_scale = if size.width() > size.height() {
size.height() / size.width()
} else {
1.0
};
let radius = size.width() * 3.0 / 2.0;
let height = f64::min(size.height(), size.width() * Self::WIDTH_TO_HEIGHT_FACTOR);
let scale_y = self.glow_size(app).value(app) * base_glow_scale;
let rect = Rect::from_ltwh(0.0, 0.0, size.width(), height);
let center = Offset::new(
(size.width() / 2.0) * (0.5 + controller.displacement),
height - radius,
);
#[allow(deprecated)]
let paint = Paint::from_color(controller.color.with_opacity(glow_opacity).into());
canvas.save();
canvas.translate(
0.0,
(controller.paint_offset + controller.paint_offset_scroll_pixels) as f32,
);
canvas.scale(1.0, scale_y as f32);
canvas.clip_rect(rect, ClipOp::Intersect, true);
canvas.draw_circle(center, radius as f32, &paint);
canvas.restore();
}
}
impl ChangeNotifier for GlowController {
fn change_notifier_data(&self) -> &ChangeNotifierData {
&self.change_notifier
}
fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
&mut self.change_notifier
}
}
impl Debug for GlowController {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"_GlowController(color: {:?}, axis: {:?})",
self.color, self.axis
)
}
}
struct GlowingOverscrollIndicatorPainter {
leading_controller: Option<Ref<GlowController>>,
trailing_controller: Option<Ref<GlowController>>,
axis_direction: AxisDirection,
repaint: Option<Rc<dyn Listenable>>,
}
impl GlowingOverscrollIndicatorPainter {
const PI_OVER_2: f64 = std::f64::consts::PI / 2.0;
fn paint_side(
&self,
app: &App,
canvas: &mut Canvas,
size: Size,
controller: Option<Handle<GlowController>>,
axis_direction: AxisDirection,
growth_direction: GrowthDirection,
) {
let Some(controller) = controller else {
return;
};
match apply_growth_direction_to_axis_direction(axis_direction, growth_direction) {
AxisDirection::Up => controller.paint(app, canvas, size),
AxisDirection::Down => {
canvas.save();
canvas.translate(0.0, size.height() as f32);
canvas.scale(1.0, -1.0);
controller.paint(app, canvas, size);
canvas.restore();
}
AxisDirection::Left => {
canvas.save();
canvas.rotate(Self::PI_OVER_2 as f32);
canvas.scale(1.0, -1.0);
controller.paint(app, canvas, Size::new(size.height(), size.width()));
canvas.restore();
}
AxisDirection::Right => {
canvas.save();
canvas.translate(size.width() as f32, 0.0);
canvas.rotate(Self::PI_OVER_2 as f32);
controller.paint(app, canvas, Size::new(size.height(), size.width()));
canvas.restore();
}
}
}
}
impl CustomPainter for GlowingOverscrollIndicatorPainter {
fn repaint(&self) -> Option<&Rc<dyn Listenable>> {
self.repaint.as_ref()
}
fn paint(&self, app: &mut App, canvas: &mut Canvas, size: Size) {
self.paint_side(
app,
canvas,
size,
self.leading_controller.handle(),
self.axis_direction,
GrowthDirection::Reverse,
);
self.paint_side(
app,
canvas,
size,
self.trailing_controller.handle(),
self.axis_direction,
GrowthDirection::Forward,
);
}
fn should_repaint(&self, _app: &App, old_delegate: &dyn CustomPainter) -> bool {
let old_delegate = old_delegate
.as_any()
.downcast_ref::<GlowingOverscrollIndicatorPainter>()
.expect("Dart's covariant parameter");
old_delegate.leading_controller != self.leading_controller
|| old_delegate.trailing_controller != self.trailing_controller
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
}
impl Debug for GlowingOverscrollIndicatorPainter {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"_GlowingOverscrollIndicatorPainter({:?}, {:?})",
self.leading_controller, self.trailing_controller
)
}
}
pub struct StretchingOverscrollIndicator {
pub key: Option<KeyRef>,
pub axis_direction: AxisDirection,
pub notification_predicate: ScrollNotificationPredicate,
pub clip_behavior: Clip,
pub child: Option<WidgetRef>,
}
impl StretchingOverscrollIndicator {
pub fn new(axis_direction: AxisDirection) -> StretchingOverscrollIndicator {
StretchingOverscrollIndicator {
key: None,
axis_direction,
notification_predicate: Rc::new(default_scroll_notification_predicate),
clip_behavior: Clip::HardEdge,
child: None,
}
}
pub fn key(mut self, key: KeyRef) -> StretchingOverscrollIndicator {
self.key = Some(key);
self
}
pub fn notification_predicate(
mut self,
notification_predicate: ScrollNotificationPredicate,
) -> StretchingOverscrollIndicator {
self.notification_predicate = notification_predicate;
self
}
pub fn clip_behavior(mut self, clip_behavior: Clip) -> StretchingOverscrollIndicator {
self.clip_behavior = clip_behavior;
self
}
#[cfg_attr(debug_assertions, track_caller)]
pub fn child<K>(mut self, child: impl IntoWidget<K>) -> StretchingOverscrollIndicator {
self.child = Some(child.into_widget());
self
}
pub fn axis(&self) -> Axis {
axis_direction_to_axis(self.axis_direction)
}
}
impl Debug for StretchingOverscrollIndicator {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("StretchingOverscrollIndicator")
.field("axisDirection", &self.axis_direction)
.finish_non_exhaustive()
}
}
impl StatefulWidget for StretchingOverscrollIndicator {
type State = StretchingOverscrollIndicatorState;
fn key(&self) -> Option<&KeyRef> {
self.key.as_ref()
}
fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
properties.add(EnumProperty::new("axisDirection", self.axis_direction));
}
fn create_state(&self) -> StretchingOverscrollIndicatorState {
StretchingOverscrollIndicatorState {
state: StateData::new(),
ticker_provider: TickerProviderStateMixinData::new(),
stretch_controller: None,
last_overscroll_notification_metrics: None,
total_overscroll: 0.0,
accepted: true,
}
}
}
pub struct StretchingOverscrollIndicatorState {
state: StateData<StretchingOverscrollIndicator>,
ticker_provider: TickerProviderStateMixinData,
stretch_controller: Option<(Ref<StretchController>, Rc<dyn Listenable>)>,
last_overscroll_notification_metrics:
Option<Rc<dyn crate::widgets::scroll_metrics::ScrollMetrics>>,
total_overscroll: f64,
accepted: bool,
}
impl StretchingOverscrollIndicatorState {
fn stretch_controller(self: Handle<Self>, app: &mut App) -> Handle<StretchController> {
self.stretch_listenable_controller(app).0
}
fn stretch_listenable_controller(
self: Handle<Self>,
app: &mut App,
) -> (Handle<StretchController>, Rc<dyn Listenable>) {
if let Some((controller, listenable)) = &app.get(self).stretch_controller {
return (controller.handle(), Rc::clone(listenable));
}
let controller = StretchController::new(app, TickerProviderRef::new(self));
let handle = controller.handle();
let listenable: Rc<dyn Listenable> = Rc::new(controller.clone());
app.get_mut(self).stretch_controller = Some((controller, Rc::clone(&listenable)));
(handle, listenable)
}
fn handle_scroll_notification(
self: Handle<Self>,
app: &mut App,
notification: &dyn ScrollNotification,
) -> bool {
let widget = self.widget(app);
let notification_predicate = Rc::clone(&widget.notification_predicate);
let axis = widget.axis();
if !notification_predicate(notification) {
return false;
}
if notification.metrics().axis() != axis {
return false;
}
let any = notification.as_any();
if any.is::<ScrollStartNotification>() {
let state = app.get_mut(self);
state.accepted = true;
state.total_overscroll = 0.0;
} else if let Some(notification) = any.downcast_ref::<OverscrollNotification>() {
app.get_mut(self).last_overscroll_notification_metrics =
Some(Rc::clone(notification.metrics()));
let confirmation_notification =
OverscrollIndicatorNotification::new(notification.overscroll < 0.0);
confirmation_notification.dispatch(app, Some(self.context(app)));
app.get_mut(self).accepted = confirmation_notification.accepted.get();
if app.get(self).accepted {
app.get_mut(self).total_overscroll += notification.overscroll;
if notification.velocity != 0.0 {
debug_assert!(notification.drag_details.is_none());
self.stretch_controller(app)
.absorb_impact(app, notification.velocity);
} else {
debug_assert!(notification.overscroll != 0.0);
if notification.drag_details.is_some() {
let viewport_dimension = notification.metrics().viewport_dimension();
let distance_for_pull = app.get(self).total_overscroll / viewport_dimension;
let clamped_overscroll = clamp_double(distance_for_pull, -1.0, 1.0);
self.stretch_controller(app).pull(app, clamped_overscroll);
}
}
}
} else if let Some(notification) = any.downcast_ref::<ScrollEndNotification>() {
let mut velocity = match axis {
Axis::Vertical => notification
.drag_details
.as_ref()
.map_or(0.0, |details| details.velocity.pixels_per_second.dy()),
Axis::Horizontal => notification
.drag_details
.as_ref()
.map_or(0.0, |details| details.velocity.pixels_per_second.dx()),
};
if matches!(
notification.metrics().axis_direction(),
AxisDirection::Left | AxisDirection::Up
) {
velocity = -velocity;
}
app.get_mut(self).total_overscroll = 0.0;
if app.get(self).accepted {
self.stretch_controller(app).scroll_end(app, velocity);
}
} else if any.is::<ScrollUpdateNotification>() {
app.get_mut(self).total_overscroll = 0.0;
self.stretch_controller(app).scroll_end(app, 0.0);
}
false
}
fn build_stretch(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
let stretch = self.stretch_controller(app).overscroll(app);
let widget = self.widget(app);
let (axis, axis_direction, clip_behavior) =
(widget.axis(), widget.axis_direction, widget.clip_behavior);
let child = widget
.child
.clone()
.unwrap_or_else(|| SizedBox::shrink().into_widget());
let main_axis_size = match axis {
Axis::Horizontal => MediaQuery::width_of(app, context),
Axis::Vertical => MediaQuery::height_of(app, context),
};
let viewport_dimension = app
.get(self)
.last_overscroll_notification_metrics
.as_ref()
.map_or(main_axis_size, |metrics| metrics.viewport_dimension());
let mut overscroll = -stretch;
if axis_direction == AxisDirection::Up || axis_direction == AxisDirection::Left {
overscroll = -overscroll;
}
let transform = StretchEffect::new(axis, child).stretch_strength(overscroll);
ClipRect::new()
.clip_behavior(if stretch != 0.0 && viewport_dimension != main_axis_size {
clip_behavior
} else {
Clip::None
})
.child(transform)
.into_widget()
}
}
impl Debug for StretchingOverscrollIndicatorState {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("StretchingOverscrollIndicatorState")
.finish_non_exhaustive()
}
}
impl TickerProviderStateMixin for StretchingOverscrollIndicatorState {
fn ticker_provider_data(self: Handle<Self>, app: &App) -> &TickerProviderStateMixinData {
&app.get(self).ticker_provider
}
fn ticker_provider_data_mut(
self: Handle<Self>,
app: &mut App,
) -> &mut TickerProviderStateMixinData {
&mut app.get_mut(self).ticker_provider
}
}
impl TickerProviderObject for StretchingOverscrollIndicatorState {
fn create_ticker(self: Handle<Self>, app: &mut App, on_tick: TickerCallback) -> Ref<Ticker> {
TickerProviderStateMixin::create_ticker(self, app, on_tick)
}
}
impl State for StretchingOverscrollIndicatorState {
type Widget = StretchingOverscrollIndicator;
crate::state_accessors!();
fn activate(self: Handle<Self>, app: &mut App) {
TickerProviderStateMixin::activate(self, app);
}
fn dispose(self: Handle<Self>, app: &mut App) {
self.stretch_controller(app).dispose(app);
TickerProviderStateMixin::dispose(self, app);
}
fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
let (_, stretch_listenable) = self.stretch_listenable_controller(app);
NotificationListener::<dyn ScrollNotification>::new(
AnimatedBuilder::new(
stretch_listenable,
move |app: &mut App, context: BuildContext, _child: Option<&WidgetRef>| {
self.build_stretch(app, context)
},
)
.into_widget(),
)
.on_notification(
move |app: &mut App, notification: &dyn ScrollNotification| {
self.handle_scroll_notification(app, notification)
},
)
.into_widget()
}
}
struct StretchController {
vsync: TickerProviderRef,
controller: Option<Ref<AnimationController>>,
overscroll_notifier: Ref<ValueNotifier<f64>>,
interrupted_overscroll: f64,
}
impl StretchController {
const EXPONENTIAL_SCALAR: f64 = std::f64::consts::E / 0.33;
const STRETCH_INTENSITY: f64 = 0.016;
const MIN_OVERSCROLL: f64 = -1.0;
const MAX_OVERSCROLL: f64 = 1.0;
const FLING_VELOCITY_FRICTION: f64 = 1.0 / 6000.0;
const ABSORB_IMPACT_VELOCITY_FRICTION: f64 = 1.0 / 3000.0;
const MAX_FLING_VELOCITY: f64 = 0.5;
const MAX_ABSORB_IMPACT_VELOCITY: f64 = 1.25;
const K_NATURAL_FREQUENCY: f64 = 24.657;
const K_DAMPING_RATIO: f64 = 0.98;
const K_TIME_CORRECTION_FACTOR: f64 = 0.8;
const K_STIFFNESS: f64 = Self::K_NATURAL_FREQUENCY * Self::K_NATURAL_FREQUENCY;
fn stretch_spring_description() -> SpringDescription {
SpringDescription::with_damping_ratio_value(
1.0,
Self::K_STIFFNESS * Self::K_TIME_CORRECTION_FACTOR * Self::K_TIME_CORRECTION_FACTOR,
Self::K_DAMPING_RATIO,
)
}
fn new(app: &mut App, vsync: TickerProviderRef) -> Ref<StretchController> {
let overscroll_notifier = app.create(ValueNotifier::new(0.0));
app.create(StretchController {
vsync,
controller: None,
overscroll_notifier,
interrupted_overscroll: 0.0,
})
}
fn overscroll(self: Handle<Self>, app: &App) -> f64 {
*app.get(&app.get(self).overscroll_notifier).value()
}
fn set_overscroll(self: Handle<Self>, app: &mut App, new_value: f64) {
let notifier = app.get(self).overscroll_notifier.handle();
notifier.set_value(
app,
clamp_double(new_value, Self::MIN_OVERSCROLL, Self::MAX_OVERSCROLL),
);
}
fn create_stretch_simulation(self: Handle<Self>, app: &App, velocity: f64) -> SpringSimulation {
SpringSimulation::new(
Self::stretch_spring_description(),
self.overscroll(app),
0.0,
velocity * Self::K_TIME_CORRECTION_FACTOR,
)
}
fn absorb_impact(self: Handle<Self>, app: &mut App, velocity: f64) {
if velocity == 0.0 {
return;
}
let scaled_velocity = clamp_double(
velocity * Self::ABSORB_IMPACT_VELOCITY_FRICTION,
-Self::MAX_ABSORB_IMPACT_VELOCITY,
Self::MAX_ABSORB_IMPACT_VELOCITY,
);
let simulation = self.create_stretch_simulation(app, scaled_velocity);
self.animate(app, Box::new(simulation));
}
fn scroll_end(self: Handle<Self>, app: &mut App, velocity: f64) {
if velocity == 0.0 && self.overscroll(app) == 0.0 {
return;
}
let scaled_velocity = clamp_double(
-(velocity * Self::FLING_VELOCITY_FRICTION),
-Self::MAX_FLING_VELOCITY,
Self::MAX_FLING_VELOCITY,
);
if app.get(self).controller.is_none() {
let simulation = self.create_stretch_simulation(app, scaled_velocity);
self.animate(app, Box::new(simulation));
}
}
fn animate(self: Handle<Self>, app: &mut App, simulation: Box<dyn Simulation>) {
let vsync = app.get(self).vsync.clone();
let controller = AnimationController::unbounded(
app,
0.0,
None,
None,
AnimationBehavior::Preserve,
vsync,
);
controller.view().add_listener(
app,
Listener::new(move |app: &mut App| {
let new_overscroll = app
.get(self)
.controller
.handle()
.map_or(0.0, |controller| controller.value(app));
self.set_overscroll(app, new_overscroll);
}),
);
let handle = controller.handle();
controller.animate_with(app, simulation).when_complete(
app,
Listener::new(move |app: &mut App| {
let controller = handle;
if app.get(self).controller.handle() == Some(controller) {
self.set_overscroll(app, 0.0);
app.get_mut(self).interrupted_overscroll = 0.0;
controller.dispose(app);
app.get_mut(self).controller = None;
}
}),
);
if let Some(old_controller) = app.get(self).controller.handle() {
old_controller.dispose(app);
}
app.get_mut(self).controller = Some(controller);
}
fn pull(self: Handle<Self>, app: &mut App, normalized_overscroll: f64) {
if let Some(controller) = app.get(self).controller.handle() {
app.get_mut(self).interrupted_overscroll = controller.value(app);
controller.dispose(app);
app.get_mut(self).controller = None;
}
let pull_distance = normalized_overscroll;
let abs_distance = pull_distance.abs();
let linear_intensity = Self::STRETCH_INTENSITY * abs_distance;
let exponential_intensity =
Self::STRETCH_INTENSITY * (1.0 - (-abs_distance * Self::EXPONENTIAL_SCALAR).exp());
let direction_sign = if pull_distance > 0.0 {
1.0
} else if pull_distance < 0.0 {
-1.0
} else {
pull_distance
};
let new_overscroll = direction_sign * (linear_intensity + exponential_intensity);
let interrupted_overscroll = app.get(self).interrupted_overscroll;
self.set_overscroll(app, new_overscroll + interrupted_overscroll);
}
fn dispose(self: Handle<Self>, app: &mut App) {
if let Some(controller) = app.get_mut(self).controller.take() {
controller.dispose(app);
}
let notifier = app.get(self).overscroll_notifier.handle();
notifier.dispose(app);
}
}
impl ListenableObject for StretchController {
fn add_listener(self: Handle<Self>, app: &mut App, listener: Listener) {
let notifier = app.get(self).overscroll_notifier.handle();
notifier.add_listener(app, listener);
}
fn remove_listener(self: Handle<Self>, app: &mut App, listener: &Listener) {
let notifier = app.get(self).overscroll_notifier.handle();
notifier.remove_listener(app, listener);
}
}
impl Debug for StretchController {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("_StretchController()")
}
}
pub struct OverscrollIndicatorNotification {
viewport_notification: ViewportNotificationData,
pub leading: bool,
pub paint_offset: Cell<f64>,
pub accepted: Cell<bool>,
}
impl OverscrollIndicatorNotification {
pub fn new(leading: bool) -> OverscrollIndicatorNotification {
OverscrollIndicatorNotification {
viewport_notification: ViewportNotificationData::new(),
leading,
paint_offset: Cell::new(0.0),
accepted: Cell::new(true),
}
}
pub fn disallow_indicator(&self) {
self.accepted.set(false);
}
}
impl Notification for OverscrollIndicatorNotification {
fn as_any(&self) -> &dyn std::any::Any {
self
}
fn viewport_depth(&self) -> Option<&Cell<u32>> {
Some(self.viewport_notification.depth_cell())
}
}
impl ViewportNotificationMixin for OverscrollIndicatorNotification {
fn viewport_notification_data(&self) -> &ViewportNotificationData {
&self.viewport_notification
}
}
impl Debug for OverscrollIndicatorNotification {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut description = Vec::new();
ViewportNotificationMixin::debug_fill_description(self, &mut description);
description.push(format!(
"side: {}",
if self.leading {
"leading edge"
} else {
"trailing edge"
}
));
write!(
f,
"OverscrollIndicatorNotification({})",
description.join(", ")
)
}
}
#[cfg(test)]
mod tests {
use waft_foundation::OptionRetained;
use waft_embedder::TextDirection;
use waft_embedder::valo::Op;
use waft_foundation::UniqueKey;
use waft_gestures::{DragEndDetails, DragStartDetails, DragUpdateDetails, Velocity};
use waft_painting::EdgeInsetsGeometry;
use waft_physics::Simulation;
use waft_rendering::{
RenderBox, RenderClipRect, RenderCustomClip, RenderCustomPaint, RenderHandle,
};
use super::*;
use crate::binding::WidgetsBinding;
use crate::framework::GlobalKey;
use crate::testing::{TestPointer, WidgetTester, test_widgets};
use crate::testing::{assert_f32_equals, expect, find, finds_nothing, finds_one_widget};
use crate::widgets::basic::{
Center, Column, Directionality, Opacity, Padding, SliverToBoxAdapter,
};
use crate::widgets::container::Container;
use crate::widgets::media_query::MediaQueryData;
use crate::widgets::page_view::PageView;
use crate::widgets::scroll_configuration::{
ScrollBehavior, ScrollBehaviorRef, ScrollConfiguration,
};
use crate::widgets::scroll_controller::{ScrollController, ScrollControllerLeaf};
use crate::widgets::scroll_metrics::ScrollMetrics;
use crate::widgets::scroll_physics::{
AlwaysScrollableScrollPhysics, ScrollPhysics, ScrollPhysicsBase, ScrollPhysicsRef,
};
use crate::widgets::scroll_simulation::ClampingScrollSimulation;
use crate::widgets::scroll_view::{CustomScrollView, ListView};
use crate::widgets::scrollable_helpers::ScrollableDetails;
use crate::widgets::single_child_scroll_view::SingleChildScrollView;
use crate::widgets::sliver::SliverList;
use crate::widgets::text::Text;
use waft_rendering::testing::{PaintCall, RecordedCall, assert_paints, paints};
const VIEW_CENTER: Offset = Offset::new(
WidgetTester::SIZE.width() / 2.0,
WidgetTester::SIZE.height() / 2.0,
);
fn slow_drag(tester: &mut WidgetTester, start: Offset, offset: Offset, pointer: i64) {
let mut gesture = TestPointer::touch(pointer);
tester.down(&mut gesture, start);
for _ in 0..10 {
tester.move_by(&mut gesture, offset, true);
tester.pump_by(Duration::from_millis(20));
}
tester.up(&gesture);
}
fn has_image_filter_layer(tester: &WidgetTester) -> bool {
let root = tester
.update(|app| WidgetsBinding::instance(app).root_element(app))
.expect("a mounted tree");
let layers = tester.layer_list_of(root);
let app = tester.cell.borrow();
layers.into_iter().any(|layer| {
app.handle::<waft_rendering::ImageFilterLayer>(layer.id())
.is_some()
})
}
fn stretch_strength(tester: &WidgetTester) -> f64 {
tester.widget(
find::by_type::<StretchEffect>(),
|effect: &StretchEffect| effect.stretch_strength,
)
}
fn custom_paints(tester: &WidgetTester) -> Vec<RenderHandle<RenderCustomPaint>> {
tester.all::<RenderCustomPaint>()
}
fn custom_paint(tester: &WidgetTester) -> RenderHandle<RenderCustomPaint> {
let paints = custom_paints(tester);
assert_eq!(paints.len(), 1, "one CustomPaint");
paints[0]
}
fn first_clip_rect(tester: &WidgetTester) -> Rect {
let clip = tester.first::<RenderClipRect>();
tester.get_rect(clip.as_box())
}
fn first_clip_behavior(tester: &WidgetTester) -> Clip {
let clip = tester.first::<RenderClipRect>();
clip.clip_behavior(&tester.cell.borrow())
}
fn painted(tester: &WidgetTester, custom_paint: RenderHandle<RenderCustomPaint>) -> Vec<Op> {
let mut app = tester.cell.borrow_mut();
let painter = custom_paint
.foreground_painter(&app)
.expect("the indicator paints in the foreground");
let size = custom_paint.size(&app);
let mut canvas = Canvas::new();
canvas.save();
painter.paint(&mut app, &mut canvas, size);
canvas.restore();
canvas.build().ops().to_vec()
}
fn origin_of(tester: &WidgetTester, key: &GlobalKey) -> Offset {
let render_box = tester.render_object(key).as_box().expect("a render box");
render_box.local_to_global(&tester.cell.borrow(), Offset::ZERO, None)
}
fn does_not_overscroll(ops: &[Op]) -> bool {
paints(ops, &[circle()]).is_err()
}
fn circle() -> PaintCall {
PaintCall::circle(None)
}
fn circle_with(x: Option<f64>, color: Option<u32>) -> PaintCall {
PaintCall::Circle {
x,
y: None,
radius: None,
color: color.map(Color::new),
style: None,
}
}
fn ltr<K>(child: impl IntoWidget<K>) -> WidgetRef {
Directionality::new(TextDirection::Ltr, child).into_widget()
}
fn sized_scroll_view(height: f64) -> CustomScrollView {
CustomScrollView::new().slivers([SliverToBoxAdapter::new()
.child(SizedBox::new().height(height))
.into_widget()])
}
fn always_scrollable() -> ScrollPhysicsRef {
Rc::new(AlwaysScrollableScrollPhysics::new())
}
#[derive(Debug)]
struct TestScrollBehavior<const COLOR: u32>;
impl<const COLOR: u32> ScrollBehavior for TestScrollBehavior<COLOR> {
fn as_any(&self) -> &dyn std::any::Any {
self
}
fn build_overscroll_indicator(
&self,
_app: &mut App,
_context: BuildContext,
child: WidgetRef,
details: &ScrollableDetails,
) -> WidgetRef {
if COLOR == 0 {
return child;
}
GlowingOverscrollIndicator::new(details.direction, Color::new(COLOR))
.child(child)
.into_widget()
}
}
fn behavior<const COLOR: u32>() -> ScrollBehaviorRef {
ScrollBehaviorRef::new(TestScrollBehavior::<COLOR>)
}
fn paint_offset_listener(
child: WidgetRef,
side: impl Fn(bool) -> bool + 'static,
paint_offset: f64,
) -> WidgetRef {
NotificationListener::<OverscrollIndicatorNotification>::new(child)
.on_notification(move |_app, notification| {
if side(notification.leading) {
notification.paint_offset.set(paint_offset);
}
false
})
.into_widget()
}
#[test]
fn the_default_glow_is_white_and_shows_only_for_a_slow_drag() {
test_widgets(|tester| {
tester.pump_widget(ltr(sized_scroll_view(2000.0)));
let painter = custom_paint(tester);
assert!(does_not_overscroll(&painted(tester, painter)));
tester.drag_from(VIEW_CENTER, Offset::new(0.0, 100.0), 1);
assert!(does_not_overscroll(&painted(tester, painter)));
tester.pump(); assert!(does_not_overscroll(&painted(tester, painter)));
tester.pump_by(Duration::from_millis(100)); assert!(does_not_overscroll(&painted(tester, painter)));
let mut gesture = TestPointer::touch(2);
tester.down(&mut gesture, Offset::new(200.0, 200.0));
tester.pump_by(Duration::from_millis(100)); assert!(does_not_overscroll(&painted(tester, painter)));
tester.up(&gesture);
assert!(does_not_overscroll(&painted(tester, painter)));
slow_drag(tester, Offset::new(200.0, 200.0), Offset::new(0.0, 5.0), 3);
assert_paints(
&painted(tester, painter),
&[circle_with(None, Some(0x0DFFFFFF))],
);
tester.pump_and_settle_by(Duration::from_secs(1));
assert!(does_not_overscroll(&painted(tester, painter)));
});
}
#[test]
fn a_predicate_lets_the_outer_indicator_glow_for_the_inner_scrollable() {
test_widgets(|tester| {
tester.pump_widget(ltr(GlowingOverscrollIndicator::new(
AxisDirection::Down,
Color::new(0x0DFFFFFF),
)
.notification_predicate(Rc::new(|notification| notification.depth() == 1))
.child(
SingleChildScrollView::new()
.scroll_direction(Axis::Horizontal)
.child(
SizedBox::new()
.width(600.0)
.child(sized_scroll_view(2000.0)),
),
)));
let paints_found = custom_paints(tester);
let outer_painter = paints_found[0];
let inner_painter = *paints_found.last().expect("two CustomPaints");
slow_drag(tester, Offset::new(200.0, 200.0), Offset::new(0.0, 5.0), 1);
assert_paints(&painted(tester, outer_painter), &[circle()]);
assert_paints(&painted(tester, inner_painter), &[circle()]);
});
}
#[test]
fn the_glow_centers_on_the_side_the_drag_is_on() {
test_widgets(|tester| {
tester.pump_widget(ltr(sized_scroll_view(2000.0)));
let painter = custom_paint(tester);
slow_drag(tester, Offset::new(400.0, 200.0), Offset::new(0.0, 10.0), 1);
assert_paints(&painted(tester, painter), &[circle_with(Some(400.0), None)]);
slow_drag(tester, Offset::new(100.0, 200.0), Offset::new(0.0, 10.0), 2);
assert_paints(
&painted(tester, painter),
&[PaintCall::something(|call| match call {
RecordedCall::Circle { center, .. } if center.dx() < 400.0 => Ok(true),
RecordedCall::Circle { .. } => Err(
"Dragging on left hand side did not overscroll on left hand side.".into(),
),
_ => Ok(false),
})],
);
slow_drag(tester, Offset::new(700.0, 200.0), Offset::new(0.0, 10.0), 3);
assert_paints(
&painted(tester, painter),
&[PaintCall::something(|call| match call {
RecordedCall::Circle { center, .. } if center.dx() > 400.0 => Ok(true),
RecordedCall::Circle { .. } => Err(
"Dragging on right hand side did not overscroll on right hand side.".into(),
),
_ => Ok(false),
})],
);
tester.pump_and_settle_by(Duration::from_secs(1));
assert!(does_not_overscroll(&painted(tester, painter)));
});
}
#[test]
fn the_glow_follows_a_drag_that_slides_sideways() {
test_widgets(|tester| {
tester.pump_widget(ltr(sized_scroll_view(2000.0)));
let painter = custom_paint(tester);
let mut gesture = TestPointer::touch(1);
tester.down(&mut gesture, Offset::new(300.0, 200.0));
tester.move_by(&mut gesture, Offset::new(0.0, 10.0), true);
tester.pump_by(Duration::from_millis(20));
let old_x = Rc::new(std::cell::Cell::new(0.0));
for _ in 0..10 {
tester.move_by(&mut gesture, Offset::new(50.0, 50.0), true);
tester.pump_by(Duration::from_millis(20));
assert_paints(
&painted(tester, painter),
&[PaintCall::something({
let old_x = Rc::clone(&old_x);
move |call| match call {
RecordedCall::Circle { center, .. } => {
if center.dx() <= old_x.get() {
return Err("Sliding to the right did not make the center of \
the radius slide to the right."
.into());
}
old_x.set(center.dx());
Ok(true)
}
_ => Ok(false),
}
})],
);
}
tester.up(&gesture);
tester.pump_and_settle_by(Duration::from_secs(1));
assert!(does_not_overscroll(&painted(tester, painter)));
});
}
#[test]
fn a_downward_scroll_view_glows_at_the_top_when_pulled_down() {
test_widgets(|tester| {
tester.pump_widget(ltr(sized_scroll_view(20.0).physics(always_scrollable())));
let painter = custom_paint(tester);
slow_drag(tester, Offset::new(200.0, 200.0), Offset::new(0.0, 5.0), 1);
assert_paints(
&painted(tester, painter),
&[
PaintCall::Save,
circle(),
PaintCall::Restore,
PaintCall::Save,
PaintCall::scale(None, Some(-1.0)),
PaintCall::Restore,
PaintCall::Restore,
],
);
tester.pump_and_settle_by(Duration::from_secs(1));
assert!(does_not_overscroll(&painted(tester, painter)));
});
}
#[test]
fn a_reversed_scroll_view_glows_at_the_top_when_pulled_down() {
test_widgets(|tester| {
tester.pump_widget(ltr(sized_scroll_view(20.0)
.reverse(true)
.physics(always_scrollable())));
let painter = custom_paint(tester);
slow_drag(tester, Offset::new(200.0, 200.0), Offset::new(0.0, 5.0), 1);
assert_paints(
&painted(tester, painter),
&[
PaintCall::Save,
PaintCall::scale(None, Some(-1.0)),
PaintCall::Restore,
PaintCall::Save,
circle(),
PaintCall::Restore,
PaintCall::Restore,
],
);
tester.pump_and_settle_by(Duration::from_secs(1));
assert!(does_not_overscroll(&painted(tester, painter)));
});
}
#[test]
fn pulling_one_way_then_the_other_glows_at_both_ends() {
test_widgets(|tester| {
tester.pump_widget(ltr(sized_scroll_view(20.0).physics(always_scrollable())));
let painter = custom_paint(tester);
slow_drag(tester, Offset::new(200.0, 200.0), Offset::new(0.0, 5.0), 1);
assert_paints(&painted(tester, painter), &[circle()]);
assert!(paints(&painted(tester, painter), &[circle(), circle()]).is_err());
slow_drag(tester, Offset::new(200.0, 200.0), Offset::new(0.0, -5.0), 2);
assert_paints(&painted(tester, painter), &[circle(), circle()]);
tester.pump_and_settle_by(Duration::from_secs(1));
assert!(does_not_overscroll(&painted(tester, painter)));
});
}
#[test]
fn an_indicator_ignores_overscrolls_along_the_other_axis() {
test_widgets(|tester| {
tester.pump_widget(ltr(ScrollConfiguration::new(
behavior::<0>(),
GlowingOverscrollIndicator::new(AxisDirection::Right, Color::new(0xFF0000FF))
.child(sized_scroll_view(20.0).physics(always_scrollable())),
)));
let painter = custom_paint(tester);
slow_drag(tester, Offset::new(200.0, 200.0), Offset::new(0.0, 5.0), 1);
assert!(does_not_overscroll(&painted(tester, painter)));
slow_drag(tester, Offset::new(200.0, 200.0), Offset::new(0.0, -5.0), 2);
assert!(does_not_overscroll(&painted(tester, painter)));
tester.pump_and_settle_by(Duration::from_secs(1));
assert!(does_not_overscroll(&painted(tester, painter)));
});
}
#[test]
fn a_horizontal_glow_is_rotated_a_quarter_turn() {
test_widgets(|tester| {
tester.pump_widget(ltr(sized_scroll_view(20.0)
.scroll_direction(Axis::Horizontal)
.physics(always_scrollable())));
let painter = custom_paint(tester);
let quarter = std::f64::consts::PI / 2.0;
slow_drag(tester, Offset::new(200.0, 200.0), Offset::new(5.0, 0.0), 1);
assert_paints(
&painted(tester, painter),
&[
PaintCall::rotate(Some(quarter)),
circle(),
PaintCall::SaveRestore,
],
);
assert!(paints(&painted(tester, painter), &[circle(), circle()]).is_err());
slow_drag(tester, Offset::new(200.0, 200.0), Offset::new(-5.0, 0.0), 2);
assert_paints(
&painted(tester, painter),
&[
PaintCall::rotate(Some(quarter)),
circle(),
PaintCall::rotate(Some(quarter)),
circle(),
],
);
tester.pump_and_settle_by(Duration::from_secs(1));
assert!(does_not_overscroll(&painted(tester, painter)));
});
}
#[test]
fn nested_overscrolls_do_not_throw_exceptions() {
test_widgets(|tester| {
tester.pump_widget(ltr(PageView::new().children([ListView::new()
.children([Container::new()
.width(2000.0)
.height(2000.0)
.color(Color::new(0xFF00FF00))
.into_widget()])
.into_widget()])));
tester.drag_from(Offset::new(100.0, 100.0), Offset::new(0.0, 2000.0), 1);
tester.pump_and_settle();
});
}
#[test]
fn a_new_behavior_glows_in_its_own_color() {
test_widgets(|tester| {
let quarter = std::f64::consts::PI / 2.0;
tester.pump_widget(ltr(ScrollConfiguration::new(
behavior::<0xFF00FF00>(),
sized_scroll_view(20.0)
.scroll_direction(Axis::Horizontal)
.physics(always_scrollable())
.reverse(true),
)));
let painter = custom_paint(tester);
slow_drag(tester, Offset::new(200.0, 200.0), Offset::new(5.0, 0.0), 1);
assert_paints(
&painted(tester, painter),
&[
PaintCall::rotate(Some(quarter)),
circle_with(None, Some(0x0A00FF00)),
],
);
assert!(paints(&painted(tester, painter), &[circle(), circle()]).is_err());
tester.pump_and_settle_by(Duration::from_secs(1));
tester.pump_widget(ltr(ScrollConfiguration::new(
behavior::<0xFF0000FF>(),
sized_scroll_view(20.0)
.scroll_direction(Axis::Horizontal)
.physics(always_scrollable()),
)));
let painter = custom_paint(tester);
slow_drag(tester, Offset::new(200.0, 200.0), Offset::new(5.0, 0.0), 2);
assert_paints(
&painted(tester, painter),
&[
PaintCall::rotate(Some(quarter)),
circle_with(None, Some(0x0A0000FF)),
PaintCall::SaveRestore,
],
);
assert!(paints(&painted(tester, painter), &[circle(), circle()]).is_err());
});
}
fn centered_scroll_view(first_sliver_1: &GlobalKey) -> WidgetRef {
let center_key: KeyRef = UniqueKey::new().into();
let first_sliver_1 = first_sliver_1.clone();
CustomScrollView::new()
.center(center_key.clone())
.physics(always_scrollable())
.slivers([
SliverList::builder(move |_app, _context, index| {
let item = Text::new(format!("First sliver {index}"));
Some(if index == 1 {
item.key(first_sliver_1.clone().into()).into_widget()
} else {
item.into_widget()
})
})
.item_count(2)
.into_widget(),
SliverList::builder(|_app, _context, index| {
Some(Text::new(format!("Second sliver {index}")).into_widget())
})
.key(center_key)
.item_count(5)
.into_widget(),
])
.into_widget()
}
#[test]
fn a_glow_over_slivers_before_the_center_starts_at_the_edge() {
test_widgets(|tester| {
let first_sliver_1 = GlobalKey::new();
tester.pump_widget(ltr(ScrollConfiguration::new(
behavior::<0xFF0000FF>(),
centered_scroll_view(&first_sliver_1),
)));
expect(
tester,
&find::by_global_key(&first_sliver_1),
finds_nothing(),
);
slow_drag(
tester,
Offset::new(200.0, 200.0),
Offset::new(0.0, 300.0),
1,
);
expect(
tester,
&find::by_global_key(&first_sliver_1),
finds_one_widget(),
);
let painter = custom_paint(tester);
assert_paints(
&painted(tester, painter),
&[
PaintCall::Save,
PaintCall::translate(None, Some(0.0)),
PaintCall::scale(None, None),
circle(),
],
);
});
}
#[test]
fn a_glow_over_slivers_before_the_center_honors_the_paint_offset() {
test_widgets(|tester| {
let first_sliver_1 = GlobalKey::new();
tester.pump_widget(ltr(ScrollConfiguration::new(
behavior::<0xFF0000FF>(),
paint_offset_listener(
centered_scroll_view(&first_sliver_1),
|leading| leading,
50.0,
),
)));
expect(
tester,
&find::by_global_key(&first_sliver_1),
finds_nothing(),
);
slow_drag(tester, Offset::new(200.0, 200.0), Offset::new(0.0, 5.0), 1);
expect(
tester,
&find::by_global_key(&first_sliver_1),
finds_one_widget(),
);
let painter = custom_paint(tester);
assert_paints(
&painted(tester, painter),
&[
PaintCall::Save,
PaintCall::translate(None, Some(50.0)),
PaintCall::scale(None, None),
circle(),
],
);
});
}
fn translated_glow(y: f64) -> Vec<PaintCall> {
vec![
PaintCall::Save,
PaintCall::translate(None, Some(y)),
PaintCall::scale(None, None),
circle(),
]
}
fn flipped_translated_glow(y: f64) -> Vec<PaintCall> {
vec![
PaintCall::scale(None, Some(-1.0)),
PaintCall::Save,
PaintCall::translate(None, Some(y)),
PaintCall::scale(None, None),
circle(),
]
}
#[test]
fn a_glow_moves_with_the_content_but_never_past_the_edge() {
test_widgets(|tester| {
tester.pump_widget(ltr(paint_offset_listener(
sized_scroll_view(2000.0).into_widget(),
|_leading| true,
50.0,
)));
let painter = custom_paint(tester);
let start = Offset::new(200.0, 200.0);
slow_drag(tester, start, Offset::new(0.0, 5.0), 1);
assert_paints(&painted(tester, painter), &translated_glow(50.0));
tester.drag_from(start, Offset::new(0.0, -30.0), 2);
tester.pump();
assert_paints(&painted(tester, painter), &translated_glow(50.0 - 30.0));
tester.drag_from(start, Offset::new(0.0, -20.0), 3);
tester.pump();
assert_paints(&painted(tester, painter), &translated_glow(50.0 - 50.0));
tester.drag_from(start, Offset::new(0.0, -10.0), 4);
tester.pump();
assert_paints(&painted(tester, painter), &translated_glow(50.0 - 50.0));
tester.pump_and_settle();
slow_drag(tester, start, Offset::new(0.0, -200.0), 5);
assert_paints(&painted(tester, painter), &flipped_translated_glow(50.0));
tester.drag_from(start, Offset::new(0.0, 30.0), 6);
tester.pump();
assert_paints(
&painted(tester, painter),
&flipped_translated_glow(50.0 - 30.0),
);
tester.drag_from(start, Offset::new(0.0, 20.0), 7);
tester.pump();
assert_paints(
&painted(tester, painter),
&flipped_translated_glow(50.0 - 50.0),
);
tester.drag_from(start, Offset::new(0.0, 10.0), 8);
tester.pump();
assert_paints(
&painted(tester, painter),
&flipped_translated_glow(50.0 - 50.0),
);
});
}
#[test]
fn the_leading_glow_draws_at_the_paint_offset_a_listener_sets() {
test_widgets(|tester| {
tester.pump_widget(ltr(paint_offset_listener(
sized_scroll_view(2000.0).into_widget(),
|leading| leading,
50.0,
)));
let painter = custom_paint(tester);
slow_drag(tester, Offset::new(200.0, 200.0), Offset::new(0.0, 5.0), 1);
assert_paints(&painted(tester, painter), &translated_glow(50.0));
tester.drag_from(Offset::new(200.0, 200.0), Offset::new(0.0, -30.0), 2);
tester.pump();
assert_paints(&painted(tester, painter), &translated_glow(50.0 - 30.0));
});
}
#[test]
fn the_trailing_glow_draws_at_the_paint_offset_a_listener_sets() {
test_widgets(|tester| {
tester.pump_widget(ltr(paint_offset_listener(
sized_scroll_view(2000.0).into_widget(),
|leading| !leading,
50.0,
)));
let painter = custom_paint(tester);
tester.drag_from(Offset::new(200.0, 200.0), Offset::new(200.0, -10000.0), 1);
tester.pump();
slow_drag(tester, Offset::new(200.0, 200.0), Offset::new(0.0, -5.0), 2);
assert_paints(&painted(tester, painter), &flipped_translated_glow(50.0));
tester.drag_from(Offset::new(200.0, 200.0), Offset::new(0.0, 30.0), 3);
tester.pump();
assert_paints(
&painted(tester, painter),
&flipped_translated_glow(50.0 - 30.0),
);
});
}
#[test]
fn a_stretching_indicator_with_no_child_builds() {
test_widgets(|tester| {
tester.pump_widget(ltr(StretchingOverscrollIndicator::new(AxisDirection::Down)));
expect(
tester,
&find::by_type::<StretchEffect>(),
finds_one_widget(),
);
});
}
fn list_of_items(count: i32, height: f64) -> WidgetRef {
ListView::builder(move |_app, _context, _index| {
Some(SizedBox::new().height(height).into_widget())
})
.item_count(count)
.build()
.physics(always_scrollable())
.into_widget()
}
#[test]
fn a_stretching_indicator_disposed_mid_animation_leaves_nothing_running() {
test_widgets(|tester| {
tester.pump_widget(ltr(StretchingOverscrollIndicator::new(AxisDirection::Down)
.child(list_of_items(20, 100.0))));
tester.fling_from(VIEW_CENTER, Offset::new(0.0, 300.0), 1000.0, 1);
tester.pump(); tester.pump_by(Duration::from_millis(100)); assert_ne!(
stretch_strength(tester),
0.0,
"the fling stretches the list"
);
tester.pump_widget(SizedBox::new().into_widget());
tester.pump_and_settle();
expect(tester, &find::by_type::<StretchEffect>(), finds_nothing());
});
}
#[test]
fn a_stretch_controller_frees_each_release_animation_it_replaces() {
test_widgets(|tester| {
tester.pump_widget(ltr(StretchingOverscrollIndicator::new(AxisDirection::Down)
.child(list_of_items(20, 100.0))));
let release_controller = |tester: &WidgetTester| {
let element = tester.element(find::by_type::<StretchingOverscrollIndicator>());
let mut app = tester.cell.borrow_mut();
let state = element
.state_handle::<StretchingOverscrollIndicatorState>(&app)
.expect("a mounted StretchingOverscrollIndicator");
let stretch = state.stretch_controller(&mut app);
app.get(stretch).controller.handle()
};
tester.fling_from(VIEW_CENTER, Offset::new(0.0, 300.0), 1000.0, 1);
tester.pump();
tester.pump_by(Duration::from_millis(100));
let first = release_controller(tester).expect("the fling animates the release");
tester.fling_from(VIEW_CENTER, Offset::new(0.0, 300.0), 1000.0, 2);
tester.pump();
tester.pump_by(Duration::from_millis(100));
let second = release_controller(tester).expect("the fling animates the release");
assert_ne!(first, second);
tester.cell.checkpoint();
assert!(
!tester.cell.borrow().contains(first),
"the replaced release's"
);
tester.pump_and_settle();
assert!(release_controller(tester).is_none());
tester.cell.checkpoint();
assert!(
!tester.cell.borrow().contains(second),
"the finished release's"
);
});
}
#[test]
fn a_glowing_indicator_lays_out_at_zero_area() {
test_widgets(|tester| {
let key = GlobalKey::new();
tester.pump_widget(ltr(Center::new().child(
SizedBox::shrink().child(
GlowingOverscrollIndicator::new(AxisDirection::Down, Color::new(0xFF112233))
.key(key.clone().into()),
),
)));
let app = tester.cell.borrow();
let size = key
.current_context(&app)
.and_then(|context| context.find_render_object(&app))
.and_then(|object| object.as_box())
.expect("the indicator is laid out")
.size(&app);
assert_eq!(size, Size::ZERO);
});
}
#[test]
fn a_stretching_indicator_lays_out_at_zero_area() {
test_widgets(|tester| {
let key = GlobalKey::new();
tester.pump_widget(ltr(Center::new().child(
SizedBox::shrink().child(
StretchingOverscrollIndicator::new(AxisDirection::Down)
.key(key.clone().into())
.child(ListView::new()),
),
)));
let app = tester.cell.borrow();
let size = key
.current_context(&app)
.and_then(|context| context.find_render_object(&app))
.and_then(|object| object.as_box())
.expect("the indicator is laid out")
.size(&app);
assert_eq!(size, Size::ZERO);
});
}
struct Boxes {
box1: GlobalKey,
box2: GlobalKey,
box3: GlobalKey,
controller: Ref<ScrollController>,
}
impl Boxes {
fn new(tester: &WidgetTester) -> Boxes {
Boxes {
box1: GlobalKey::new(),
box2: GlobalKey::new(),
box3: GlobalKey::new(),
controller: ScrollController::default(&mut tester.cell.borrow_mut()),
}
}
fn origins(&self, tester: &WidgetTester) -> [Offset; 3] {
[
origin_of(tester, &self.box1),
origin_of(tester, &self.box2),
origin_of(tester, &self.box3),
]
}
fn offset(&self, tester: &WidgetTester) -> f64 {
self.controller
.as_controller()
.offset(&tester.cell.borrow())
}
fn jump_to_max(&self, tester: &WidgetTester) {
let mut app = tester.cell.borrow_mut();
let controller = self.controller.as_controller();
let max = controller.position(&app).max_scroll_extent(&app);
controller.jump_to(&mut app, max);
}
}
struct BuildTest {
axis: Axis,
reverse: bool,
text_direction: TextDirection,
box_height: f64,
box_width: f64,
physics: Option<ScrollPhysicsRef>,
}
impl Default for BuildTest {
fn default() -> BuildTest {
BuildTest {
axis: Axis::Vertical,
reverse: false,
text_direction: TextDirection::Ltr,
box_height: 250.0,
box_width: 300.0,
physics: None,
}
}
}
fn no_overscroll_behavior() -> ScrollBehaviorRef {
ScrollBehaviorRef::new(ScrollBehaviorRef::plain().copy_with().overscroll(false))
}
fn build_test(boxes: &Boxes, options: BuildTest) -> WidgetRef {
let axis_direction = match options.axis {
Axis::Horizontal => match options.text_direction {
TextDirection::Rtl => {
if options.reverse {
AxisDirection::Right
} else {
AxisDirection::Left
}
}
TextDirection::Ltr => {
if options.reverse {
AxisDirection::Left
} else {
AxisDirection::Right
}
}
},
Axis::Vertical => {
if options.reverse {
AxisDirection::Up
} else {
AxisDirection::Down
}
}
};
let tile = |color: u32, key: &GlobalKey| {
SliverToBoxAdapter::new()
.child(
Container::new()
.color(Color::new(color))
.key(key.clone().into())
.height(options.box_height)
.width(options.box_width),
)
.into_widget()
};
let mut scroll_view = CustomScrollView::new()
.reverse(options.reverse)
.scroll_direction(options.axis)
.controller(boxes.controller.erase())
.slivers([
tile(0xD0FF0000, &boxes.box1),
tile(0xFFFFFF00, &boxes.box2),
tile(0xFF6200EA, &boxes.box3),
]);
if let Some(physics) = options.physics {
scroll_view = scroll_view.physics(physics);
}
Directionality::new(
options.text_direction,
MediaQuery::new(
MediaQueryData::new().size(WidgetTester::SIZE),
ScrollConfiguration::new(
no_overscroll_behavior(),
StretchingOverscrollIndicator::new(axis_direction).child(scroll_view),
)
.into_widget(),
)
.into_widget(),
)
.into_widget()
}
fn assert_one_stretching_indicator(tester: &WidgetTester) {
expect(
tester,
&find::by_type::<StretchingOverscrollIndicator>(),
finds_one_widget(),
);
expect(
tester,
&find::by_type::<GlowingOverscrollIndicator>(),
finds_nothing(),
);
}
#[test]
fn a_stretch_on_the_other_axis_does_nothing() {
test_widgets(|tester| {
let boxes = Boxes::new(tester);
tester.pump_widget(ltr(MediaQuery::new(
MediaQueryData::new().size(WidgetTester::SIZE),
ScrollConfiguration::new(
no_overscroll_behavior(),
StretchingOverscrollIndicator::new(AxisDirection::Right).child(
CustomScrollView::new()
.controller(boxes.controller.erase())
.slivers([
SliverToBoxAdapter::new()
.child(
Container::new()
.color(Color::new(0xD0FF0000))
.key(boxes.box1.clone().into())
.height(250.0),
)
.into_widget(),
SliverToBoxAdapter::new()
.child(
Container::new()
.color(Color::new(0xFFFFFF00))
.key(boxes.box2.clone().into())
.height(250.0)
.width(300.0),
)
.into_widget(),
]),
),
)
.into_widget(),
)
.into_widget()));
assert_one_stretching_indicator(tester);
assert_eq!(boxes.offset(tester), 0.0);
assert_eq!(origin_of(tester, &boxes.box1), Offset::ZERO);
assert_eq!(origin_of(tester, &boxes.box2), Offset::new(0.0, 250.0));
let mut gesture = TestPointer::touch(1);
tester.down(&mut gesture, VIEW_CENTER);
tester.move_by(&mut gesture, Offset::new(0.0, 200.0), true);
tester.pump_and_settle();
assert_eq!(origin_of(tester, &boxes.box1), Offset::ZERO);
assert_eq!(origin_of(tester, &boxes.box2).dy(), 250.0);
tester.up(&gesture);
tester.pump_and_settle();
assert_eq!(origin_of(tester, &boxes.box1), Offset::ZERO);
assert_eq!(origin_of(tester, &boxes.box2), Offset::new(0.0, 250.0));
});
}
#[test]
fn a_vertical_stretch_pulls_the_boxes_apart_at_either_end_and_releases() {
test_widgets(|tester| {
let boxes = Boxes::new(tester);
tester.pump_widget(build_test(&boxes, BuildTest::default()));
assert_one_stretching_indicator(tester);
assert_eq!(boxes.offset(tester), 0.0);
assert_eq!(
boxes.origins(tester),
[
Offset::ZERO,
Offset::new(0.0, 250.0),
Offset::new(0.0, 500.0)
]
);
let mut gesture = TestPointer::touch(1);
tester.down(&mut gesture, VIEW_CENTER);
tester.move_by(&mut gesture, Offset::new(0.0, 200.0), true);
tester.pump_and_settle();
let [box1, box2, box3] = boxes.origins(tester);
assert_eq!(box1, Offset::ZERO);
assert!(box2.dy() > 255.0, "{box2:?}");
assert!(box3.dy() > 510.0, "{box3:?}");
tester.up(&gesture);
tester.pump_and_settle();
assert_eq!(
boxes.origins(tester),
[
Offset::ZERO,
Offset::new(0.0, 250.0),
Offset::new(0.0, 500.0)
]
);
boxes.jump_to_max(tester);
tester.pump_and_settle();
assert_eq!(boxes.offset(tester), 150.0);
let [box1, box2, box3] = boxes.origins(tester);
assert_eq!(box1.dy(), -150.0);
assert_eq!(box2.dy(), 100.0);
assert_eq!(box3.dy(), 350.0);
let mut gesture = TestPointer::touch(2);
tester.down(&mut gesture, VIEW_CENTER);
tester.move_by(&mut gesture, Offset::new(0.0, -200.0), true);
tester.pump_and_settle();
let [box1, box2, box3] = boxes.origins(tester);
assert!(box1.dy() < -165.0, "{box1:?}");
assert!(box2.dy() < 90.0, "{box2:?}");
assert!(box3.dy() < 350.0, "{box3:?}");
tester.up(&gesture);
tester.pump_and_settle();
let [box1, box2, box3] = boxes.origins(tester);
assert_eq!(box1.dy(), -150.0);
assert_eq!(box2.dy(), 100.0);
assert_eq!(box3.dy(), 350.0);
});
}
#[test]
fn a_reversed_vertical_stretch_pulls_the_boxes_up() {
test_widgets(|tester| {
let boxes = Boxes::new(tester);
tester.pump_widget(build_test(
&boxes,
BuildTest {
reverse: true,
..BuildTest::default()
},
));
assert_one_stretching_indicator(tester);
assert_eq!(boxes.offset(tester), 0.0);
assert_eq!(
boxes.origins(tester),
[
Offset::new(0.0, 350.0),
Offset::new(0.0, 100.0),
Offset::new(0.0, -150.0)
]
);
let mut gesture = TestPointer::touch(1);
tester.down(&mut gesture, VIEW_CENTER);
tester.move_by(&mut gesture, Offset::new(0.0, -200.0), true);
tester.pump_and_settle();
let [box1, box2, box3] = boxes.origins(tester);
assert!(box1.dy() < 350.0, "{box1:?}");
assert!(box2.dy() < 100.0, "{box2:?}");
assert!(box3.dy() < -150.0, "{box3:?}");
});
}
#[test]
fn a_reversed_horizontal_stretch_pulls_the_boxes_left() {
test_widgets(|tester| {
let boxes = Boxes::new(tester);
tester.pump_widget(build_test(
&boxes,
BuildTest {
axis: Axis::Horizontal,
reverse: true,
..BuildTest::default()
},
));
assert_one_stretching_indicator(tester);
assert_eq!(boxes.offset(tester), 0.0);
assert_eq!(
boxes.origins(tester),
[
Offset::new(500.0, 0.0),
Offset::new(200.0, 0.0),
Offset::new(-100.0, 0.0)
]
);
let mut gesture = TestPointer::touch(1);
tester.down(&mut gesture, VIEW_CENTER);
tester.move_by(&mut gesture, Offset::new(-200.0, 0.0), true);
tester.pump_and_settle();
let [box1, box2, box3] = boxes.origins(tester);
assert!(box1.dx() < 500.0, "{box1:?}");
assert!(box2.dx() < 200.0, "{box2:?}");
assert!(box3.dx() < -100.0, "{box3:?}");
});
}
fn horizontal_stretch_at_both_ends(tester: &mut WidgetTester, options: BuildTest) {
let boxes = Boxes::new(tester);
tester.pump_widget(build_test(&boxes, options));
assert_one_stretching_indicator(tester);
assert_eq!(boxes.offset(tester), 0.0);
assert_eq!(
boxes.origins(tester),
[
Offset::ZERO,
Offset::new(300.0, 0.0),
Offset::new(600.0, 0.0)
]
);
let mut gesture = TestPointer::touch(2);
tester.down(&mut gesture, VIEW_CENTER);
tester.move_by(&mut gesture, Offset::new(200.0, 0.0), true);
tester.pump_and_settle();
let [box1, box2, box3] = boxes.origins(tester);
assert_eq!(box1, Offset::ZERO);
assert!(box2.dx() > 305.0, "{box2:?}");
assert!(box3.dx() > 610.0, "{box3:?}");
tester.up(&gesture);
tester.pump_and_settle();
assert_eq!(
boxes.origins(tester),
[
Offset::ZERO,
Offset::new(300.0, 0.0),
Offset::new(600.0, 0.0)
]
);
boxes.jump_to_max(tester);
tester.pump_and_settle();
assert_eq!(boxes.offset(tester), 100.0);
let [box1, box2, box3] = boxes.origins(tester);
assert_eq!(box1.dx(), -100.0);
assert_eq!(box2.dx(), 200.0);
assert_eq!(box3.dx(), 500.0);
let mut gesture = TestPointer::touch(3);
tester.down(&mut gesture, VIEW_CENTER);
tester.move_by(&mut gesture, Offset::new(-200.0, 0.0), true);
tester.pump_and_settle();
let [box1, box2, box3] = boxes.origins(tester);
assert!(box1.dx() < -116.0, "{box1:?}");
assert!(box2.dx() < 190.0, "{box2:?}");
assert!(box3.dx() < 500.0, "{box3:?}");
tester.up(&gesture);
tester.pump_and_settle();
let [box1, box2, box3] = boxes.origins(tester);
assert_eq!(box1.dx(), -100.0);
assert_eq!(box2.dx(), 200.0);
assert_eq!(box3.dx(), 500.0);
}
#[test]
fn a_reversed_right_to_left_stretch_pulls_the_boxes_apart_at_either_end() {
test_widgets(|tester| {
horizontal_stretch_at_both_ends(
tester,
BuildTest {
axis: Axis::Horizontal,
reverse: true,
text_direction: TextDirection::Rtl,
..BuildTest::default()
},
)
});
}
#[test]
fn a_horizontal_stretch_pulls_the_boxes_apart_at_either_end_and_releases() {
test_widgets(|tester| {
horizontal_stretch_at_both_ends(
tester,
BuildTest {
axis: Axis::Horizontal,
..BuildTest::default()
},
)
});
}
#[test]
fn a_stretch_filters_its_child_only_while_it_stretches() {
test_widgets(|tester| {
let boxes = Boxes::new(tester);
tester.pump_widget(build_test(
&boxes,
BuildTest {
axis: Axis::Horizontal,
..BuildTest::default()
},
));
assert!(!has_image_filter_layer(tester));
let mut gesture = TestPointer::touch(1);
tester.down(&mut gesture, VIEW_CENTER);
tester.move_by(&mut gesture, Offset::new(200.0, 0.0), true);
tester.pump_and_settle();
assert!(has_image_filter_layer(tester));
});
}
#[test]
fn a_right_to_left_stretch_pulls_the_boxes_left() {
test_widgets(|tester| {
let boxes = Boxes::new(tester);
tester.pump_widget(build_test(
&boxes,
BuildTest {
axis: Axis::Horizontal,
text_direction: TextDirection::Rtl,
..BuildTest::default()
},
));
assert_one_stretching_indicator(tester);
assert_eq!(boxes.offset(tester), 0.0);
assert_eq!(
boxes.origins(tester),
[
Offset::new(500.0, 0.0),
Offset::new(200.0, 0.0),
Offset::new(-100.0, 0.0)
]
);
let mut gesture = TestPointer::touch(1);
tester.down(&mut gesture, VIEW_CENTER);
tester.move_by(&mut gesture, Offset::new(-200.0, 0.0), true);
tester.pump_and_settle();
let [box1, box2, box3] = boxes.origins(tester);
assert!(box1.dx() < 500.0, "{box1:?}");
assert!(box2.dx() < 200.0, "{box2:?}");
assert!(box3.dx() < -100.0, "{box3:?}");
});
}
fn counting_listener(
child: WidgetRef,
count: &Rc<Cell<u32>>,
disallow: &Rc<Cell<bool>>,
) -> WidgetRef {
let count = Rc::clone(count);
let disallow = Rc::clone(disallow);
NotificationListener::<OverscrollIndicatorNotification>::new(child)
.on_notification(move |_app, notification| {
if disallow.get() {
notification.disallow_indicator();
}
count.set(count.get() + 1);
false
})
.into_widget()
}
#[test]
fn a_disallowed_stretch_leaves_the_boxes_in_place() {
test_widgets(|tester| {
let boxes = Boxes::new(tester);
let indicator_notification = Rc::new(Cell::new(0));
tester.pump_widget(counting_listener(
build_test(&boxes, BuildTest::default()),
&indicator_notification,
&Rc::new(Cell::new(true)),
));
assert_one_stretching_indicator(tester);
assert_eq!(indicator_notification.get(), 0);
assert_eq!(boxes.offset(tester), 0.0);
assert_eq!(
boxes.origins(tester),
[
Offset::ZERO,
Offset::new(0.0, 250.0),
Offset::new(0.0, 500.0)
]
);
let mut gesture = TestPointer::touch(1);
tester.down(&mut gesture, VIEW_CENTER);
tester.move_by(&mut gesture, Offset::new(0.0, 200.0), true);
tester.pump_and_settle();
assert_eq!(indicator_notification.get(), 1);
assert_eq!(
boxes.origins(tester),
[
Offset::ZERO,
Offset::new(0.0, 250.0),
Offset::new(0.0, 500.0)
]
);
tester.up(&gesture);
tester.pump_and_settle();
});
}
#[test]
fn a_disallowed_stretch_does_not_absorb_a_fling() {
test_widgets(|tester| {
let boxes = Boxes::new(tester);
let indicator_notification = Rc::new(Cell::new(0));
tester.pump_widget(counting_listener(
build_test(&boxes, BuildTest::default()),
&indicator_notification,
&Rc::new(Cell::new(true)),
));
assert_one_stretching_indicator(tester);
assert_eq!(indicator_notification.get(), 0);
boxes.jump_to_max(tester);
tester.pump();
{
let mut app = tester.cell.borrow_mut();
let position = boxes.controller.as_controller().position(&app);
let drag =
position.drag(&mut app, DragStartDetails::default(), Listener::new(|_| {}));
drag.update(
&mut app,
DragUpdateDetails::new(
Offset::ZERO,
None,
None,
Offset::new(0.0, -5000.0),
Some(-5000.0),
None,
),
);
drag.end(
&mut app,
DragEndDetails::new(
Offset::ZERO,
None,
Velocity {
pixels_per_second: Offset::new(0.0, -5000.0),
},
Some(-5000.0),
),
);
}
tester.pump();
tester.pump_by(Duration::from_millis(16));
assert_eq!(indicator_notification.get(), 1);
assert_eq!(stretch_strength(tester), 0.0);
});
}
#[test]
fn a_disallowed_stretch_is_allowed_again_in_the_next_scroll() {
test_widgets(|tester| {
let boxes = Boxes::new(tester);
let indicator_notification = Rc::new(Cell::new(0));
let disallow_stretch = Rc::new(Cell::new(true));
tester.pump_widget(counting_listener(
build_test(&boxes, BuildTest::default()),
&indicator_notification,
&disallow_stretch,
));
assert_one_stretching_indicator(tester);
assert_eq!(indicator_notification.get(), 0);
let mut disallowed_gesture = TestPointer::touch(1);
tester.down(&mut disallowed_gesture, VIEW_CENTER);
tester.move_by(&mut disallowed_gesture, Offset::new(0.0, 200.0), true);
tester.pump_and_settle();
tester.up(&disallowed_gesture);
tester.pump_and_settle();
assert_eq!(indicator_notification.get(), 1);
assert_eq!(stretch_strength(tester), 0.0);
disallow_stretch.set(false);
{
let mut app = tester.cell.borrow_mut();
let controller = boxes.controller.as_controller();
let max = controller.position(&app).max_scroll_extent(&app);
controller.jump_to(&mut app, max / 2.0);
}
tester.pump();
tester.fling_from(VIEW_CENTER, Offset::new(0.0, -50.0), 10000.0, 2);
tester.pump_by(Duration::from_millis(100));
tester.pump_by(Duration::from_millis(100));
tester.pump_by(Duration::from_millis(100));
assert_eq!(indicator_notification.get(), 2);
assert_ne!(stretch_strength(tester), 0.0);
});
}
fn padded_items() -> WidgetRef {
ListView::builder(|_app, _context, index| {
Some(
Padding::new(EdgeInsetsGeometry::all(10.0))
.child(Text::new(format!("Index {index}")))
.into_widget(),
)
})
.item_count(20)
.into_widget()
}
fn list_over_box(clip_behavior: Option<Clip>) -> WidgetRef {
let mut indicator = StretchingOverscrollIndicator::new(AxisDirection::Down)
.child(SizedBox::new().height(300.0).child(padded_items()));
if let Some(clip_behavior) = clip_behavior {
indicator = indicator.clip_behavior(clip_behavior);
}
ltr(MediaQuery::new(
MediaQueryData::new().size(WidgetTester::SIZE),
ScrollConfiguration::new(
no_overscroll_behavior(),
Column::new().children([
indicator.into_widget(),
Opacity::new(0.5)
.child(Container::new().color(Color::new(0xD0FF0000)).height(100.0))
.into_widget(),
]),
)
.into_widget(),
)
.into_widget())
}
#[test]
fn a_stretched_list_stays_in_its_container() {
test_widgets(|tester| {
tester.pump_widget(list_over_box(None));
expect(tester, &find::text("Index 1"), finds_one_widget());
assert_eq!(tester.get_center(find::text("Index 1")).dy(), 51.0);
let mut gesture = TestPointer::touch(1);
tester.down(&mut gesture, tester.get_center(find::text("Index 1")));
tester.move_by(&mut gesture, Offset::new(0.0, 200.0), true);
tester.pump_and_settle();
expect(tester, &find::text("Index 1"), finds_one_widget());
assert!(tester.get_center(find::text("Index 1")).dy() > 0.0);
assert_eq!(
first_clip_rect(tester),
Rect::from_ltwh(0.0, 0.0, 800.0, 300.0)
);
assert_eq!(first_clip_behavior(tester), Clip::HardEdge);
tester.up(&gesture);
tester.pump_and_settle();
});
}
#[test]
fn a_stretch_clips_only_while_it_stretches_a_viewport_smaller_than_the_screen() {
test_widgets(|tester| {
tester.pump_widget(list_over_box(None));
expect(tester, &find::text("Index 1"), finds_one_widget());
assert_eq!(tester.get_center(find::text("Index 1")).dy(), 51.0);
assert_eq!(first_clip_behavior(tester), Clip::None);
let mut gesture = TestPointer::touch(1);
tester.down(&mut gesture, tester.get_center(find::text("Index 1")));
tester.move_by(&mut gesture, Offset::new(0.0, 200.0), true);
tester.pump_and_settle();
expect(tester, &find::text("Index 1"), finds_one_widget());
assert!(tester.get_center(find::text("Index 1")).dy() > 0.0);
assert_eq!(first_clip_behavior(tester), Clip::HardEdge);
tester.up(&gesture);
tester.pump_and_settle();
});
}
#[test]
fn a_stretch_clips_with_the_clip_behavior_it_is_given() {
test_widgets(|tester| {
tester.pump_widget(list_over_box(Some(Clip::None)));
expect(tester, &find::text("Index 1"), finds_one_widget());
assert_eq!(tester.get_center(find::text("Index 1")).dy(), 51.0);
assert_eq!(first_clip_behavior(tester), Clip::None);
let mut gesture = TestPointer::touch(1);
tester.down(&mut gesture, tester.get_center(find::text("Index 1")));
tester.move_by(&mut gesture, Offset::new(0.0, 200.0), true);
tester.pump_and_settle();
expect(tester, &find::text("Index 1"), finds_one_widget());
assert!(tester.get_center(find::text("Index 1")).dy() > 0.0);
assert_eq!(first_clip_behavior(tester), Clip::None);
tester.up(&gesture);
tester.pump_and_settle();
});
}
fn list_alone() -> WidgetRef {
ltr(MediaQuery::new(
MediaQueryData::new(),
ScrollConfiguration::new(
no_overscroll_behavior(),
StretchingOverscrollIndicator::new(AxisDirection::Down)
.child(SizedBox::new().height(300.0).child(padded_items())),
)
.into_widget(),
)
.into_widget())
}
#[test]
fn a_stretch_stops_at_its_limit() {
test_widgets(|tester| {
tester.pump_widget(list_alone());
const MAX_STRETCH_LOCATION: f64 = 52.63178407049861;
expect(tester, &find::text("Index 1"), finds_one_widget());
assert_eq!(tester.get_center(find::text("Index 1")).dy(), 51.0);
let mut pointer = TestPointer::touch(1);
tester.down(&mut pointer, tester.get_center(find::text("Index 1")));
tester.move_by(&mut pointer, Offset::new(0.0, 610.0), true);
tester.pump_and_settle();
expect(tester, &find::text("Index 1"), finds_one_widget());
assert_f32_equals(
tester.get_center(find::text("Index 1")).dy(),
MAX_STRETCH_LOCATION,
);
let mut pointer = TestPointer::touch(2);
tester.down(&mut pointer, tester.get_center(find::text("Index 1")));
tester.move_by(&mut pointer, Offset::new(0.0, 1000.0), true);
tester.pump_and_settle();
expect(tester, &find::text("Index 1"), finds_one_widget());
assert_f32_equals(
tester.get_center(find::text("Index 1")).dy(),
MAX_STRETCH_LOCATION,
);
tester.up(&pointer);
tester.pump_and_settle();
});
}
#[test]
fn more_pointers_do_not_stretch_past_the_limit() {
test_widgets(|tester| {
tester.pump_widget(list_alone());
expect(tester, &find::text("Index 1"), finds_one_widget());
assert_eq!(tester.get_center(find::text("Index 1")).dy(), 51.0);
let mut pointer1 = TestPointer::touch(1);
tester.down(&mut pointer1, tester.get_center(find::text("Index 1")));
tester.move_by(&mut pointer1, Offset::new(0.0, 210.0), true);
tester.pump_and_settle();
expect(tester, &find::text("Index 1"), finds_one_widget());
let mut last_stretched_location = tester.get_center(find::text("Index 1")).dy();
assert!(last_stretched_location > 51.0);
let mut pointer2 = TestPointer::touch(2);
tester.down(&mut pointer2, tester.get_center(find::text("Index 1")));
tester.move_by(&mut pointer2, Offset::new(0.0, 210.0), true);
tester.pump_and_settle();
expect(tester, &find::text("Index 1"), finds_one_widget());
assert!(tester.get_center(find::text("Index 1")).dy() > last_stretched_location);
last_stretched_location = tester.get_center(find::text("Index 1")).dy();
let mut pointer3 = TestPointer::touch(3);
tester.down(&mut pointer3, tester.get_center(find::text("Index 1")));
tester.move_by(&mut pointer3, Offset::new(0.0, 210.0), true);
tester.pump_and_settle();
expect(tester, &find::text("Index 1"), finds_one_widget());
assert!(tester.get_center(find::text("Index 1")).dy() > last_stretched_location);
last_stretched_location = tester.get_center(find::text("Index 1")).dy();
let mut pointer4 = TestPointer::touch(4);
tester.down(&mut pointer4, tester.get_center(find::text("Index 1")));
tester.move_by(&mut pointer4, Offset::new(0.0, 210.0), true);
tester.pump_and_settle();
expect(tester, &find::text("Index 1"), finds_one_widget());
assert_eq!(
tester.get_center(find::text("Index 1")).dy(),
last_stretched_location
);
tester.up(&pointer1);
tester.up(&pointer2);
tester.up(&pointer3);
tester.up(&pointer4);
tester.pump_and_settle();
});
}
#[test]
fn a_vertical_stretch_turns_to_the_other_end_when_the_drag_does() {
test_widgets(|tester| {
let boxes = Boxes::new(tester);
tester.pump_widget(build_test(
&boxes,
BuildTest {
box_height: 100.0,
physics: Some(always_scrollable()),
..BuildTest::default()
},
));
assert_one_stretching_indicator(tester);
assert_eq!(boxes.offset(tester), 0.0);
assert_eq!(
boxes.origins(tester),
[
Offset::ZERO,
Offset::new(0.0, 100.0),
Offset::new(0.0, 200.0)
]
);
let mut gesture = TestPointer::touch(1);
tester.down(&mut gesture, VIEW_CENTER);
tester.move_by(&mut gesture, Offset::new(0.0, 600.0), true);
tester.pump_and_settle();
let [box1, box2, box3] = boxes.origins(tester);
assert_eq!(box1, Offset::ZERO);
assert!(box2.dy() > 103.0, "{box2:?}");
assert!(box3.dy() > 206.0, "{box3:?}");
tester.move_by(&mut gesture, Offset::new(0.0, -20.0), true);
tester.pump_and_settle();
let [box1, box2, box3] = boxes.origins(tester);
assert_eq!(box1, Offset::ZERO);
assert!(box2.dy() > 103.0, "{box2:?}");
assert!(box3.dy() > 206.0, "{box3:?}");
tester.move_by(&mut gesture, Offset::new(0.0, -1200.0), true);
tester.pump_and_settle();
let [box1, box2, box3] = boxes.origins(tester);
assert!(box1.dy() < -19.0, "{box1:?}");
assert!(box2.dy() < 85.0, "{box2:?}");
assert!(box3.dy() < 188.0, "{box3:?}");
tester.up(&gesture);
tester.pump_and_settle();
assert_eq!(
boxes.origins(tester),
[
Offset::ZERO,
Offset::new(0.0, 100.0),
Offset::new(0.0, 200.0)
]
);
});
}
#[test]
fn a_horizontal_stretch_turns_to_the_other_end_when_the_drag_does() {
test_widgets(|tester| {
let boxes = Boxes::new(tester);
tester.pump_widget(build_test(
&boxes,
BuildTest {
box_width: 100.0,
physics: Some(always_scrollable()),
axis: Axis::Horizontal,
..BuildTest::default()
},
));
assert_one_stretching_indicator(tester);
assert_eq!(boxes.offset(tester), 0.0);
assert_eq!(
boxes.origins(tester),
[
Offset::ZERO,
Offset::new(100.0, 0.0),
Offset::new(200.0, 0.0)
]
);
let mut gesture = TestPointer::touch(1);
tester.down(&mut gesture, VIEW_CENTER);
tester.move_by(&mut gesture, Offset::new(600.0, 0.0), true);
tester.pump_and_settle();
let [box1, box2, box3] = boxes.origins(tester);
assert_eq!(box1, Offset::ZERO);
assert!(box2.dx() > 102.0, "{box2:?}");
assert!(box3.dx() > 205.0, "{box3:?}");
tester.move_by(&mut gesture, Offset::new(-20.0, 0.0), true);
tester.pump_and_settle();
let [box1, box2, box3] = boxes.origins(tester);
assert_eq!(box1, Offset::ZERO);
assert!(box2.dx() > 102.0, "{box2:?}");
assert!(box3.dx() > 205.0, "{box3:?}");
tester.move_by(&mut gesture, Offset::new(-1200.0, 0.0), true);
tester.pump_and_settle();
let [box1, box2, box3] = boxes.origins(tester);
assert!(box1.dx() < -19.0, "{box1:?}");
assert!(box2.dx() < 85.0, "{box2:?}");
assert!(box3.dx() < 188.0, "{box3:?}");
tester.up(&gesture);
tester.pump_and_settle();
assert_eq!(
boxes.origins(tester),
[
Offset::ZERO,
Offset::new(100.0, 0.0),
Offset::new(200.0, 0.0)
]
);
});
}
#[test]
fn a_fling_into_the_trailing_edge_stretches_toward_the_leading_edge() {
test_widgets(|tester| {
let boxes = Boxes::new(tester);
tester.pump_widget(build_test(&boxes, BuildTest::default()));
assert_one_stretching_indicator(tester);
assert_eq!(boxes.offset(tester), 0.0);
assert_eq!(
boxes.origins(tester),
[
Offset::ZERO,
Offset::new(0.0, 250.0),
Offset::new(0.0, 500.0)
]
);
tester.fling_from(VIEW_CENTER, Offset::new(0.0, -50.0), 10000.0, 1);
tester.pump_by(Duration::from_millis(100));
tester.pump_by(Duration::from_millis(100));
tester.pump_by(Duration::from_millis(100));
assert_eq!(boxes.offset(tester), 150.0);
let [box1, box2, box3] = boxes.origins(tester);
assert!(box1.dy() < -160.0, "{box1:?}");
assert!(box2.dy() < 93.0, "{box2:?}");
assert!(box3.dy() < 347.0, "{box3:?}");
tester.pump_and_settle();
assert_eq!(boxes.offset(tester), 150.0);
let [box1, box2, box3] = boxes.origins(tester);
assert_eq!(box1.dy(), -150.0);
assert_eq!(box2.dy(), 100.0);
assert_eq!(box3.dy(), 350.0);
});
}
#[test]
fn a_fling_into_the_leading_edge_stretches_toward_the_trailing_edge() {
test_widgets(|tester| {
let boxes = Boxes::new(tester);
tester.pump_widget(build_test(&boxes, BuildTest::default()));
assert_one_stretching_indicator(tester);
assert_eq!(boxes.offset(tester), 0.0);
assert_eq!(
boxes.origins(tester),
[
Offset::ZERO,
Offset::new(0.0, 250.0),
Offset::new(0.0, 500.0)
]
);
tester.fling_from(VIEW_CENTER, Offset::new(0.0, -50.0), 10000.0, 1);
tester.pump_and_settle();
assert_eq!(boxes.offset(tester), 150.0);
let [box1, box2, box3] = boxes.origins(tester);
assert_eq!(box1.dy(), -150.0);
assert_eq!(box2.dy(), 100.0);
assert_eq!(box3.dy(), 350.0);
tester.fling_from(VIEW_CENTER, Offset::new(0.0, 50.0), 10000.0, 2);
tester.pump_by(Duration::from_millis(100));
tester.pump_by(Duration::from_millis(100));
tester.pump_by(Duration::from_millis(100));
tester.pump_by(Duration::from_millis(100));
assert_eq!(boxes.offset(tester), 0.0);
let [box1, box2, box3] = boxes.origins(tester);
assert_eq!(box1.dy(), 0.0);
assert!(box2.dy() > 250.9, "{box2:?}");
assert!(box3.dy() > 500.9, "{box3:?}");
tester.pump_and_settle();
assert_eq!(boxes.offset(tester), 0.0);
let [box1, box2, box3] = boxes.origins(tester);
assert_eq!(box1.dy(), 0.0);
assert_eq!(box2.dy(), 250.0);
assert_eq!(box3.dy(), 500.0);
});
}
#[test]
fn turning_the_drag_while_the_stretch_recedes_keeps_its_direction() {
test_widgets(|tester| {
let boxes = Boxes::new(tester);
tester.pump_widget(build_test(
&boxes,
BuildTest {
box_height: 205.0,
..BuildTest::default()
},
));
assert_one_stretching_indicator(tester);
tester.fling_from(VIEW_CENTER, Offset::new(0.0, -50.0), 10000.0, 1);
tester.pump_and_settle();
let [box1, box2, box3] = boxes.origins(tester);
assert_eq!(box1.dy(), -15.0);
assert_eq!(box2.dy(), 190.0);
assert_eq!(box3.dy(), 395.0);
let mut gesture = TestPointer::touch(2);
tester.down(&mut gesture, VIEW_CENTER);
tester.move_by(&mut gesture, Offset::new(0.0, -200.0), true);
tester.pump_and_settle();
let [box1, box2, box3] = boxes.origins(tester);
assert!(box1.dy() < -25.0, "{box1:?}");
assert!(box2.dy() < 185.0, "{box2:?}");
assert!(box3.dy() < 392.0, "{box3:?}");
tester.move_by(&mut gesture, Offset::new(0.0, 150.0), true);
tester.pump_by(Duration::from_millis(100));
assert_ne!(stretch_strength(tester), 0.0);
tester.up(&gesture);
tester.pump_by(Duration::from_millis(100));
assert!(stretch_strength(tester).abs() < 0.01);
tester.pump_and_settle();
let [box1, box2, box3] = boxes.origins(tester);
assert_eq!(box1.dy(), 0.0);
assert_eq!(box2.dy(), 205.0);
assert_eq!(box3.dy(), 410.0);
});
}
#[derive(Debug)]
struct HighFrictionClampingScrollPhysics {
parent: Option<ScrollPhysicsRef>,
}
impl ScrollPhysics for HighFrictionClampingScrollPhysics {
fn as_any(&self) -> &dyn std::any::Any {
self
}
fn parent(&self) -> Option<&ScrollPhysicsRef> {
self.parent.as_ref()
}
fn apply_to(&self, ancestor: Option<ScrollPhysicsRef>) -> ScrollPhysicsRef {
Rc::new(HighFrictionClampingScrollPhysics {
parent: ScrollPhysicsBase::build_parent(self, ancestor),
})
}
fn create_ballistic_simulation(
&self,
position: &dyn ScrollMetrics,
velocity: f64,
) -> Option<Box<dyn Simulation>> {
Some(Box::new(ClampingScrollSimulation::with_options(
position.pixels(),
velocity,
0.94,
self.tolerance_for(position),
)))
}
}
#[test]
fn a_stretch_settles_after_a_fling_under_high_friction() {
test_widgets(|tester| {
let boxes = Boxes::new(tester);
let overscroll_velocity: Rc<Cell<Option<f64>>> = Rc::default();
let tree = NotificationListener::<OverscrollNotification>::new(build_test(
&boxes,
BuildTest {
physics: Some(Rc::new(HighFrictionClampingScrollPhysics { parent: None })),
..BuildTest::default()
},
))
.on_notification({
let overscroll_velocity = Rc::clone(&overscroll_velocity);
move |_app, notification| {
overscroll_velocity.set(Some(notification.velocity));
false
}
})
.into_widget();
tester.pump_widget(tree);
assert_one_stretching_indicator(tester);
assert_eq!(boxes.offset(tester), 0.0);
assert_eq!(
boxes.origins(tester),
[
Offset::ZERO,
Offset::new(0.0, 250.0),
Offset::new(0.0, 500.0)
]
);
tester.fling_from(VIEW_CENTER, Offset::new(0.0, -50.0), 10000.0, 1);
tester.pump_and_settle_by(Duration::from_millis(300));
assert!(overscroll_velocity.get().expect("an overscroll") < 25.0);
assert_eq!(boxes.offset(tester), 150.0);
let [box1, box2, box3] = boxes.origins(tester);
assert_eq!(box1.dy(), -150.0);
assert_eq!(box2.dy(), 100.0);
assert_eq!(box3.dy(), 350.0);
});
}
#[test]
fn a_short_fling_into_the_edge_keeps_stretching_after_it_ends() {
test_widgets(|tester| {
let boxes = Boxes::new(tester);
let tree = build_test(&boxes, BuildTest::default());
tester.pump_widget(tree.clone());
assert_one_stretching_indicator(tester);
assert_eq!(boxes.offset(tester), 0.0);
assert_eq!(
boxes.origins(tester),
[
Offset::ZERO,
Offset::new(0.0, 250.0),
Offset::new(0.0, 500.0)
]
);
tester.fling_from(VIEW_CENTER, Offset::new(0.0, 50.0), 1000.0, 1);
let progress_strength = stretch_strength(tester);
tester.pump_frames(tree, Duration::from_millis(50));
assert!(stretch_strength(tester) > progress_strength);
tester.pump_and_settle();
assert_eq!(stretch_strength(tester).abs(), 0.0);
});
}
#[test]
fn a_short_fling_into_the_reversed_edge_keeps_stretching_after_it_ends() {
test_widgets(|tester| {
let boxes = Boxes::new(tester);
let tree = build_test(
&boxes,
BuildTest {
reverse: true,
..BuildTest::default()
},
);
tester.pump_widget(tree.clone());
assert_one_stretching_indicator(tester);
assert_eq!(boxes.offset(tester), 0.0);
assert_eq!(
boxes.origins(tester),
[
Offset::new(0.0, 350.0),
Offset::new(0.0, 100.0),
Offset::new(0.0, -150.0)
]
);
tester.fling_from(VIEW_CENTER, Offset::new(0.0, -50.0), 1000.0, 1);
let progress_strength = stretch_strength(tester);
tester.pump_frames(tree, Duration::from_millis(50));
assert!(stretch_strength(tester) < progress_strength);
tester.pump_and_settle();
assert_eq!(stretch_strength(tester).abs(), 0.0);
});
}
#[test]
fn a_confirmation_describes_its_side_and_can_be_disallowed() {
let notification = OverscrollIndicatorNotification::new(true);
assert!(notification.accepted.get());
notification.disallow_indicator();
assert!(!notification.accepted.get());
assert_eq!(
format!("{notification:?}"),
"OverscrollIndicatorNotification(depth: 0 (local), side: leading edge)"
);
assert_eq!(
format!("{:?}", OverscrollIndicatorNotification::new(false)),
"OverscrollIndicatorNotification(depth: 0 (local), side: trailing edge)"
);
}
}