1use std::cell::Cell;
4use std::fmt::{self, Debug};
5use std::rc::Rc;
6use std::time::Duration;
7
8use waft_animation::{Animation, AnimationBehavior, AnimationController, Curve};
9use waft_embedder::clamp_double;
10use waft_foundation::{
11 App, ChangeNotifier, ChangeNotifierData, CompleterFuture, Handle, ListenableObject, Listener,
12 OptionRetained, ValueListenable, ValueNotifier,
13};
14use waft_gestures::{Drag, DragStartDetails};
15use waft_painting::AlignmentGeometry;
16use waft_physics::{Simulation, Tolerance};
17use waft_scheduler::{FrameCallback, SchedulerBinding};
18
19use crate::framework::{
20 BuildContext, IntoWidget, KeyRef, Notification, State, StateData, StatefulWidget, WidgetRef,
21};
22use crate::view::View;
23use crate::widgets::basic::{FractionallySizedBox, SizedBox};
24use crate::widgets::inherited_notifier::{InheritedNotifier, InheritedNotifierKind};
25use crate::widgets::layout_builder::LayoutBuilder;
26use crate::widgets::scroll_activity::ScrollActivityRef;
27use crate::widgets::scroll_context::ScrollContext;
28use crate::widgets::scroll_controller::{
29 ScrollController, ScrollControllerData, ScrollControllerLeaf, ScrollControllerRef,
30};
31use crate::widgets::scroll_notification::{ViewportNotificationData, ViewportNotificationMixin};
32use crate::widgets::scroll_physics::{AlwaysScrollableScrollPhysics, ScrollPhysicsRef};
33use crate::widgets::scroll_position::{
34 AnyScrollPosition, ScrollPosition, ScrollPositionData, ScrollPositionRef,
35};
36use crate::widgets::scroll_position_with_single_context::{
37 ScrollPositionWithSingleContext, ScrollPositionWithSingleContextData,
38 ScrollPositionWithSingleContextLeaf,
39};
40use crate::widgets::scroll_simulation::ClampingScrollSimulation;
41use crate::widgets::value_listenable_builder::ValueListenableBuilder;
42use crate::{InheritedWidget, ScrollActivityDelegate};
43use waft_foundation::Ref;
44
45pub type ScrollableWidgetBuilder =
57 Rc<dyn Fn(&mut App, BuildContext, ScrollControllerRef) -> WidgetRef>;
58
59type GetSheetExtent = Rc<dyn Fn(&App) -> Handle<DraggableSheetExtent>>;
62
63pub struct DraggableScrollableController {
84 change_notifier: ChangeNotifierData,
85 attached_controller: Option<Ref<DraggableScrollableSheetScrollController>>,
86 animation_controllers: Vec<Ref<AnimationController>>,
87}
88
89impl DraggableScrollableController {
90 pub fn new(app: &mut App) -> Ref<DraggableScrollableController> {
92 app.create(DraggableScrollableController {
93 change_notifier: ChangeNotifierData::new(),
94 attached_controller: None,
95 animation_controllers: Vec::new(),
96 })
97 }
98
99 pub fn size(self: Handle<Self>, app: &App) -> f64 {
101 self.assert_attached(app);
102 self.extent(app).current_size(app)
103 }
104
105 pub fn pixels(self: Handle<Self>, app: &App) -> f64 {
107 self.assert_attached(app);
108 let extent = self.extent(app);
109 extent.current_pixels(app)
110 }
111
112 pub fn size_to_pixels(self: Handle<Self>, app: &App, size: f64) -> f64 {
114 self.assert_attached(app);
115 self.extent(app).size_to_pixels(app, size)
116 }
117
118 pub fn is_attached(self: Handle<Self>, app: &App) -> bool {
125 app.get(self)
126 .attached_controller
127 .as_ref()
128 .is_some_and(|controller| controller.has_clients(app))
129 }
130
131 pub fn pixels_to_size(self: Handle<Self>, app: &App, pixels: f64) -> f64 {
133 self.assert_attached(app);
134 self.extent(app).pixels_to_size(app, pixels)
135 }
136
137 pub fn animate_to(
158 self: Handle<Self>,
159 app: &mut App,
160 size: f64,
161 duration: Duration,
162 curve: Rc<dyn Curve>,
163 ) -> CompleterFuture<()> {
164 self.assert_attached(app);
165 debug_assert!((0.0..=1.0).contains(&size));
166 debug_assert!(!duration.is_zero());
167 let attached = self.attached_controller(app);
168 let extent = app.get(attached).extent.clone();
169 let position = attached.position(app);
170 let vsync = position.context(app).vsync();
171 let animation_controller = AnimationController::unbounded(
172 app,
173 extent.current_size(app),
174 None,
175 None,
176 AnimationBehavior::Preserve,
177 vsync,
178 );
179 app.get_mut(self)
180 .animation_controllers
181 .push(animation_controller.clone());
182 ScrollActivityDelegate::go_idle(position, app);
183 app.get_mut(&extent).has_dragged = false;
185 app.get_mut(&extent).has_changed = true;
186 let canceled = animation_controller.clone();
187 extent.start_activity(
188 app,
189 Listener::new(move |app| {
190 if canceled.is_animating(app) {
193 canceled.stop(app, true);
194 }
195 }),
196 );
197 let ticking = animation_controller.handle();
198 Animation::add_listener(
199 ticking,
200 app,
201 Listener::new(move |app: &mut App| {
202 let value = ticking.value(app);
203 let position = self.attached_controller(app).position(app);
204 let context = position.context(app).notification_context(app);
205 extent.update_size(app, value, context.expect("a mounted scrollable"));
206 }),
207 );
208 let extent = self.extent(app);
209 let target = clamp_double(size, extent.min_size(app), extent.max_size(app));
210 let animated = animation_controller.animate_to(app, target, Some(duration), curve);
211 CompleterFuture::spawn(app, animated)
212 }
213
214 pub fn jump_to(self: Handle<Self>, app: &mut App, size: f64) {
227 self.assert_attached(app);
228 debug_assert!((0.0..=1.0).contains(&size));
229 let extent = self.extent(app);
230 let position = self.attached_controller(app).position(app);
231 extent.start_activity(app, Listener::new(|_app| {}));
233 ScrollActivityDelegate::go_idle(position, app);
234 app.get_mut(extent).has_dragged = false;
235 app.get_mut(extent).has_changed = true;
236 let context = position.context(app).notification_context(app);
237 extent.update_size(app, size, context.expect("a mounted scrollable"));
238 }
239
240 pub fn reset(self: Handle<Self>, app: &mut App) {
243 self.assert_attached(app);
244 self.attached_controller(app).reset(app);
245 }
246
247 pub fn dispose(self: Handle<Self>, app: &mut App) {
249 ChangeNotifierData::dispose(app, self);
250 }
251
252 fn assert_attached(self: Handle<Self>, app: &App) {
253 debug_assert!(
254 self.is_attached(app),
255 "DraggableScrollableController is not attached to a sheet. A \
256 DraggableScrollableController must be used in a DraggableScrollableSheet before \
257 any of its methods are called."
258 );
259 }
260
261 fn attached_controller(
262 self: Handle<Self>,
263 app: &App,
264 ) -> Handle<DraggableScrollableSheetScrollController> {
265 app.get(self)
266 .attached_controller
267 .handle()
268 .expect("the controller is attached to a sheet")
269 }
270
271 fn extent(self: Handle<Self>, app: &App) -> Handle<DraggableSheetExtent> {
272 app.get(self.attached_controller(app)).extent.handle()
273 }
274
275 fn notification_listener(self: Handle<Self>) -> Listener {
277 Listener::handle_method(self, DraggableScrollableController::forward_notification)
278 }
279
280 fn forward_notification(self: Handle<Self>, app: &mut App) {
281 self.notify_listeners(app);
282 }
283
284 fn attach(
285 self: Handle<Self>,
286 app: &mut App,
287 scroll_controller: Ref<DraggableScrollableSheetScrollController>,
288 ) {
289 debug_assert!(
290 app.get(self).attached_controller.is_none(),
291 "Draggable scrollable controller is already attached to a sheet."
292 );
293 app.get_mut(self).attached_controller = Some(scroll_controller.clone());
294 let current_size = app
295 .get(&app.get(&scroll_controller).extent)
296 .current_size
297 .handle();
298 let listener = self.notification_listener();
299 ListenableObject::add_listener(current_size, app, listener);
300 app.get_mut(&scroll_controller).on_position_detached = Some(Listener::handle_method(
301 self,
302 DraggableScrollableController::dispose_animation_controllers,
303 ));
304 }
305
306 fn on_extent_replaced(
307 self: Handle<Self>,
308 app: &mut App,
309 previous_extent: Handle<DraggableSheetExtent>,
310 ) {
311 let extent = self.extent(app);
315 let current_size = app.get(extent).current_size.handle();
316 let listener = self.notification_listener();
317 ListenableObject::add_listener(current_size, app, listener);
318 if previous_extent.current_size(app) != extent.current_size(app) {
319 self.notify_listeners(app);
322 }
323 }
324
325 fn detach(self: Handle<Self>, app: &mut App, dispose_extent: bool) {
326 if let Some(attached_controller) = app.get(self).attached_controller.handle() {
327 let extent = app.get(attached_controller).extent.handle();
328 if dispose_extent {
329 extent.dispose(app);
330 } else {
331 let current_size = app.get(extent).current_size.handle();
332 ListenableObject::remove_listener(current_size, app, &self.notification_listener());
333 }
334 }
335 self.dispose_animation_controllers(app);
336 app.get_mut(self).attached_controller = None;
337 }
338
339 fn dispose_animation_controllers(self: Handle<Self>, app: &mut App) {
340 for animation_controller in std::mem::take(&mut app.get_mut(self).animation_controllers) {
341 animation_controller.dispose(app);
342 }
343 }
344}
345
346impl ChangeNotifier for DraggableScrollableController {
347 fn change_notifier_data(&self) -> &ChangeNotifierData {
348 &self.change_notifier
349 }
350
351 fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
352 &mut self.change_notifier
353 }
354}
355
356pub struct DraggableScrollableSheet {
395 pub key: Option<KeyRef>,
397 pub initial_child_size: f64,
406 pub min_child_size: f64,
411 pub max_child_size: f64,
416 pub expand: bool,
425 pub snap: bool,
441 pub snap_sizes: Option<Vec<f64>>,
451 pub snap_animation_duration: Option<Duration>,
456 pub controller: Option<Ref<DraggableScrollableController>>,
458 pub should_close_on_min_extent: bool,
464 pub builder: ScrollableWidgetBuilder,
468}
469
470impl DraggableScrollableSheet {
471 pub fn new(builder: ScrollableWidgetBuilder) -> DraggableScrollableSheet {
477 DraggableScrollableSheet {
478 key: None,
479 initial_child_size: 0.5,
480 min_child_size: 0.25,
481 max_child_size: 1.0,
482 expand: true,
483 snap: false,
484 snap_sizes: None,
485 snap_animation_duration: None,
486 controller: None,
487 should_close_on_min_extent: true,
488 builder,
489 }
490 }
491
492 pub fn key(mut self, key: KeyRef) -> DraggableScrollableSheet {
494 self.key = Some(key);
495 self
496 }
497
498 pub fn initial_child_size(mut self, initial_child_size: f64) -> DraggableScrollableSheet {
500 self.initial_child_size = initial_child_size;
501 self
502 }
503
504 pub fn min_child_size(mut self, min_child_size: f64) -> DraggableScrollableSheet {
506 self.min_child_size = min_child_size;
507 self
508 }
509
510 pub fn max_child_size(mut self, max_child_size: f64) -> DraggableScrollableSheet {
512 self.max_child_size = max_child_size;
513 self
514 }
515
516 pub fn expand(mut self, expand: bool) -> DraggableScrollableSheet {
518 self.expand = expand;
519 self
520 }
521
522 pub fn snap(mut self, snap: bool) -> DraggableScrollableSheet {
524 self.snap = snap;
525 self
526 }
527
528 pub fn snap_sizes(mut self, snap_sizes: Vec<f64>) -> DraggableScrollableSheet {
530 self.snap_sizes = Some(snap_sizes);
531 self
532 }
533
534 pub fn snap_animation_duration(mut self, duration: Duration) -> DraggableScrollableSheet {
536 debug_assert!(!duration.is_zero());
537 self.snap_animation_duration = Some(duration);
538 self
539 }
540
541 pub fn controller(
543 mut self,
544 controller: Ref<DraggableScrollableController>,
545 ) -> DraggableScrollableSheet {
546 self.controller = Some(controller);
547 self
548 }
549
550 pub fn should_close_on_min_extent(
552 mut self,
553 should_close_on_min_extent: bool,
554 ) -> DraggableScrollableSheet {
555 self.should_close_on_min_extent = should_close_on_min_extent;
556 self
557 }
558}
559
560impl Debug for DraggableScrollableSheet {
561 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
562 f.debug_struct("DraggableScrollableSheet")
563 .field("initialChildSize", &self.initial_child_size)
564 .field("minChildSize", &self.min_child_size)
565 .field("maxChildSize", &self.max_child_size)
566 .finish_non_exhaustive()
567 }
568}
569
570impl StatefulWidget for DraggableScrollableSheet {
571 type State = DraggableScrollableSheetState;
572
573 fn key(&self) -> Option<&KeyRef> {
574 self.key.as_ref()
575 }
576
577 fn create_state(&self) -> DraggableScrollableSheetState {
578 debug_assert!(self.min_child_size >= 0.0);
579 debug_assert!(self.max_child_size <= 1.0);
580 debug_assert!(self.min_child_size <= self.initial_child_size);
581 debug_assert!(self.initial_child_size <= self.max_child_size);
582 DraggableScrollableSheetState {
583 state: StateData::new(),
584 scroll_controller: None,
585 extent: None,
586 }
587 }
588}
589
590pub struct DraggableScrollableNotification {
612 viewport_notification: ViewportNotificationData,
613 pub extent: f64,
616 pub min_extent: f64,
618 pub max_extent: f64,
620 pub initial_extent: f64,
622 pub context: BuildContext,
628 pub should_close_on_min_extent: bool,
633}
634
635impl DraggableScrollableNotification {
636 pub fn new(
641 extent: f64,
642 min_extent: f64,
643 max_extent: f64,
644 initial_extent: f64,
645 context: BuildContext,
646 ) -> DraggableScrollableNotification {
647 debug_assert!(0.0 <= min_extent);
648 debug_assert!(max_extent <= 1.0);
649 debug_assert!(min_extent <= extent);
650 debug_assert!(min_extent <= initial_extent);
651 debug_assert!(extent <= max_extent);
652 debug_assert!(initial_extent <= max_extent);
653 DraggableScrollableNotification {
654 viewport_notification: ViewportNotificationData::new(),
655 extent,
656 min_extent,
657 max_extent,
658 initial_extent,
659 context,
660 should_close_on_min_extent: true,
661 }
662 }
663
664 pub fn should_close_on_min_extent(
666 mut self,
667 should_close_on_min_extent: bool,
668 ) -> DraggableScrollableNotification {
669 self.should_close_on_min_extent = should_close_on_min_extent;
670 self
671 }
672}
673
674impl Notification for DraggableScrollableNotification {
675 fn as_any(&self) -> &dyn std::any::Any {
676 self
677 }
678
679 fn viewport_depth(&self) -> Option<&Cell<u32>> {
680 Some(self.viewport_notification.depth_cell())
681 }
682}
683
684impl ViewportNotificationMixin for DraggableScrollableNotification {
685 fn viewport_notification_data(&self) -> &ViewportNotificationData {
686 &self.viewport_notification
687 }
688}
689
690impl Debug for DraggableScrollableNotification {
691 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
692 let mut description = Vec::new();
693 ViewportNotificationMixin::debug_fill_description(self, &mut description);
694 description.push(format!(
695 "minExtent: {}, extent: {}, maxExtent: {}, initialExtent: {}",
696 self.min_extent, self.extent, self.max_extent, self.initial_extent
697 ));
698 write!(
699 f,
700 "DraggableScrollableNotification({})",
701 description.join(", ")
702 )
703 }
704}
705
706struct DraggableSheetExtent {
720 cancel_activity: Option<Listener>,
721 min_size: f64,
722 max_size: f64,
723 snap: bool,
724 snap_sizes: Vec<f64>,
725 snap_animation_duration: Option<Duration>,
726 initial_size: f64,
727 should_close_on_min_extent: bool,
728 current_size: Ref<ValueNotifier<f64>>,
729 available_pixels: f64,
730 has_dragged: bool,
732 has_changed: bool,
742}
743
744impl DraggableSheetExtent {
745 #[allow(clippy::too_many_arguments)]
746 fn new(
747 app: &mut App,
748 min_size: f64,
749 max_size: f64,
750 snap: bool,
751 snap_sizes: Vec<f64>,
752 initial_size: f64,
753 snap_animation_duration: Option<Duration>,
754 current_size: Option<Ref<ValueNotifier<f64>>>,
755 has_dragged: Option<bool>,
756 has_changed: Option<bool>,
757 should_close_on_min_extent: bool,
758 ) -> Ref<DraggableSheetExtent> {
759 debug_assert!(min_size >= 0.0);
760 debug_assert!(max_size <= 1.0);
761 debug_assert!(min_size <= initial_size);
762 debug_assert!(initial_size <= max_size);
763 let current_size =
764 current_size.unwrap_or_else(|| app.create(ValueNotifier::new(initial_size)));
765 app.create(DraggableSheetExtent {
766 cancel_activity: None,
767 min_size,
768 max_size,
769 snap,
770 snap_sizes,
771 snap_animation_duration,
772 initial_size,
773 should_close_on_min_extent,
774 current_size,
775 available_pixels: f64::INFINITY,
776 has_dragged: has_dragged.unwrap_or(false),
777 has_changed: has_changed.unwrap_or(false),
778 })
779 }
780
781 pub fn min_size(self: Handle<Self>, app: &App) -> f64 {
783 app.get(self).min_size
784 }
785
786 pub fn max_size(self: Handle<Self>, app: &App) -> f64 {
788 app.get(self).max_size
789 }
790
791 fn is_at_min(self: Handle<Self>, app: &App) -> bool {
792 app.get(self).min_size >= self.current_size(app)
793 }
794
795 fn is_at_max(self: Handle<Self>, app: &App) -> bool {
796 app.get(self).max_size <= self.current_size(app)
797 }
798
799 pub fn current_size(self: Handle<Self>, app: &App) -> f64 {
801 *app.get(&app.get(self).current_size).value()
802 }
803
804 pub fn current_pixels(self: Handle<Self>, app: &App) -> f64 {
806 self.size_to_pixels(app, self.current_size(app))
807 }
808
809 fn pixel_snap_sizes(self: Handle<Self>, app: &App) -> Vec<f64> {
810 app.get(self)
811 .snap_sizes
812 .clone()
813 .into_iter()
814 .map(|size| self.size_to_pixels(app, size))
815 .collect()
816 }
817
818 fn start_activity(self: Handle<Self>, app: &mut App, on_canceled: Listener) {
825 if let Some(cancel_activity) = app.get(self).cancel_activity.clone() {
826 cancel_activity.call(app);
827 }
828 app.get_mut(self).cancel_activity = Some(on_canceled);
829 }
830
831 fn add_pixel_delta(self: Handle<Self>, app: &mut App, delta: f64, context: BuildContext) {
838 if let Some(cancel_activity) = app.get_mut(self).cancel_activity.take() {
840 cancel_activity.call(app);
841 }
842 app.get_mut(self).has_dragged = true;
845 app.get_mut(self).has_changed = true;
846 if app.get(self).available_pixels == 0.0 {
847 return;
848 }
849 let new_size = self.current_size(app) + self.pixels_to_size(app, delta);
850 self.update_size(app, new_size, context);
851 }
852
853 fn update_size(self: Handle<Self>, app: &mut App, new_size: f64, context: BuildContext) {
859 let clamped_size = clamp_double(new_size, app.get(self).min_size, app.get(self).max_size);
860 if self.current_size(app) == clamped_size {
861 return;
862 }
863 let current_size = app.get(self).current_size.handle();
864 current_size.set_value(app, clamped_size);
865 let extent = app.get(self);
866 DraggableScrollableNotification::new(
867 self.current_size(app),
868 extent.min_size,
869 extent.max_size,
870 extent.initial_size,
871 context,
872 )
873 .should_close_on_min_extent(extent.should_close_on_min_extent)
874 .dispatch(app, Some(context));
875 }
876
877 pub fn pixels_to_size(self: Handle<Self>, app: &App, pixels: f64) -> f64 {
879 let extent = app.get(self);
880 pixels / extent.available_pixels * extent.max_size
881 }
882
883 pub fn size_to_pixels(self: Handle<Self>, app: &App, size: f64) -> f64 {
885 let extent = app.get(self);
886 size / extent.max_size * extent.available_pixels
887 }
888
889 pub fn dispose(self: Handle<Self>, app: &mut App) {
891 let current_size = app.get(self).current_size.handle();
892 current_size.dispose(app);
893 }
894
895 #[allow(clippy::too_many_arguments)]
896 fn copy_with(
897 self: Handle<Self>,
898 app: &mut App,
899 min_size: f64,
900 max_size: f64,
901 snap: bool,
902 snap_sizes: Vec<f64>,
903 initial_size: f64,
904 snap_animation_duration: Option<Duration>,
905 should_close_on_min_extent: bool,
906 ) -> Ref<DraggableSheetExtent> {
907 let has_changed = app.get(self).has_changed;
908 let has_dragged = app.get(self).has_dragged;
909 let size = if has_changed {
912 clamp_double(self.current_size(app), min_size, max_size)
913 } else {
914 initial_size
915 };
916 let current_size = app.create(ValueNotifier::new(size));
917 DraggableSheetExtent::new(
918 app,
919 min_size,
920 max_size,
921 snap,
922 snap_sizes,
923 initial_size,
924 snap_animation_duration,
925 Some(current_size),
926 Some(has_dragged),
927 Some(has_changed),
928 should_close_on_min_extent,
929 )
930 }
931}
932
933impl Debug for DraggableSheetExtent {
934 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
935 f.debug_struct("DraggableSheetExtent")
936 .field("minSize", &self.min_size)
937 .field("maxSize", &self.max_size)
938 .field("snap", &self.snap)
939 .finish_non_exhaustive()
940 }
941}
942
943pub struct DraggableScrollableSheetState {
948 state: StateData<DraggableScrollableSheet>,
949 scroll_controller: Option<Ref<DraggableScrollableSheetScrollController>>,
950 extent: Option<Ref<DraggableSheetExtent>>,
951}
952
953impl DraggableScrollableSheetState {
954 fn scroll_controller(
955 self: Handle<Self>,
956 app: &App,
957 ) -> Handle<DraggableScrollableSheetScrollController> {
958 app.get(self)
959 .scroll_controller
960 .handle()
961 .expect("init_state has run")
962 }
963
964 fn extent(self: Handle<Self>, app: &App) -> Handle<DraggableSheetExtent> {
965 app.get(self).extent.handle().expect("init_state has run")
966 }
967
968 fn implied_snap_sizes(self: Handle<Self>, app: &App) -> Vec<f64> {
969 let widget = self.widget(app);
970 if cfg!(debug_assertions)
971 && let Some(snap_sizes) = &widget.snap_sizes
972 {
973 for (index, snap_size) in snap_sizes.iter().copied().enumerate() {
974 debug_assert!(
975 snap_size >= widget.min_child_size && snap_size <= widget.max_child_size,
976 "Invalid snapSize '{snap_size}' at index {index}. Snap sizes must be \
977 between `minChildSize` and `maxChildSize`."
978 );
979 debug_assert!(
980 index == 0 || snap_size > snap_sizes[index - 1],
981 "Invalid snapSize '{snap_size}' at index {index}. Snap sizes must be in \
982 ascending order."
983 );
984 }
985 }
986 let Some(snap_sizes) = widget.snap_sizes.as_ref().filter(|sizes| !sizes.is_empty()) else {
988 return vec![widget.min_child_size, widget.max_child_size];
989 };
990 let mut implied = Vec::with_capacity(snap_sizes.len() + 2);
991 if snap_sizes[0] != widget.min_child_size {
992 implied.push(widget.min_child_size);
993 }
994 implied.extend_from_slice(snap_sizes);
995 if snap_sizes[snap_sizes.len() - 1] != widget.max_child_size {
996 implied.push(widget.max_child_size);
997 }
998 implied
999 }
1000
1001 fn replace_extent(self: Handle<Self>, app: &mut App, old_widget: &DraggableScrollableSheet) {
1002 let previous_extent = self.extent(app);
1003 let snap_sizes = self.implied_snap_sizes(app);
1004 let widget = self.widget(app);
1005 let (min, max, snap, duration, initial, close_on_min) = (
1006 widget.min_child_size,
1007 widget.max_child_size,
1008 widget.snap,
1009 widget.snap_animation_duration,
1010 widget.initial_child_size,
1011 widget.should_close_on_min_extent,
1012 );
1013 let snap_sizes_changed = widget.snap_sizes != old_widget.snap_sizes;
1014 let snap_changed = widget.snap != old_widget.snap;
1015 let extent = previous_extent.copy_with(
1016 app,
1017 min,
1018 max,
1019 snap,
1020 snap_sizes,
1021 initial,
1022 duration,
1023 close_on_min,
1024 );
1025 app.get_mut(self).extent = Some(extent.clone());
1026 let scroll_controller = self.scroll_controller(app);
1029 app.get_mut(scroll_controller).extent = extent;
1030 if let Some(controller) = self.widget(app).controller.handle() {
1033 controller.on_extent_replaced(app, previous_extent);
1034 }
1035 previous_extent.dispose(app);
1036 if snap && (snap_changed || snap_sizes_changed) && scroll_controller.has_clients(app) {
1037 let scroll_controller = app
1043 .get(self)
1044 .scroll_controller
1045 .clone()
1046 .expect("init_state has run");
1047 SchedulerBinding::add_post_frame_callback(
1048 app,
1049 FrameCallback::new(move |app, _timestamp| {
1050 for position in scroll_controller.positions(app) {
1051 let position = position
1052 .downcast::<DraggableScrollableSheetScrollPosition>(app)
1053 .expect("the controller creates its own positions");
1054 ScrollActivityDelegate::go_ballistic(position, app, 0.0);
1055 }
1056 }),
1057 View::maybe_id_of(app, self.context(app)),
1058 );
1059 }
1060 }
1061}
1062
1063impl State for DraggableScrollableSheetState {
1064 type Widget = DraggableScrollableSheet;
1065 crate::state_accessors!();
1066
1067 fn init_state(self: Handle<Self>, app: &mut App) {
1068 let snap_sizes = self.implied_snap_sizes(app);
1069 let widget = self.widget(app);
1070 let (min, max, snap, duration, initial, close_on_min) = (
1071 widget.min_child_size,
1072 widget.max_child_size,
1073 widget.snap,
1074 widget.snap_animation_duration,
1075 widget.initial_child_size,
1076 widget.should_close_on_min_extent,
1077 );
1078 let extent = DraggableSheetExtent::new(
1079 app,
1080 min,
1081 max,
1082 snap,
1083 snap_sizes,
1084 initial,
1085 duration,
1086 None,
1087 None,
1088 None,
1089 close_on_min,
1090 );
1091 app.get_mut(self).extent = Some(extent.clone());
1092 let scroll_controller = DraggableScrollableSheetScrollController::new(app, extent);
1093 app.get_mut(self).scroll_controller = Some(scroll_controller.clone());
1094 if let Some(controller) = self.widget(app).controller.handle() {
1095 controller.attach(app, scroll_controller);
1096 }
1097 }
1098
1099 fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &DraggableScrollableSheet) {
1100 let controller = self.widget(app).controller.handle();
1101 if controller != old_widget.controller.handle() {
1102 if let Some(old_controller) = old_widget.controller.handle() {
1103 old_controller.detach(app, false);
1104 }
1105 if let Some(controller) = controller {
1106 let scroll_controller = app
1107 .get(self)
1108 .scroll_controller
1109 .clone()
1110 .expect("init_state has run");
1111 controller.attach(app, scroll_controller);
1112 }
1113 }
1114 self.replace_extent(app, old_widget);
1115 }
1116
1117 fn did_change_dependencies(self: Handle<Self>, app: &mut App) {
1118 let context = self.context(app);
1119 if InheritedResetNotifier::should_reset(app, context) {
1120 self.scroll_controller(app).reset(app);
1121 }
1122 }
1123
1124 fn dispose(self: Handle<Self>, app: &mut App) {
1125 match self.widget(app).controller.handle() {
1126 None => self.extent(app).dispose(app),
1127 Some(controller) => controller.detach(app, true),
1128 }
1129 self.scroll_controller(app).dispose(app);
1130 }
1131
1132 fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
1133 let extent = self.extent(app);
1134 let expand = self.widget(app).expand;
1135 let max_child_size = self.widget(app).max_child_size;
1136 let builder = Rc::clone(&self.widget(app).builder);
1137 let scroll_controller = app
1138 .get(self)
1139 .scroll_controller
1140 .clone()
1141 .expect("init_state has run");
1142 let child = builder(app, context, scroll_controller.into_erased());
1143 let current_size: Rc<dyn ValueListenable<f64>> =
1144 Rc::new(app.get(extent).current_size.clone());
1145 ValueListenableBuilder::<f64>::new(
1146 current_size,
1147 move |_app, _context, current_size, child| {
1148 let current_size = *current_size;
1149 let child = child.cloned();
1150 LayoutBuilder::new(move |app, _context, constraints| {
1151 let extent = self.extent(app);
1153 app.get_mut(extent).available_pixels =
1154 max_child_size * constraints.biggest().height();
1155 let mut sheet = FractionallySizedBox::new()
1156 .height_factor(current_size)
1157 .alignment(AlignmentGeometry::BOTTOM_CENTER);
1158 if let Some(child) = &child {
1159 sheet = sheet.child(child.clone());
1160 }
1161 if expand {
1162 SizedBox::expand().child(sheet).into_widget()
1163 } else {
1164 sheet.into_widget()
1165 }
1166 })
1167 .into_widget()
1168 },
1169 )
1170 .child(child)
1171 .into_widget()
1172 }
1173}
1174
1175struct DraggableScrollableSheetScrollController {
1192 change_notifier: ChangeNotifierData,
1193 scroll_controller: ScrollControllerData,
1194 extent: Ref<DraggableSheetExtent>,
1195 on_position_detached: Option<Listener>,
1196}
1197
1198impl DraggableScrollableSheetScrollController {
1199 fn new(
1200 app: &mut App,
1201 extent: Ref<DraggableSheetExtent>,
1202 ) -> Ref<DraggableScrollableSheetScrollController> {
1203 app.create(DraggableScrollableSheetScrollController {
1204 change_notifier: ChangeNotifierData::new(),
1205 scroll_controller: ScrollControllerData::new(0.0, true, None, None, None),
1206 extent,
1207 on_position_detached: None,
1208 })
1209 }
1210
1211 pub fn position(
1214 self: Handle<Self>,
1215 app: &App,
1216 ) -> Handle<DraggableScrollableSheetScrollPosition> {
1217 ScrollControllerLeaf::position(self, app)
1218 .downcast::<DraggableScrollableSheetScrollPosition>(app)
1219 .expect("the controller creates its own positions")
1220 }
1221
1222 fn reset(self: Handle<Self>, app: &mut App) {
1223 let extent = app.get(self).extent.handle();
1224 if let Some(cancel_activity) = app.get(extent).cancel_activity.clone() {
1225 cancel_activity.call(app);
1226 }
1227 app.get_mut(extent).has_dragged = false;
1228 app.get_mut(extent).has_changed = false;
1229 if self.offset(app) != 0.0 {
1233 self.animate_to(
1234 app,
1235 0.0,
1236 Duration::from_millis(1),
1237 waft_animation::Curves::linear(),
1238 );
1239 }
1240 let initial_size = app.get(extent).initial_size;
1241 let context = self.position(app).context(app).notification_context(app);
1242 extent.update_size(app, initial_size, context.expect("a mounted scrollable"));
1243 }
1244}
1245
1246impl ChangeNotifier for DraggableScrollableSheetScrollController {
1247 fn change_notifier_data(&self) -> &ChangeNotifierData {
1248 &self.change_notifier
1249 }
1250
1251 fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
1252 &mut self.change_notifier
1253 }
1254}
1255
1256impl ScrollControllerLeaf for DraggableScrollableSheetScrollController {
1257 crate::scroll_controller_accessors!();
1258
1259 fn create_scroll_position(
1260 self: Handle<Self>,
1261 app: &mut App,
1262 physics: ScrollPhysicsRef,
1263 context: Rc<dyn ScrollContext>,
1264 old_position: Option<AnyScrollPosition>,
1265 ) -> ScrollPositionRef {
1266 let physics = physics.apply_to(Some(Rc::new(AlwaysScrollableScrollPhysics::new())));
1267 DraggableScrollableSheetScrollPosition::new(
1268 app,
1269 physics,
1270 context,
1271 old_position,
1272 Rc::new(move |app: &App| app.get(self).extent.handle()),
1273 )
1274 .into_erased()
1275 }
1276
1277 fn debug_fill_description(self: Handle<Self>, app: &App, description: &mut Vec<String>) {
1278 ScrollController::debug_fill_description(self.as_controller(), app, description);
1279 description.push(format!("extent: {:?}", app.get(self).extent));
1280 }
1281
1282 fn detach(self: Handle<Self>, app: &mut App, position: AnyScrollPosition) {
1283 if let Some(on_position_detached) = app.get(self).on_position_detached.clone() {
1284 on_position_detached.call(app);
1285 }
1286 ScrollController::detach(self.as_controller(), app, position);
1287 }
1288}
1289
1290struct DraggableScrollableSheetScrollPosition {
1300 change_notifier: ChangeNotifierData,
1301 scroll_position: ScrollPositionData,
1302 single_context: ScrollPositionWithSingleContextData,
1303 drag_cancel_callback: Option<Listener>,
1304 get_extent: GetSheetExtent,
1305 ballistic_controllers: Vec<Ref<AnimationController>>,
1306}
1307
1308impl DraggableScrollableSheetScrollPosition {
1309 fn new(
1310 app: &mut App,
1311 physics: ScrollPhysicsRef,
1312 context: Rc<dyn ScrollContext>,
1313 old_position: Option<AnyScrollPosition>,
1314 get_extent: GetSheetExtent,
1315 ) -> Ref<DraggableScrollableSheetScrollPosition> {
1316 let scroll_position = ScrollPositionData::new(app, physics, context, true, None);
1317 let this = app.create(DraggableScrollableSheetScrollPosition {
1318 change_notifier: ChangeNotifierData::new(),
1319 scroll_position,
1320 single_context: ScrollPositionWithSingleContextData::new(),
1321 drag_cancel_callback: None,
1322 get_extent,
1323 ballistic_controllers: Vec::new(),
1324 });
1325 ScrollPositionWithSingleContext::init(this.handle(), app, Some(0.0), old_position);
1326 this
1327 }
1328
1329 pub fn list_should_scroll(self: Handle<Self>, app: &App) -> bool {
1331 waft_rendering::ViewportOffset::pixels(self, app) > 0.0
1332 }
1333
1334 pub fn extent(self: Handle<Self>, app: &App) -> Handle<DraggableSheetExtent> {
1336 (Rc::clone(&app.get(self).get_extent))(app)
1337 }
1338
1339 fn get_current_snap_size(self: Handle<Self>, app: &App) -> Option<f64> {
1342 let extent = self.extent(app);
1343 let metrics = self.copy_with(app);
1344 let tolerance = self.physics(app).tolerance_for(&*metrics).distance;
1345 let current_size = extent.current_size(app);
1346 app.get(extent)
1347 .snap_sizes
1348 .iter()
1349 .copied()
1350 .find(|snap_size| {
1351 (current_size - snap_size).abs() <= extent.pixels_to_size(app, tolerance)
1352 })
1353 }
1354
1355 fn is_at_snap_size(self: Handle<Self>, app: &App) -> bool {
1356 self.get_current_snap_size(app).is_some()
1357 }
1358
1359 fn should_snap(self: Handle<Self>, app: &App) -> bool {
1360 let extent = self.extent(app);
1361 app.get(extent).snap && app.get(extent).has_dragged && !self.is_at_snap_size(app)
1362 }
1363}
1364
1365impl ChangeNotifier for DraggableScrollableSheetScrollPosition {
1366 fn change_notifier_data(&self) -> &ChangeNotifierData {
1367 &self.change_notifier
1368 }
1369
1370 fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
1371 &mut self.change_notifier
1372 }
1373}
1374
1375impl waft_rendering::ViewportOffset for DraggableScrollableSheetScrollPosition {
1376 crate::scroll_position_with_single_context_viewport_offset_overrides!();
1377}
1378
1379impl ScrollPosition for DraggableScrollableSheetScrollPosition {
1380 crate::scroll_position_with_single_context_overrides!();
1381}
1382
1383impl ScrollActivityDelegate for DraggableScrollableSheetScrollPosition {
1384 crate::scroll_position_with_single_context_delegate_overrides!();
1385}
1386
1387impl ScrollPositionWithSingleContextLeaf for DraggableScrollableSheetScrollPosition {
1388 crate::scroll_position_with_single_context_accessors!();
1389
1390 fn absorb(self: Handle<Self>, app: &mut App, other: AnyScrollPosition) {
1391 ScrollPositionWithSingleContext::absorb(self, app, other);
1392 debug_assert!(app.get(self).drag_cancel_callback.is_none());
1393
1394 let Some(other) = other.downcast::<DraggableScrollableSheetScrollPosition>(app) else {
1395 return;
1396 };
1397
1398 if let Some(drag_cancel_callback) = app.get_mut(other).drag_cancel_callback.take() {
1399 app.get_mut(self).drag_cancel_callback = Some(drag_cancel_callback);
1400 }
1401 }
1402
1403 fn begin_activity(self: Handle<Self>, app: &mut App, new_activity: Option<ScrollActivityRef>) {
1404 for ballistic_controller in app.get(self).ballistic_controllers.clone() {
1406 ballistic_controller.stop(app, true);
1407 }
1408 ScrollPositionWithSingleContext::begin_activity(self, app, new_activity);
1409 }
1410
1411 fn apply_user_offset(self: Handle<Self>, app: &mut App, delta: f64) {
1412 let extent = self.extent(app);
1413 let is_at_min = extent.is_at_min(app);
1414 let is_at_max = extent.is_at_max(app);
1415 if !self.list_should_scroll(app)
1416 && (!(is_at_min || is_at_max)
1417 || (is_at_min && delta < 0.0)
1418 || (is_at_max && delta > 0.0))
1419 {
1420 let context = self.context(app).notification_context(app);
1421 extent.add_pixel_delta(app, -delta, context.expect("a mounted scrollable"));
1422 } else {
1423 ScrollPositionWithSingleContext::apply_user_offset(self, app, delta);
1424 }
1425 }
1426
1427 fn dispose(self: Handle<Self>, app: &mut App) {
1428 for ballistic_controller in std::mem::take(&mut app.get_mut(self).ballistic_controllers) {
1429 ballistic_controller.dispose(app);
1430 }
1431 ScrollPositionWithSingleContext::dispose(self, app);
1432 }
1433
1434 fn go_ballistic(self: Handle<Self>, app: &mut App, velocity: f64) {
1435 let extent = self.extent(app);
1436 if (velocity == 0.0 && !self.should_snap(app))
1437 || (velocity < 0.0 && self.list_should_scroll(app))
1438 || (velocity > 0.0 && extent.is_at_max(app))
1439 {
1440 ScrollPositionWithSingleContext::go_ballistic(self, app, velocity);
1441 return;
1442 }
1443 if let Some(drag_cancel_callback) = app.get_mut(self).drag_cancel_callback.take() {
1445 drag_cancel_callback.call(app);
1446 }
1447
1448 let metrics = self.copy_with(app);
1449 let tolerance = self.physics(app).tolerance_for(&*metrics);
1450 let simulation: Box<dyn Simulation> = if app.get(extent).snap {
1451 Box::new(SnappingSimulation::new(
1453 extent.current_pixels(app),
1454 velocity,
1455 extent.pixel_snap_sizes(app),
1456 app.get(extent).snap_animation_duration,
1457 tolerance,
1458 ))
1459 } else {
1460 Box::new(ClampingScrollSimulation::with_options(
1463 extent.current_pixels(app),
1465 velocity,
1466 ClampingScrollSimulation::DEFAULT_FRICTION,
1467 tolerance,
1468 ))
1469 };
1470
1471 let vsync = self.context(app).vsync();
1472 let ballistic_controller = AnimationController::unbounded(
1473 app,
1474 0.0,
1475 None,
1476 None,
1477 AnimationBehavior::Preserve,
1478 vsync,
1479 );
1480 app.get_mut(self)
1481 .ballistic_controllers
1482 .push(ballistic_controller.clone());
1483 let ballistic_controller = ballistic_controller.handle();
1484
1485 let last_position = Rc::new(Cell::new(extent.current_pixels(app)));
1486 let velocity = Rc::new(Cell::new(velocity));
1487 let tick = {
1488 let last_position = Rc::clone(&last_position);
1489 let velocity = Rc::clone(&velocity);
1490 move |app: &mut App| {
1491 let value = ballistic_controller.value(app);
1492 let delta = value - last_position.get();
1493 last_position.set(value);
1494 let context = self.context(app).notification_context(app);
1495 let extent = self.extent(app);
1497 extent.add_pixel_delta(app, delta, context.expect("a mounted scrollable"));
1498 if (velocity.get() > 0.0 && extent.is_at_max(app))
1499 || (velocity.get() < 0.0 && extent.is_at_min(app))
1500 {
1501 let controller_velocity = ballistic_controller.velocity(app);
1505 let metrics = self.copy_with(app);
1506 velocity.set(
1507 controller_velocity
1508 + self.physics(app).tolerance_for(&*metrics).velocity
1509 * controller_velocity.signum(),
1510 );
1511 ScrollPositionWithSingleContext::go_ballistic(self, app, velocity.get());
1512 ballistic_controller.stop(app, true);
1513 } else if Animation::is_completed(ballistic_controller, app) {
1514 if let Some(snap_size) = self.get_current_snap_size(app) {
1518 let context = self.context(app).notification_context(app);
1519 self.extent(app).update_size(
1520 app,
1521 snap_size,
1522 context.expect("a mounted scrollable"),
1523 );
1524 }
1525 ScrollPositionWithSingleContext::go_ballistic(self, app, 0.0);
1526 }
1527 }
1528 };
1529
1530 Animation::add_listener(ballistic_controller, app, Listener::new(tick));
1531 let future = ballistic_controller.animate_with(app, simulation);
1532 future.when_complete_or_cancel(
1533 app,
1534 Listener::new(move |app: &mut App| {
1535 let controllers = &mut app.get_mut(self).ballistic_controllers;
1536 if let Some(index) = controllers
1537 .iter()
1538 .position(|controller| controller == ballistic_controller)
1539 {
1540 let removed = controllers.remove(index);
1541 removed.dispose(app);
1542 }
1543 }),
1544 );
1545 }
1546
1547 fn drag(
1548 self: Handle<Self>,
1549 app: &mut App,
1550 details: DragStartDetails,
1551 drag_cancel_callback: Listener,
1552 ) -> Rc<dyn Drag> {
1553 app.get_mut(self).drag_cancel_callback = Some(drag_cancel_callback.clone());
1555 ScrollPositionWithSingleContext::drag(self, app, details, drag_cancel_callback)
1556 }
1557}
1558
1559#[derive(Debug)]
1572pub struct DraggableScrollableActuator {
1573 pub key: Option<KeyRef>,
1575 pub child: WidgetRef,
1578}
1579
1580impl DraggableScrollableActuator {
1581 #[cfg_attr(debug_assertions, track_caller)]
1584 pub fn new<K>(child: impl IntoWidget<K>) -> DraggableScrollableActuator {
1585 DraggableScrollableActuator {
1586 key: None,
1587 child: child.into_widget(),
1588 }
1589 }
1590
1591 pub fn key(mut self, key: KeyRef) -> DraggableScrollableActuator {
1593 self.key = Some(key);
1594 self
1595 }
1596
1597 pub fn reset(app: &mut App, context: BuildContext) -> bool {
1604 let notifier = context
1605 .depend_on_inherited_widget_of_exact_type::<InheritedResetNotifier>(app)
1606 .map(|widget| widget.notifier.handle());
1607 notifier.is_some_and(|notifier| notifier.send_reset(app))
1608 }
1609}
1610
1611impl StatefulWidget for DraggableScrollableActuator {
1612 type State = DraggableScrollableActuatorState;
1613
1614 fn key(&self) -> Option<&KeyRef> {
1615 self.key.as_ref()
1616 }
1617
1618 fn create_state(&self) -> DraggableScrollableActuatorState {
1619 DraggableScrollableActuatorState {
1620 state: StateData::new(),
1621 notifier: None,
1622 }
1623 }
1624}
1625
1626pub struct DraggableScrollableActuatorState {
1628 state: StateData<DraggableScrollableActuator>,
1629 notifier: Option<Ref<ResetNotifier>>,
1630}
1631
1632impl State for DraggableScrollableActuatorState {
1633 type Widget = DraggableScrollableActuator;
1634 crate::state_accessors!();
1635
1636 fn init_state(self: Handle<Self>, app: &mut App) {
1637 app.get_mut(self).notifier = Some(ResetNotifier::new(app));
1638 }
1639
1640 fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
1641 InheritedResetNotifier {
1642 notifier: app.get(self).notifier.clone().expect("init_state has run"),
1643 child: self.widget(app).child.clone(),
1644 }
1645 .into_widget()
1646 }
1647
1648 fn dispose(self: Handle<Self>, app: &mut App) {
1649 let notifier = app.get(self).notifier.handle().expect("init_state has run");
1650 notifier.dispose(app);
1651 }
1652}
1653
1654struct ResetNotifier {
1657 change_notifier: ChangeNotifierData,
1658 was_called: bool,
1662}
1663
1664impl ResetNotifier {
1665 fn new(app: &mut App) -> Ref<ResetNotifier> {
1666 app.create(ResetNotifier {
1667 change_notifier: ChangeNotifierData::new(),
1668 was_called: false,
1669 })
1670 }
1671
1672 fn send_reset(self: Handle<Self>, app: &mut App) -> bool {
1676 if !app.get(self).change_notifier.has_listeners() {
1677 return false;
1678 }
1679 app.get_mut(self).was_called = true;
1680 self.notify_listeners(app);
1681 true
1682 }
1683
1684 fn dispose(self: Handle<Self>, app: &mut App) {
1686 ChangeNotifierData::dispose(app, self);
1687 }
1688}
1689
1690impl ChangeNotifier for ResetNotifier {
1691 fn change_notifier_data(&self) -> &ChangeNotifierData {
1692 &self.change_notifier
1693 }
1694
1695 fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
1696 &mut self.change_notifier
1697 }
1698}
1699
1700#[derive(Debug)]
1704struct InheritedResetNotifier {
1705 notifier: Ref<ResetNotifier>,
1706 child: WidgetRef,
1707}
1708
1709impl InheritedResetNotifier {
1710 fn into_widget(self) -> WidgetRef {
1713 IntoWidget::<InheritedNotifierKind>::into_widget(self)
1714 }
1715
1716 fn should_reset(app: &mut App, context: BuildContext) -> bool {
1721 let Some(widget) =
1722 context.depend_on_inherited_widget_of_exact_type::<InheritedResetNotifier>(app)
1723 else {
1724 return false;
1725 };
1726 let notifier = widget.notifier.handle();
1727 let was_called = app.get(notifier).was_called;
1728 app.get_mut(notifier).was_called = false;
1729 was_called
1730 }
1731}
1732
1733impl InheritedWidget for InheritedResetNotifier {
1734 crate::inherited_notifier_overrides!();
1735
1736 fn child(&self) -> &WidgetRef {
1737 &self.child
1738 }
1739}
1740
1741impl InheritedNotifier for InheritedResetNotifier {
1742 type Notifier = ResetNotifier;
1743
1744 fn notifier(&self) -> Option<Handle<ResetNotifier>> {
1745 Some(self.notifier.handle())
1746 }
1747}
1748
1749#[derive(Debug)]
1754struct SnappingSimulation {
1755 position: f64,
1756 velocity: f64,
1757 pixel_snap_size: f64,
1758 tolerance: Tolerance,
1759}
1760
1761impl SnappingSimulation {
1762 const MINIMUM_SPEED: f64 = 1600.0;
1765
1766 fn new(
1767 position: f64,
1768 initial_velocity: f64,
1769 pixel_snap_size: Vec<f64>,
1770 snap_animation_duration: Option<Duration>,
1771 tolerance: Tolerance,
1772 ) -> SnappingSimulation {
1773 let pixel_snap_size = SnappingSimulation::get_snap_size(
1774 position,
1775 initial_velocity,
1776 &pixel_snap_size,
1777 tolerance,
1778 );
1779
1780 let velocity = match snap_animation_duration {
1781 Some(duration) if duration.as_millis() > 0 => {
1782 (pixel_snap_size - position) * 1000.0 / duration.as_millis() as f64
1783 }
1784 _ if pixel_snap_size < position => {
1787 (-SnappingSimulation::MINIMUM_SPEED).min(initial_velocity)
1788 }
1789 _ => SnappingSimulation::MINIMUM_SPEED.max(initial_velocity),
1790 };
1791
1792 SnappingSimulation {
1793 position,
1794 velocity,
1795 pixel_snap_size,
1796 tolerance,
1797 }
1798 }
1799
1800 fn get_snap_size(
1804 position: f64,
1805 initial_velocity: f64,
1806 pixel_snap_sizes: &[f64],
1807 tolerance: Tolerance,
1808 ) -> f64 {
1809 let index_of_next_size = pixel_snap_sizes.iter().position(|size| *size >= position);
1810 if index_of_next_size == Some(0) {
1811 return pixel_snap_sizes[0];
1812 }
1813 let index_of_next_size =
1814 index_of_next_size.expect("the position is at or below the largest snap size");
1815 let next_size = pixel_snap_sizes[index_of_next_size];
1816 if next_size == position {
1818 return next_size;
1819 }
1820 let previous_size = pixel_snap_sizes[index_of_next_size - 1];
1821 if initial_velocity.abs() <= tolerance.velocity {
1822 if position - previous_size < next_size - position {
1824 return previous_size;
1825 }
1826 return next_size;
1827 }
1828 if initial_velocity < 0.0 {
1830 return pixel_snap_sizes[index_of_next_size - 1];
1831 }
1832 pixel_snap_sizes[index_of_next_size]
1833 }
1834}
1835
1836impl Simulation for SnappingSimulation {
1837 fn x(&self, time: f64) -> f64 {
1838 let new_position = self.position + self.velocity * time;
1839 if (self.velocity >= 0.0 && new_position > self.pixel_snap_size)
1840 || (self.velocity < 0.0 && new_position < self.pixel_snap_size)
1841 {
1842 return self.pixel_snap_size;
1844 }
1845 new_position
1846 }
1847
1848 fn dx(&self, time: f64) -> f64 {
1849 if self.is_done(time) {
1850 return 0.0;
1851 }
1852 self.velocity
1853 }
1854
1855 fn is_done(&self, time: f64) -> bool {
1856 self.x(time) == self.pixel_snap_size
1857 }
1858
1859 fn tolerance(&self) -> Tolerance {
1860 self.tolerance
1861 }
1862
1863 fn set_tolerance(&mut self, tolerance: Tolerance) {
1864 self.tolerance = tolerance;
1865 }
1866}
1867
1868#[cfg(test)]
1869mod tests {
1870 use std::cell::Cell;
1871
1872 use waft_animation::Curves;
1873 use waft_embedder::{Offset, TextDirection};
1874 use waft_gestures::{DragEndDetails, DragUpdateDetails, Velocity};
1875
1876 use super::*;
1877 use crate::testing::{WidgetTester, test_widgets};
1878 use crate::widgets::basic::{Builder, Directionality};
1879 use crate::widgets::media_query::{MediaQuery, MediaQueryData};
1880 use crate::widgets::single_child_scroll_view::SingleChildScrollView;
1881
1882 const VIEW_HEIGHT: f64 = WidgetTester::SIZE.height();
1883
1884 fn wrap<K>(child: impl IntoWidget<K>) -> WidgetRef {
1887 let query: WidgetRef =
1888 MediaQuery::new(MediaQueryData::new().size(WidgetTester::SIZE), child).into_widget();
1889 Directionality::new(TextDirection::Ltr, query).into_widget()
1890 }
1891
1892 fn scrollable_builder() -> ScrollableWidgetBuilder {
1894 Rc::new(|_app, _context, controller| {
1895 SingleChildScrollView::new()
1896 .controller(controller)
1897 .child(
1898 SizedBox::new()
1899 .height(2.5 * VIEW_HEIGHT)
1900 .width(WidgetTester::SIZE.width()),
1901 )
1902 .into_widget()
1903 })
1904 }
1905
1906 fn drag_by(delta: f64) -> DragUpdateDetails {
1907 DragUpdateDetails::new(
1908 Offset::ZERO,
1909 None,
1910 Some(Duration::ZERO),
1911 Offset::new(0.0, delta),
1912 Some(delta),
1913 None,
1914 )
1915 }
1916
1917 fn position(
1918 app: &App,
1919 controller: Ref<DraggableScrollableController>,
1920 ) -> Handle<DraggableScrollableSheetScrollPosition> {
1921 controller.attached_controller(app).position(app)
1922 }
1923
1924 #[test]
1925 fn the_sheet_starts_at_the_initial_child_size() {
1926 test_widgets(|tester| {
1927 let controller = tester.update(DraggableScrollableController::new);
1928 tester.pump_widget(wrap(
1929 DraggableScrollableSheet::new(scrollable_builder())
1930 .initial_child_size(0.4)
1931 .controller(controller.clone()),
1932 ));
1933 let app = tester.cell.borrow();
1934
1935 assert!(controller.is_attached(&app));
1936 assert_eq!(controller.size(&app), 0.4);
1937 assert_eq!(controller.pixels(&app), VIEW_HEIGHT * 0.4);
1939 });
1940 }
1941
1942 #[test]
1943 fn a_drag_on_the_scrollable_grows_the_sheet_up_to_the_max_child_size() {
1944 test_widgets(|tester| {
1945 let controller = tester.update(DraggableScrollableController::new);
1946 tester.pump_widget(wrap(
1947 DraggableScrollableSheet::new(scrollable_builder())
1948 .initial_child_size(0.5)
1949 .controller(controller.clone()),
1950 ));
1951 let mut app = tester.cell.borrow_mut();
1952
1953 let position = position(&app, controller.clone());
1954 let drag = ScrollPosition::drag(
1955 position,
1956 &mut app,
1957 waft_gestures::DragStartDetails::default(),
1958 Listener::new(|_app| {}),
1959 );
1960
1961 drag.update(&mut app, drag_by(-VIEW_HEIGHT / 5.0));
1963 assert!(
1964 (controller.size(&app) - 0.7).abs() < 1e-9,
1965 "{}",
1966 controller.size(&app)
1967 );
1968 assert_eq!(waft_rendering::ViewportOffset::pixels(position, &app), 0.0);
1970
1971 drag.update(&mut app, drag_by(-VIEW_HEIGHT));
1973 assert_eq!(controller.size(&app), 1.0);
1974 drag.update(&mut app, drag_by(-10.0));
1975 assert_eq!(controller.size(&app), 1.0);
1976 assert!(waft_rendering::ViewportOffset::pixels(position, &app) > 0.0);
1977
1978 drag.end(
1979 &mut app,
1980 DragEndDetails::new(Offset::ZERO, None, Velocity::ZERO, Some(0.0)),
1981 );
1982 });
1983 }
1984
1985 #[test]
1986 fn animate_to_reaches_the_size_and_notifies() {
1987 test_widgets(|tester| {
1988 let controller = tester.update(DraggableScrollableController::new);
1989 tester.pump_widget(wrap(
1990 DraggableScrollableSheet::new(scrollable_builder())
1991 .initial_child_size(0.5)
1992 .controller(controller.clone()),
1993 ));
1994
1995 let notified = Rc::new(Cell::new(0));
1996 let counter = Rc::clone(¬ified);
1997 tester.update(|app| {
1998 ListenableObject::add_listener(
1999 controller.handle(),
2000 app,
2001 Listener::new(move |_app| counter.set(counter.get() + 1)),
2002 )
2003 });
2004
2005 let done = tester.update(|app| {
2006 controller.animate_to(app, 0.8, Duration::from_millis(100), Curves::linear())
2007 });
2008
2009 tester.pump();
2010 tester.pump_by(Duration::from_millis(50));
2011 let size = controller.size(&tester.cell.borrow());
2012 assert!((size - 0.65).abs() < 0.01, "{size}");
2013 assert!(!done.is_completed());
2014
2015 tester.pump_by(Duration::from_millis(50));
2016 let size = controller.size(&tester.cell.borrow());
2017 assert!((size - 0.8).abs() < 1e-9, "{size}");
2018 assert!(notified.get() > 0);
2019 tester.pump_by(Duration::from_millis(50));
2022 assert!(done.is_completed());
2023 });
2024 }
2025
2026 #[test]
2027 fn a_snapping_sheet_settles_on_the_nearest_snap_size() {
2028 test_widgets(|tester| {
2029 let controller = tester.update(DraggableScrollableController::new);
2030 tester.pump_widget(wrap(
2031 DraggableScrollableSheet::new(scrollable_builder())
2032 .initial_child_size(0.5)
2033 .snap(true)
2034 .snap_sizes(vec![0.5])
2035 .controller(controller.clone()),
2036 ));
2037
2038 tester.update(|app| {
2039 let position = position(app, controller.clone());
2040 let drag = ScrollPosition::drag(
2041 position,
2042 app,
2043 waft_gestures::DragStartDetails::default(),
2044 Listener::new(|_app| {}),
2045 );
2046 drag.update(app, drag_by(-VIEW_HEIGHT * 0.15));
2048 assert!(
2049 (controller.size(app) - 0.65).abs() < 1e-9,
2050 "{}",
2051 controller.size(app)
2052 );
2053 drag.end(
2054 app,
2055 DragEndDetails::new(Offset::ZERO, None, Velocity::ZERO, Some(0.0)),
2056 );
2057 });
2058
2059 tester.pump();
2060 for _ in 0..200 {
2061 if (controller.size(&tester.cell.borrow()) - 0.5).abs() < 1e-9 {
2062 break;
2063 }
2064 tester.pump_by(Duration::from_millis(16));
2065 }
2066 assert_eq!(controller.size(&tester.cell.borrow()), 0.5);
2068 });
2069 }
2070
2071 #[test]
2072 fn the_actuator_resets_the_sheet_to_its_initial_size() {
2073 test_widgets(|tester| {
2074 let controller = tester.update(DraggableScrollableController::new);
2075 let inner_context: Rc<Cell<Option<BuildContext>>> = Rc::new(Cell::new(None));
2076 let reported = Rc::clone(&inner_context);
2077 let sheet_controller = controller.clone();
2078 tester.pump_widget(wrap(DraggableScrollableActuator::new(Builder::new(
2079 move |_app, context| {
2080 reported.set(Some(context));
2081 DraggableScrollableSheet::new(scrollable_builder())
2082 .initial_child_size(0.5)
2083 .controller(sheet_controller.clone())
2084 .into_widget()
2085 },
2086 ))));
2087
2088 tester.update(|app| controller.jump_to(app, 0.9));
2089 assert_eq!(controller.size(&tester.cell.borrow()), 0.9);
2090
2091 let context = inner_context.get().expect("the builder ran");
2092 assert!(tester.update(|app| DraggableScrollableActuator::reset(app, context)));
2093 tester.pump_by(Duration::from_millis(16));
2094
2095 assert_eq!(controller.size(&tester.cell.borrow()), 0.5);
2096 });
2097 }
2098}