1use std::any::Any;
4use std::fmt::{self, Debug};
5use std::rc::Rc;
6use std::time::Duration;
7
8use waft_animation::Curves;
9use waft_embedder::{Clip, Offset, Rect, Size};
10use waft_foundation::{App, Handle, Listener, PRECISION_ERROR_TOLERANCE, Task};
11use waft_painting::{Axis, AxisDirection, axis_direction_to_axis, transform_rect};
12
13use crate::framework::{BuildContext, State};
14use crate::widgets::actions::{Action, ActionData, ContextAction, Intent};
15use crate::widgets::primary_scroll_controller::PrimaryScrollController;
16use crate::widgets::scroll_context::ScrollContext;
17use crate::widgets::scroll_controller::ScrollControllerRef;
18use crate::widgets::scroll_metrics::ScrollMetrics;
19use crate::widgets::scroll_physics::ScrollPhysicsRef;
20use crate::widgets::scrollable::{Scrollable, ScrollableState};
21use waft_foundation::Ref;
22
23#[derive(Clone)]
30pub struct ScrollableDetails {
31 pub direction: AxisDirection,
33
34 pub controller: Option<ScrollControllerRef>,
36
37 pub physics: Option<ScrollPhysicsRef>,
39
40 pub decoration_clip_behavior: Option<Clip>,
47}
48
49impl ScrollableDetails {
50 pub fn new(direction: AxisDirection) -> ScrollableDetails {
52 ScrollableDetails {
53 direction,
54 controller: None,
55 physics: None,
56 decoration_clip_behavior: None,
57 }
58 }
59
60 pub fn vertical(reverse: bool) -> ScrollableDetails {
62 ScrollableDetails::new(if reverse {
63 AxisDirection::Up
64 } else {
65 AxisDirection::Down
66 })
67 }
68
69 pub fn horizontal(reverse: bool) -> ScrollableDetails {
71 ScrollableDetails::new(if reverse {
72 AxisDirection::Left
73 } else {
74 AxisDirection::Right
75 })
76 }
77
78 pub fn controller(mut self, controller: ScrollControllerRef) -> ScrollableDetails {
80 self.controller = Some(controller);
81 self
82 }
83
84 pub fn physics(mut self, physics: ScrollPhysicsRef) -> ScrollableDetails {
86 self.physics = Some(physics);
87 self
88 }
89
90 pub fn decoration_clip_behavior(mut self, decoration_clip_behavior: Clip) -> ScrollableDetails {
92 self.decoration_clip_behavior = Some(decoration_clip_behavior);
93 self
94 }
95
96 #[deprecated(
99 note = "Migrate to decoration_clip_behavior. This property was deprecated so that its \
100 application is clearer. This clip applies to decorators, and does not directly \
101 clip a scroll view. This feature was deprecated after v3.9.0-1.0.pre."
102 )]
103 pub fn clip_behavior(self, clip_behavior: Clip) -> ScrollableDetails {
104 self.decoration_clip_behavior(clip_behavior)
105 }
106
107 pub fn copy_with(&self) -> ScrollableDetails {
110 self.clone()
111 }
112}
113
114impl PartialEq for ScrollableDetails {
115 fn eq(&self, other: &ScrollableDetails) -> bool {
116 self.direction == other.direction
117 && self.controller == other.controller
118 && match (&self.physics, &other.physics) {
119 (None, None) => true,
120 (Some(physics), Some(other)) => Rc::ptr_eq(physics, other),
121 _ => false,
122 }
123 && self.decoration_clip_behavior == other.decoration_clip_behavior
124 }
125}
126
127impl Debug for ScrollableDetails {
128 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
129 let mut description = vec![format!("axisDirection: {:?}", self.direction)];
130 if self.controller.is_some() {
131 description.push("scroll controller: attached".to_string());
132 }
133 if let Some(physics) = &self.physics {
134 description.push(format!("scroll physics: {physics:?}"));
135 }
136 if let Some(clip) = self.decoration_clip_behavior {
137 description.push(format!("decorationClipBehavior: {clip:?}"));
138 }
139 write!(f, "ScrollableDetails({})", description.join(", "))
140 }
141}
142
143pub struct EdgeDraggingAutoScroller {
150 pub scrollable: Handle<ScrollableState>,
152
153 pub on_scroll_view_scrolled: Option<Listener>,
159
160 pub velocity_scalar: f64,
165
166 drag_target_related_to_scroll_origin: Option<Rect>,
170
171 scrolling: bool,
172}
173
174impl EdgeDraggingAutoScroller {
175 pub fn new(
177 app: &mut App,
178 scrollable: Handle<ScrollableState>,
179 on_scroll_view_scrolled: Option<Listener>,
180 velocity_scalar: f64,
181 ) -> Ref<EdgeDraggingAutoScroller> {
182 app.create(EdgeDraggingAutoScroller {
183 scrollable,
184 on_scroll_view_scrolled,
185 velocity_scalar,
186 drag_target_related_to_scroll_origin: None,
187 scrolling: false,
188 })
189 }
190
191 pub fn scrolling(self: Handle<Self>, app: &App) -> bool {
193 app.get(self).scrolling
194 }
195
196 fn offset_extent(offset: Offset, scroll_direction: Axis) -> f64 {
197 match scroll_direction {
198 Axis::Horizontal => offset.dx(),
199 Axis::Vertical => offset.dy(),
200 }
201 }
202
203 fn size_extent(size: Size, scroll_direction: Axis) -> f64 {
204 match scroll_direction {
205 Axis::Horizontal => size.width(),
206 Axis::Vertical => size.height(),
207 }
208 }
209
210 fn axis_direction(self: Handle<Self>, app: &App) -> AxisDirection {
211 app.get(self).scrollable.axis_direction(app)
212 }
213
214 fn scroll_direction(self: Handle<Self>, app: &App) -> Axis {
215 axis_direction_to_axis(self.axis_direction(app))
216 }
217
218 pub fn start_auto_scroll_if_necessary(self: Handle<Self>, app: &mut App, drag_target: Rect) {
231 let scrollable = app.get(self).scrollable;
232 let physics = scrollable.resolved_physics(app);
233 if let Some(physics) = physics
234 && !physics.should_accept_user_offset(&*scrollable.position(app).copy_with(app))
235 {
236 self.stop_auto_scroll(app);
237 return;
238 }
239 let delta_to_origin = scrollable.delta_to_scroll_origin(app);
240 app.get_mut(self).drag_target_related_to_scroll_origin =
241 Some(drag_target.translate(delta_to_origin.dx(), delta_to_origin.dy()));
242 if app.get(self).scrolling {
243 return;
245 }
246 debug_assert!(!app.get(self).scrolling);
247 drop(self.scroll(app));
249 }
250
251 pub fn stop_auto_scroll(self: Handle<Self>, app: &mut App) {
253 app.get_mut(self).scrolling = false;
254 }
255
256 fn scroll(self: Handle<Self>, app: &mut App) -> Task<()> {
259 let scrollable = app.get(self).scrollable;
260 let scroll_render_box = scrollable
261 .context(app)
262 .find_render_object(app)
263 .and_then(|object| object.as_box())
264 .expect("a Scrollable's render object is a RenderBox");
265 let transform = scroll_render_box.as_object().get_transform_to(app, None);
266 let size = scroll_render_box.size(app);
267 let global_rect = transform_rect(
268 &transform,
269 Rect::from_ltwh(0.0, 0.0, size.width(), size.height()),
270 );
271 let drag_target_related_to_scroll_origin = app
272 .get(self)
273 .drag_target_related_to_scroll_origin
274 .expect("startAutoScrollIfNecessary sets the drag target before a scroll");
275 let transformed_drag_target =
276 transform_rect(&transform, drag_target_related_to_scroll_origin);
277
278 debug_assert!(
279 (global_rect.size().width() + PRECISION_ERROR_TOLERANCE)
280 >= transformed_drag_target.size().width()
281 && (global_rect.size().height() + PRECISION_ERROR_TOLERANCE)
282 >= transformed_drag_target.size().height(),
283 "Drag target size is larger than scrollable size, which may cause bouncing"
284 );
285 app.get_mut(self).scrolling = true;
286 let mut new_offset: Option<f64> = None;
287 const OVER_DRAG_MAX: f64 = 20.0;
288
289 let delta_to_origin = scrollable.delta_to_scroll_origin(app);
290 let viewport_origin = global_rect
291 .top_left()
292 .translate(delta_to_origin.dx(), delta_to_origin.dy());
293 let scroll_direction = self.scroll_direction(app);
294 let viewport_start = Self::offset_extent(viewport_origin, scroll_direction);
295 let viewport_end = viewport_start + Self::size_extent(global_rect.size(), scroll_direction);
296
297 let proxy_start = Self::offset_extent(
298 drag_target_related_to_scroll_origin.top_left(),
299 scroll_direction,
300 );
301 let proxy_end = Self::offset_extent(
302 drag_target_related_to_scroll_origin.bottom_right(),
303 scroll_direction,
304 );
305 let position = scrollable.position(app);
306 let pixels = position.pixels(app);
307 let (min_scroll_extent, max_scroll_extent) = (
308 position.min_scroll_extent(app),
309 position.max_scroll_extent(app),
310 );
311 match self.axis_direction(app) {
312 AxisDirection::Up | AxisDirection::Left => {
313 if proxy_end > viewport_end && pixels > min_scroll_extent {
314 let over_drag = (proxy_end - viewport_end).min(OVER_DRAG_MAX);
315 new_offset = Some(min_scroll_extent.max(pixels - over_drag));
316 } else if proxy_start < viewport_start && pixels < max_scroll_extent {
317 let over_drag = (viewport_start - proxy_start).min(OVER_DRAG_MAX);
318 new_offset = Some(max_scroll_extent.min(pixels + over_drag));
319 }
320 }
321 AxisDirection::Right | AxisDirection::Down => {
322 if proxy_start < viewport_start && pixels > min_scroll_extent {
323 let over_drag = (viewport_start - proxy_start).min(OVER_DRAG_MAX);
324 new_offset = Some(min_scroll_extent.max(pixels - over_drag));
325 } else if proxy_end > viewport_end && pixels < max_scroll_extent {
326 let over_drag = (proxy_end - viewport_end).min(OVER_DRAG_MAX);
327 new_offset = Some(max_scroll_extent.min(pixels + over_drag));
328 }
329 }
330 }
331
332 let Some(new_offset) = new_offset.filter(|new_offset| (new_offset - pixels).abs() >= 1.0)
333 else {
334 app.get_mut(self).scrolling = false;
336 return Task::ready(());
337 };
338 let velocity_scalar = app.get(self).velocity_scalar;
339 let duration = Duration::from_millis((1000.0 / velocity_scalar).round() as u64);
340 let animated = position.animate_to(app, new_offset, duration, Curves::linear());
341 let kept = self.keep(app);
343 app.spawn(async move |cx| {
344 let _kept = kept;
345 animated.await;
346 let scrolling = cx.update(|app| {
347 if let Some(on_scroll_view_scrolled) = app.get(self).on_scroll_view_scrolled.clone()
348 {
349 on_scroll_view_scrolled.call(app);
350 }
351 app.get(self).scrolling
352 });
353 if scrolling {
354 cx.update(|app| self.scroll(app)).await;
355 }
356 })
357 }
358}
359
360pub type ScrollIncrementCalculator = Rc<dyn Fn(&ScrollIncrementDetails) -> f64>;
366
367#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
381pub enum ScrollIncrementType {
382 Line,
390
391 Page,
399}
400
401pub struct ScrollIncrementDetails {
405 pub r#type: ScrollIncrementType,
407
408 pub metrics: Rc<dyn ScrollMetrics>,
410}
411
412impl ScrollIncrementDetails {
413 pub fn new(
415 r#type: ScrollIncrementType,
416 metrics: Rc<dyn ScrollMetrics>,
417 ) -> ScrollIncrementDetails {
418 ScrollIncrementDetails { r#type, metrics }
419 }
420}
421
422impl Debug for ScrollIncrementDetails {
423 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
424 f.debug_struct("ScrollIncrementDetails")
425 .field("type", &self.r#type)
426 .field("metrics", &self.metrics)
427 .finish()
428 }
429}
430
431#[derive(Clone, Copy, Debug, PartialEq, Eq)]
438pub struct ScrollIntent {
439 pub direction: AxisDirection,
442
443 pub r#type: ScrollIncrementType,
445}
446
447impl ScrollIntent {
448 pub const fn new(direction: AxisDirection) -> ScrollIntent {
451 ScrollIntent {
452 direction,
453 r#type: ScrollIncrementType::Line,
454 }
455 }
456
457 pub const fn r#type(mut self, r#type: ScrollIncrementType) -> ScrollIntent {
459 self.r#type = r#type;
460 self
461 }
462}
463
464impl Intent for ScrollIntent {
465 fn as_any(&self) -> &dyn Any {
466 self
467 }
468}
469
470pub struct ScrollAction {
482 action: ActionData,
483}
484
485impl ScrollAction {
486 pub fn new(app: &mut App) -> Ref<ScrollAction> {
488 app.create(ScrollAction {
489 action: ActionData::new(),
490 })
491 }
492
493 fn calculate_scroll_increment(
501 app: &mut App,
502 state: Handle<ScrollableState>,
503 r#type: ScrollIncrementType,
504 ) -> f64 {
505 let position = state.position(app);
506 debug_assert!(position.has_pixels(app));
507 debug_assert!(
508 state
509 .resolved_physics(app)
510 .is_none_or(|physics| physics.should_accept_user_offset(&*position.copy_with(app)))
511 );
512 if let Some(increment_calculator) = state.widget(app).increment_calculator.clone() {
513 let metrics = position.copy_with(app);
514 return increment_calculator(&ScrollIncrementDetails::new(r#type, metrics));
515 }
516 match r#type {
517 ScrollIncrementType::Line => 50.0,
518 ScrollIncrementType::Page => 0.8 * position.viewport_dimension(app),
519 }
520 }
521
522 pub fn get_directional_increment(
525 app: &mut App,
526 state: Handle<ScrollableState>,
527 intent: &ScrollIntent,
528 ) -> f64 {
529 if axis_direction_to_axis(intent.direction)
530 == axis_direction_to_axis(state.axis_direction(app))
531 {
532 let increment = ScrollAction::calculate_scroll_increment(app, state, intent.r#type);
533 return if intent.direction == state.axis_direction(app) {
534 increment
535 } else {
536 -increment
537 };
538 }
539 0.0
540 }
541}
542
543impl Action for ScrollAction {
544 type Intent = ScrollIntent;
545 crate::action_accessors!();
546 crate::context_action_overrides!();
547}
548
549impl ContextAction for ScrollAction {
550 fn is_enabled(
551 self: Handle<Self>,
552 app: &mut App,
553 _intent: &ScrollIntent,
554 context: Option<BuildContext>,
555 ) -> bool {
556 let Some(context) = context else {
557 return false;
558 };
559 if Scrollable::maybe_of(app, context, None).is_some() {
560 return true;
561 }
562 PrimaryScrollController::maybe_of(app, context)
563 .is_some_and(|controller| controller.has_clients(app))
564 }
565
566 fn invoke(
567 self: Handle<Self>,
568 app: &mut App,
569 intent: &ScrollIntent,
570 context: Option<BuildContext>,
571 ) -> Option<Rc<dyn Any>> {
572 let context = context.expect("Cannot scroll without a context.");
573 let mut state = Scrollable::maybe_of(app, context, None);
574 if state.is_none() {
575 let primary_scroll_controller = PrimaryScrollController::of(app, context);
576 debug_assert!(
577 primary_scroll_controller.positions(app).len() == 1,
578 "A ScrollAction was invoked with the PrimaryScrollController, but more than one \
579 ScrollPosition is attached. Only one ScrollPosition can be manipulated by a \
580 ScrollAction at a time."
581 );
582
583 let notification_context = primary_scroll_controller
584 .position(app)
585 .context(app)
586 .notification_context(app);
587 if let Some(notification_context) = notification_context {
588 state = Scrollable::maybe_of(app, notification_context, None);
589 }
590 }
591 let state = state?;
592 debug_assert!(
593 state.position(app).has_pixels(app),
594 "Scrollable must be laid out before it can be scrolled via a ScrollAction"
595 );
596
597 let position = state.position(app);
599 if let Some(physics) = state.resolved_physics(app)
600 && !physics.should_accept_user_offset(&*position.copy_with(app))
601 {
602 return None;
603 }
604 let increment = ScrollAction::get_directional_increment(app, state, intent);
605 if increment == 0.0 {
606 return None;
607 }
608 position.move_to(
609 app,
610 position.pixels(app) + increment,
611 Some(Duration::from_millis(100)),
612 Some(Curves::ease_in_out()),
613 None,
614 );
615 None
616 }
617}
618
619#[cfg(test)]
620mod tests {
621 use std::any::TypeId;
622 use std::cell::Cell;
623 use std::collections::HashMap;
624
625 use waft_embedder::Offset;
626 use waft_foundation::{App, AppCell};
627 use waft_painting::Axis;
628 use waft_rendering::{
629 AnyRenderObject, BoxConstraints, RenderBox, RenderConstrainedBox, RenderHandle,
630 RenderSliver, RenderSliverToBoxAdapter, RenderViewport, RenderViewportBase,
631 };
632
633 use super::*;
634 use crate::framework::{
635 Element, IntoWidget, LeafRenderObjectWidget, RenderObjectWidget, WidgetRef,
636 };
637 use crate::test_harness::pump_every_view;
638 use crate::test_harness::{Harness, VIEW_HEIGHT};
639 use crate::widgets::actions::{Actions, AnyAction};
640 use crate::widgets::basic::Builder;
641 use crate::widgets::media_query::{MediaQuery, MediaQueryData};
642 use crate::widgets::scroll_physics::NeverScrollableScrollPhysics;
643 use crate::widgets::scrollable::ViewportBuilder;
644 use waft_rendering::ViewportOffsetRef;
645
646 #[derive(Debug)]
648 struct TestViewport {
649 offset: ViewportOffsetRef,
650 }
651
652 impl RenderObjectWidget for TestViewport {
653 type RenderObject = RenderViewport;
654
655 fn create_render_object(&self, app: &mut App, _context: BuildContext) -> AnyRenderObject {
656 let content = RenderConstrainedBox::new(
657 app,
658 BoxConstraints::tight(waft_embedder::Size::new(300.0, 800.0)),
659 None,
660 );
661 let sliver = RenderSliverToBoxAdapter::new(app, Some(RenderBox::as_box(content)));
662 RenderViewport::new(
663 app,
664 AxisDirection::Right,
665 self.offset.clone(),
666 Some(vec![RenderSliver::as_sliver(sliver)]),
667 None,
668 )
669 .as_object()
670 }
671
672 fn update_render_object(
673 &self,
674 app: &mut App,
675 _context: BuildContext,
676 render_object: RenderHandle<RenderViewport>,
677 ) {
678 RenderViewportBase::set_offset(render_object, app, self.offset.clone());
679 }
680 }
681
682 impl LeafRenderObjectWidget for TestViewport {}
683
684 fn mount_scroll_action(
687 app: &mut App,
688 configure: impl FnOnce(Scrollable) -> Scrollable,
689 ) -> (Harness, Handle<ScrollableState>, BuildContext) {
690 let captured: Rc<Cell<Option<BuildContext>>> = Rc::default();
691 let sink = Rc::clone(&captured);
692 let viewport: ViewportBuilder = Rc::new(move |_app, _context, offset| {
693 let sink = Rc::clone(&sink);
694 let probe = Builder::new(move |_app, context| {
695 sink.set(Some(context));
696 TestViewport {
697 offset: offset.clone(),
698 }
699 .into_widget()
700 });
701 probe.into_widget()
702 });
703 let action = ScrollAction::new(app);
704 let actions = HashMap::from([(TypeId::of::<ScrollIntent>(), action.erase::<AnyAction>())]);
705 let scrollable = configure(Scrollable::new(viewport));
706 let tree: WidgetRef =
707 MediaQuery::new(MediaQueryData::new(), Actions::new(actions, scrollable)).into_widget();
708 let harness = Harness::mount(app, tree);
709 harness.pump(app);
710 let mut element = harness.root.as_element();
711 let state = loop {
712 element = element.children(app)[0];
713 if let Some(state) = element.state_handle::<ScrollableState>(app) {
714 break state;
715 }
716 };
717 let context = captured.get().expect("the viewport built");
718 (harness, state, context)
719 }
720
721 fn pump_frame_and_checkpoint(cell: &AppCell, at: Duration) {
723 pump_every_view(&mut cell.borrow_mut(), at);
724 cell.checkpoint();
725 }
726
727 struct AutoScrollDrag {
729 scroller: Ref<EdgeDraggingAutoScroller>,
730 scrolls: Rc<Cell<usize>>,
732 dragging: Rc<Cell<bool>>,
734 }
735
736 fn auto_scroll_drag(
740 app: &mut App,
741 state: Handle<ScrollableState>,
742 drag_target: Rect,
743 ) -> AutoScrollDrag {
744 let scrolls = Rc::new(Cell::new(0));
745 let dragging = Rc::new(Cell::new(true));
746 let scroller_slot: Rc<Cell<Option<Handle<EdgeDraggingAutoScroller>>>> = Rc::default();
747 let counter = Rc::clone(&scrolls);
748 let in_progress = Rc::clone(&dragging);
749 let slot = Rc::clone(&scroller_slot);
750 let on_scrolled = Listener::new(move |app| {
751 counter.set(counter.get() + 1);
752 if !in_progress.get() {
753 return;
754 }
755 if let Some(scroller) = slot.get() {
756 scroller.start_auto_scroll_if_necessary(app, drag_target);
757 }
758 });
759 let scroller = EdgeDraggingAutoScroller::new(app, state, Some(on_scrolled), 50.0);
761 scroller_slot.set(Some(scroller.handle()));
762 AutoScrollDrag {
763 scroller,
764 scrolls,
765 dragging,
766 }
767 }
768
769 #[test]
772 fn an_auto_scroller_keeps_scrolling_while_the_drag_target_hangs_over_the_edge() {
773 let cell = AppCell::new();
774 let mut app = cell.borrow_mut();
775 let (_harness, state, _context) = mount_scroll_action(&mut app, |scrollable| scrollable);
776 let drag_target = Rect::from_ltwh(0.0, VIEW_HEIGHT - 10.0, 50.0, 20.0);
777 let AutoScrollDrag {
778 scroller,
779 scrolls,
780 dragging,
781 } = auto_scroll_drag(&mut app, state, drag_target);
782 assert!(!scroller.scrolling(&app));
783
784 scroller.start_auto_scroll_if_necessary(&mut app, drag_target);
785 assert!(scroller.scrolling(&app));
786 assert_eq!(
787 state.position(&app).pixels(&app),
788 0.0,
789 "the animation has not ticked"
790 );
791 drop(app);
792
793 for frame in 0..=8 {
796 pump_frame_and_checkpoint(&cell, Duration::from_millis(20 * frame));
797 let app = cell.borrow();
798 assert!(
799 state.position(&app).pixels(&app) >= 10.0 * scrolls.get() as f64,
800 "every reported scroll moved 10 pixels"
801 );
802 }
803 let app = cell.borrow();
804 assert_eq!(scrolls.get(), 3);
805 assert!(scroller.scrolling(&app));
806 drop(app);
807
808 dragging.set(false);
810 scroller.stop_auto_scroll(&mut cell.borrow_mut());
811 assert!(!scroller.scrolling(&cell.borrow()));
812 for frame in 9..=16 {
813 pump_frame_and_checkpoint(&cell, Duration::from_millis(20 * frame));
814 }
815 let app = cell.borrow();
816 assert_eq!(scrolls.get(), 4);
817 assert_eq!(state.position(&app).pixels(&app), 40.0);
818 assert!(!scroller.scrolling(&app));
819 }
820
821 #[test]
824 fn an_auto_scroller_follows_the_axis_direction() {
825 let cell = AppCell::new();
826 let mut app = cell.borrow_mut();
827 let (_harness, state, _context) = mount_scroll_action(&mut app, |scrollable| {
828 scrollable.axis_direction(AxisDirection::Up)
829 });
830 let over_the_top = Rect::from_ltwh(0.0, -10.0, 50.0, 20.0);
831 let AutoScrollDrag {
832 scroller, scrolls, ..
833 } = auto_scroll_drag(&mut app, state, over_the_top);
834
835 scroller.start_auto_scroll_if_necessary(&mut app, over_the_top);
836 assert!(scroller.scrolling(&app));
837 drop(app);
838 for frame in 0..=2 {
839 pump_frame_and_checkpoint(&cell, Duration::from_millis(20 * frame));
840 }
841 let app = cell.borrow();
842 assert_eq!(scrolls.get(), 1);
843 assert_eq!(state.position(&app).pixels(&app), 10.0);
844 }
845
846 #[test]
849 fn an_auto_scroller_stays_idle_for_a_target_inside_the_viewport_or_refusing_physics() {
850 let cell = AppCell::new();
851 let mut app = cell.borrow_mut();
852 let (_harness, state, _context) = mount_scroll_action(&mut app, |scrollable| scrollable);
853 let inside = Rect::from_ltwh(0.0, 50.0, 50.0, 20.0);
854 let AutoScrollDrag {
855 scroller, scrolls, ..
856 } = auto_scroll_drag(&mut app, state, inside);
857 scroller.start_auto_scroll_if_necessary(&mut app, inside);
858 assert!(
859 !scroller.scrolling(&app),
860 "the drag should not trigger a scroll"
861 );
862 drop(app);
863 pump_frame_and_checkpoint(&cell, Duration::ZERO);
864 assert_eq!(scrolls.get(), 0);
865
866 let mut app = cell.borrow_mut();
867 let (_harness, state, _context) = mount_scroll_action(&mut app, |scrollable| {
868 scrollable.physics(Rc::new(NeverScrollableScrollPhysics::new()))
869 });
870 let over_the_edge = Rect::from_ltwh(0.0, VIEW_HEIGHT - 10.0, 50.0, 20.0);
871 let AutoScrollDrag { scroller, .. } = auto_scroll_drag(&mut app, state, over_the_edge);
872 scroller.start_auto_scroll_if_necessary(&mut app, over_the_edge);
873 assert!(!scroller.scrolling(&app));
874 assert_eq!(state.position(&app).pixels(&app), 0.0);
875 }
876
877 #[test]
878 fn a_scroll_intent_reaches_the_ambient_scrollable_through_actions() {
879 let cell = AppCell::new();
880 let mut app = cell.borrow_mut();
881 let (_harness, state, context) = mount_scroll_action(&mut app, |scrollable| scrollable);
882 assert!(
883 ScrollContext::notification_context(&state, &mut app).is_some(),
884 "no notification context"
885 );
886
887 Actions::invoke(
888 &mut app,
889 context,
890 &ScrollIntent::new(AxisDirection::Down).r#type(ScrollIncrementType::Line),
891 );
892 for frame in 0..20 {
894 pump_every_view(&mut app, Duration::from_millis(16 * frame));
895 }
896 assert_eq!(state.position(&app).pixels(&app), 50.0);
897
898 Actions::invoke(
900 &mut app,
901 context,
902 &ScrollIntent::new(AxisDirection::Down).r#type(ScrollIncrementType::Page),
903 );
904 for frame in 20..40 {
905 pump_every_view(&mut app, Duration::from_millis(16 * frame));
906 }
907 assert_eq!(state.position(&app).pixels(&app), 50.0 + 0.8 * VIEW_HEIGHT);
908
909 Actions::invoke(
911 &mut app,
912 context,
913 &ScrollIntent::new(AxisDirection::Up).r#type(ScrollIncrementType::Line),
914 );
915 for frame in 40..60 {
916 pump_every_view(&mut app, Duration::from_millis(16 * frame));
917 }
918 assert_eq!(state.position(&app).pixels(&app), 0.8 * VIEW_HEIGHT);
919 }
920
921 #[test]
922 fn a_scroll_intent_across_the_axis_moves_nothing() {
923 let cell = AppCell::new();
924 let mut app = cell.borrow_mut();
925 let (_harness, state, context) = mount_scroll_action(&mut app, |scrollable| scrollable);
926
927 assert_eq!(
928 ScrollAction::get_directional_increment(
929 &mut app,
930 state,
931 &ScrollIntent::new(AxisDirection::Right)
932 ),
933 0.0
934 );
935 Actions::invoke(&mut app, context, &ScrollIntent::new(AxisDirection::Right));
936 for frame in 0..20 {
937 pump_every_view(&mut app, Duration::from_millis(16 * frame));
938 }
939 assert_eq!(state.position(&app).pixels(&app), 0.0);
940 }
941
942 #[test]
943 fn a_scroll_action_is_disabled_without_a_scrollable_and_refuses_physics_that_do_not_scroll() {
944 let cell = AppCell::new();
945 let mut app = cell.borrow_mut();
946 let action = ScrollAction::new(&mut app);
947 let captured: Rc<Cell<Option<BuildContext>>> = Rc::default();
948 let sink = Rc::clone(&captured);
949 let harness = Harness::mount(
950 &mut app,
951 Builder::new(move |_app, context| {
952 sink.set(Some(context));
953 crate::widgets::basic::SizedBox::shrink().into_widget()
954 })
955 .into_widget(),
956 );
957 harness.pump(&mut app);
958 let context = captured.get().expect("the builder ran");
959 assert!(!ContextAction::is_enabled(
960 action.handle(),
961 &mut app,
962 &ScrollIntent::new(AxisDirection::Down),
963 Some(context)
964 ));
965
966 let (_harness, state, context) = mount_scroll_action(&mut app, |scrollable| {
968 scrollable.physics(Rc::new(NeverScrollableScrollPhysics::new()))
969 });
970 Actions::invoke(&mut app, context, &ScrollIntent::new(AxisDirection::Down));
971 for frame in 0..20 {
972 pump_every_view(&mut app, Duration::from_millis(16 * frame));
973 }
974 assert_eq!(state.position(&app).pixels(&app), 0.0);
975 }
976
977 #[test]
978 fn scrollable_details_compare_their_axis_controller_physics_and_clip() {
979 let axis = ScrollableDetails::vertical(false);
980 assert_eq!(axis.direction, AxisDirection::Down);
981 assert_eq!(
982 ScrollableDetails::vertical(true).direction,
983 AxisDirection::Up
984 );
985 assert_eq!(
986 ScrollableDetails::horizontal(false).direction,
987 AxisDirection::Right
988 );
989 assert_eq!(
990 ScrollableDetails::horizontal(true).direction,
991 AxisDirection::Left
992 );
993
994 let physics: ScrollPhysicsRef = Rc::new(NeverScrollableScrollPhysics::new());
995 let with_physics = axis.copy_with().physics(Rc::clone(&physics));
996 assert_ne!(with_physics, axis);
997 assert_eq!(with_physics, axis.copy_with().physics(physics));
998 assert_ne!(
999 with_physics,
1000 with_physics
1001 .copy_with()
1002 .decoration_clip_behavior(Clip::None)
1003 );
1004 assert!(format!("{with_physics:?}").contains("scroll physics"));
1005 let _ = Axis::Vertical;
1006 let _ = Offset::ZERO;
1007 }
1008}