1use std::{
2 cell::{Cell, RefCell},
3 rc::Rc,
4};
5
6use cranpose_core::{NodeId, current_runtime_handle, internal::FrameCallbackRegistration};
7use cranpose_foundation::{
8 DRAG_THRESHOLD, DelegatableNode, ModifierNode, ModifierNodeElement, NodeCapabilities,
9 NodeState, PointerButton, PointerButtons, ScrollId, lazy::LazyListState,
10};
11use cranpose_ui_layout::Axis;
12
13mod drag_gesture;
14mod release_motion;
15mod scroll_target;
16use drag_gesture::{DragGesture, drag_gesture_input, nested_drag_gesture_input};
17use scroll_target::{NestedTarget, ScrollTarget};
18
19use super::{Modifier, Point, PointerEvent, PointerEventKind, inspector_metadata};
20use crate::{
21 bring_into_view_spec::current_bring_into_view_spec,
22 draggable::{DraggableState, ScrollableState},
23 fling_animation::{
24 FlingAnimation, MIN_FLING_VELOCITY, SettleAnimation, SpringParams, fling_rest_position,
25 },
26 gesture_velocity::GestureVelocity,
27 render_state::schedule_modifier_slices_repass,
28 scroll::{
29 ScrollElement, ScrollMotionContext, ScrollMotionContextKey, ScrollState,
30 scroll_motion_context_for_key,
31 },
32 scroll_semantics::lazy_scroll_semantics,
33};
34
35#[cfg(feature = "test-helpers")]
38pub fn last_fling_velocity() -> f32 {
39 crate::render_state::debug_last_fling_velocity()
40}
41
42#[cfg(feature = "test-helpers")]
44pub fn reset_last_fling_velocity() {
45 crate::render_state::debug_reset_last_fling_velocity();
46}
47
48#[inline]
49fn set_last_fling_velocity(velocity: f32) {
50 crate::render_state::record_last_fling_velocity(velocity);
51}
52
53struct ScrollGestureState {
54 disposed: bool,
55 drag_down_position: Option<Point>,
56
57 last_position: Option<Point>,
58
59 is_dragging: bool,
60
61 interrupted_animation: bool,
64
65 axis_locked_out: bool,
66
67 velocity: GestureVelocity,
68
69 fling_animation: Option<FlingAnimation>,
70
71 is_overscrolling: bool,
72
73 settle_animation: Option<SettleAnimation>,
74
75 wheel_settle_watcher: Option<WheelSettleWatcher>,
76
77 running_scroll: Option<ScrollId>,
79}
80
81impl Default for ScrollGestureState {
82 fn default() -> Self {
83 Self {
84 disposed: false,
85 drag_down_position: None,
86 last_position: None,
87 is_dragging: false,
88 interrupted_animation: false,
89 axis_locked_out: false,
90 velocity: GestureVelocity::new(),
91 fling_animation: None,
92 is_overscrolling: false,
93 settle_animation: None,
94 wheel_settle_watcher: None,
95 running_scroll: None,
96 }
97 }
98}
99
100impl ScrollGestureState {
101 fn is_active(&self) -> bool {
102 self.is_dragging
103 || self.is_overscrolling
104 || self
105 .fling_animation
106 .as_ref()
107 .is_some_and(FlingAnimation::is_running)
108 || self
109 .settle_animation
110 .as_ref()
111 .is_some_and(SettleAnimation::is_running)
112 || self
113 .wheel_settle_watcher
114 .as_ref()
115 .is_some_and(|watcher| watcher.is_running.get())
116 }
117}
118
119#[inline]
120fn delta_along(from: Point, to: Point, axis: Axis) -> f32 {
121 match axis {
122 Axis::Horizontal => to.x - from.x,
123 Axis::Vertical => to.y - from.y,
124 }
125}
126
127const WHEEL_SETTLE_IDLE_NANOS: u64 = 180_000_000;
128
129struct WheelSettleWatcher {
130 is_running: Rc<Cell<bool>>,
131 registration: Rc<RefCell<Option<FrameCallbackRegistration>>>,
132}
133
134impl WheelSettleWatcher {
135 fn cancel(&self) {
136 self.is_running.set(false);
137 self.registration.borrow_mut().take();
138 }
139}
140
141struct ScrollGestureDetector<S: ScrollTarget> {
142 gesture_state: Rc<RefCell<ScrollGestureState>>,
143
144 scroll_target: S,
145
146 axis: Axis,
147
148 reverse_scrolling: bool,
149
150 overscroll: crate::scroll::OverscrollEffect,
151
152 motion_context: ScrollMotionContext,
153}
154
155impl<S: ScrollTarget + 'static> ScrollGestureDetector<S> {
156 fn new(
157 gesture_state: Rc<RefCell<ScrollGestureState>>,
158 scroll_target: S,
159 axis: Axis,
160 reverse_scrolling: bool,
161 overscroll: crate::scroll::OverscrollEffect,
162 motion_context: ScrollMotionContext,
163 ) -> Self {
164 Self {
165 gesture_state,
166 scroll_target,
167 axis,
168 reverse_scrolling,
169 overscroll,
170 motion_context,
171 }
172 }
173
174 fn toward_target(&self, pointer_delta: f32) -> f32 {
176 if self.reverse_scrolling {
177 -pointer_delta
178 } else {
179 pointer_delta
180 }
181 }
182
183 fn along_axis(&self, point: Point) -> f32 {
184 if self.axis.is_vertical() {
185 point.y
186 } else {
187 point.x
188 }
189 }
190
191 fn on_down(&self, event: &PointerEvent) -> bool {
192 let (position, time_ms) = (event.position, event.time_ms);
193 let interrupted = self.scroll_target.stop_animation();
194 let mut gs = self.gesture_state.borrow_mut();
195 gs.interrupted_animation = interrupted;
196
197 if let Some(fling) = gs.fling_animation.take() {
198 fling.cancel();
199 }
200 if let Some(settle) = gs.settle_animation.take() {
201 settle.cancel();
202 }
203 if let Some(watcher) = gs.wheel_settle_watcher.take() {
204 watcher.cancel();
205 }
206 self.motion_context.set_active(false);
207
208 gs.drag_down_position = Some(position);
209 gs.last_position = Some(position);
210 gs.is_dragging = false;
211 gs.axis_locked_out = false;
212 gs.is_overscrolling = self.overscroll.offset().abs() > 0.001;
213 gs.velocity
214 .begin(time_ms, self.along_axis(event.global_position));
215
216 false
217 }
218
219 fn on_move(
220 &self,
221 position: Point,
222 buttons: PointerButtons,
223 time_ms: Option<i64>,
224 event: &PointerEvent,
225 ) -> bool {
226 let mut gs = self.gesture_state.borrow_mut();
227
228 if !buttons.contains(PointerButton::Primary) && gs.drag_down_position.is_some() {
229 if gs.is_dragging {
230 self.scroll_target.set_dragging(false);
231 }
232 gs.drag_down_position = None;
233 gs.last_position = None;
234 gs.is_dragging = false;
235 gs.axis_locked_out = false;
236 gs.velocity.clear();
237 self.motion_context.set_active(false);
238 return false;
239 }
240
241 let Some(down_pos) = gs.drag_down_position else {
242 return false;
243 };
244
245 let Some(last_pos) = gs.last_position else {
246 gs.last_position = Some(position);
247 return false;
248 };
249
250 let incremental_delta = delta_along(last_pos, position, self.axis);
251
252 let mut edge_candidate = false;
253 if !gs.is_dragging && !gs.axis_locked_out {
254 let signed_main_delta = delta_along(down_pos, position, self.axis);
255 let main_delta = signed_main_delta.abs();
256 let cross_delta = delta_along(down_pos, position, self.axis.cross_axis()).abs();
257 if main_delta > DRAG_THRESHOLD && main_delta >= cross_delta {
258 if self
259 .scroll_target
260 .can_consume(self.toward_target(signed_main_delta))
261 {
262 gs.is_dragging = true;
263 self.scroll_target.set_dragging(true);
264 self.motion_context.set_active(true);
265 } else if self.scroll_target.can_scroll() {
266 edge_candidate = true;
267 }
268 } else if cross_delta > DRAG_THRESHOLD && cross_delta > main_delta {
269 gs.axis_locked_out = true;
270 }
271 }
272
273 gs.last_position = Some(position);
274
275 gs.velocity
277 .add(time_ms, self.along_axis(event.global_position));
278
279 if gs.is_dragging {
280 drop(gs);
281 let delta = self.toward_target(incremental_delta);
282 let overscroll = self.overscroll.clone();
283 overscroll.apply_to_scroll(delta, |delta| self.scroll_target.apply_delta(delta));
284 self.scroll_target.invalidate();
285 true
286 } else if gs.is_overscrolling {
287 drop(gs);
288 let delta = self.toward_target(incremental_delta);
289 self.apply_overscroll_delta(delta)
290 } else if edge_candidate {
291 drop(gs);
292 let delta = self.toward_target(incremental_delta);
293 let detector = self.clone_for_watcher();
294 event.defer_post_dispatch_action(move || detector.apply_overscroll_candidate(delta));
295 false
296 } else {
297 false
298 }
299 }
300
301 fn apply_overscroll_delta(&self, delta: f32) -> bool {
302 self.motion_context.set_active(true);
303 let overscroll = self.overscroll.clone();
304 let target_consumed = Cell::new(0.0);
305 let before_overscroll = overscroll.offset();
306 overscroll.apply_to_scroll(delta, |delta| {
307 let consumed = self.scroll_target.apply_delta(delta);
308 target_consumed.set(consumed);
309 consumed
310 });
311 self.scroll_target.invalidate();
312 let consumed = target_consumed.get().abs() > 0.001
313 || (overscroll.offset() - before_overscroll).abs() > 0.001;
314 if !consumed {
315 self.motion_context.set_active(false);
316 }
317 consumed
318 }
319
320 fn apply_overscroll_candidate(&self, delta: f32) -> bool {
321 if self.gesture_state.borrow().disposed {
322 return false;
323 }
324 let consumed = self.apply_overscroll_delta(delta);
325 if consumed {
326 self.gesture_state.borrow_mut().is_overscrolling = true;
327 }
328 consumed
329 }
330
331 fn on_scroll(&self, axis_delta: f32, event: &PointerEvent) -> bool {
332 if axis_delta.abs() <= f32::EPSILON {
333 return false;
334 }
335
336 let delta = self.toward_target(axis_delta);
337 if !self.scroll_target.can_consume(delta) && self.scroll_target.can_scroll() {
338 let detector = self.clone_for_watcher();
339 event.defer_post_dispatch_action(move || detector.apply_wheel_delta(delta));
340 return false;
341 }
342 self.apply_wheel_delta(delta)
343 }
344
345 fn apply_wheel_delta(&self, delta: f32) -> bool {
346 {
347 let mut gs = self.gesture_state.borrow_mut();
348 if gs.disposed {
349 return false;
350 }
351 if let Some(fling) = gs.fling_animation.take() {
352 fling.cancel();
353 }
354 if let Some(settle) = gs.settle_animation.take() {
355 settle.cancel();
356 }
357 gs.drag_down_position = None;
358 gs.last_position = None;
359 gs.is_dragging = false;
360 gs.axis_locked_out = false;
361 gs.velocity.clear();
362 }
363
364 self.motion_context.activate_for_current_frame();
365 let overscroll = self.overscroll.clone();
366 let consumed =
367 overscroll.apply_to_scroll(delta, |delta| self.scroll_target.apply_wheel_delta(delta));
368 let overscroll_active = self.overscroll.offset().abs() > 0.001;
369 if consumed.abs() > 0.001 {
370 self.scroll_target.invalidate();
371 }
372 if consumed.abs() > 0.001 || overscroll_active {
373 self.ensure_wheel_settle_watcher();
374 true
375 } else {
376 false
377 }
378 }
379
380 fn ensure_wheel_settle_watcher(&self) {
381 if self.scroll_target.settle_policy().is_none() && self.overscroll.offset().abs() <= 0.001 {
382 return;
383 }
384 {
385 let gs = self.gesture_state.borrow();
386 if gs
387 .wheel_settle_watcher
388 .as_ref()
389 .is_some_and(|watcher| watcher.is_running.get())
390 {
391 return;
392 }
393 }
394 let Some(runtime) = current_runtime_handle() else {
395 return;
396 };
397
398 let is_running = Rc::new(Cell::new(true));
399 let registration = Rc::new(RefCell::new(None));
400
401 struct WheelSettleLoop<S: ScrollTarget> {
402 detector: ScrollGestureDetector<S>,
403 gesture_state: Rc<RefCell<ScrollGestureState>>,
404 frame_clock: cranpose_core::internal::FrameClock,
405 is_running: Rc<Cell<bool>>,
406 registration: Rc<RefCell<Option<FrameCallbackRegistration>>>,
407 last_offset: Rc<Cell<f32>>,
408 idle_nanos: Rc<Cell<u64>>,
409 last_frame: Rc<Cell<Option<u64>>>,
410 }
411
412 impl<S: ScrollTarget + 'static> WheelSettleLoop<S> {
413 fn next(&self) -> Self {
414 Self {
415 detector: self.detector.clone_for_watcher(),
416 gesture_state: Rc::clone(&self.gesture_state),
417 frame_clock: self.frame_clock.clone(),
418 is_running: Rc::clone(&self.is_running),
419 registration: Rc::clone(&self.registration),
420 last_offset: Rc::clone(&self.last_offset),
421 idle_nanos: Rc::clone(&self.idle_nanos),
422 last_frame: Rc::clone(&self.last_frame),
423 }
424 }
425
426 fn schedule(self) {
427 let continuation = self.next();
428 let registration_slot = Rc::clone(&self.registration);
429 let new_registration = self.frame_clock.with_frame_nanos(move |frame_time_nanos| {
430 let this = &continuation;
431 if !this.is_running.get() {
432 return;
433 }
434 {
435 let gs = this.gesture_state.borrow();
436 let animating = gs.is_dragging
437 || gs
438 .fling_animation
439 .as_ref()
440 .is_some_and(FlingAnimation::is_running)
441 || gs
442 .settle_animation
443 .as_ref()
444 .is_some_and(SettleAnimation::is_running);
445 if animating {
446 this.is_running.set(false);
447 return;
448 }
449 }
450
451 let offset = this.detector.scroll_target.current_offset();
452 let dt = this
453 .last_frame
454 .get()
455 .map_or(0, |last| frame_time_nanos.saturating_sub(last));
456 this.last_frame.set(Some(frame_time_nanos));
457 if (offset - this.last_offset.get()).abs() > 0.01 {
458 this.last_offset.set(offset);
459 this.idle_nanos.set(0);
460 } else {
461 this.idle_nanos.set(this.idle_nanos.get() + dt);
462 }
463
464 if this.idle_nanos.get() >= WHEEL_SETTLE_IDLE_NANOS {
465 this.is_running.set(false);
466 if this.detector.overscroll.offset().abs() > 0.001 {
467 this.detector.start_overscroll_settle(0.0);
468 return;
469 }
470 if let Some(policy) = this.detector.scroll_target.settle_policy() {
471 let target = policy(offset, 0.0);
472 if (target - offset).abs() > 0.5 {
473 this.detector.start_settle_animation(target, 0.0);
474 }
475 }
476 return;
477 }
478
479 continuation.next().schedule();
480 });
481 *registration_slot.borrow_mut() = Some(new_registration);
482 }
483 }
484
485 WheelSettleLoop {
486 detector: self.clone_for_watcher(),
487 gesture_state: Rc::clone(&self.gesture_state),
488 frame_clock: runtime.frame_clock(),
489 is_running: Rc::clone(&is_running),
490 registration: Rc::clone(®istration),
491 last_offset: Rc::new(Cell::new(self.scroll_target.current_offset())),
492 idle_nanos: Rc::new(Cell::new(0u64)),
493 last_frame: Rc::new(Cell::new(None::<u64>)),
494 }
495 .schedule();
496
497 self.gesture_state.borrow_mut().wheel_settle_watcher = Some(WheelSettleWatcher {
498 is_running,
499 registration,
500 });
501 }
502
503 fn clone_for_watcher(&self) -> Self {
504 Self {
505 gesture_state: Rc::clone(&self.gesture_state),
506 scroll_target: self.scroll_target.clone(),
507 axis: self.axis,
508 reverse_scrolling: self.reverse_scrolling,
509 overscroll: self.overscroll.clone(),
510 motion_context: self.motion_context.clone(),
511 }
512 }
513}
514
515pub(crate) struct MotionContextAnimatedNode {
516 state: NodeState,
517 motion_context: ScrollMotionContext,
518 invalidation_callback_id: Option<u64>,
519 overscroll_callback_id: Option<u64>,
520 node_id: Option<NodeId>,
521}
522
523impl MotionContextAnimatedNode {
524 fn new(motion_context: ScrollMotionContext) -> Self {
525 Self {
526 state: NodeState::new(),
527 motion_context,
528 invalidation_callback_id: None,
529 overscroll_callback_id: None,
530 node_id: None,
531 }
532 }
533
534 pub(crate) fn is_active(&self) -> bool {
535 self.motion_context.is_active()
536 }
537
538 fn attach_callbacks(&mut self) {
539 if let Some(node_id) = self.node_id {
540 self.invalidation_callback_id = Some(self.motion_context.add_invalidate_callback(
541 Box::new(move || schedule_modifier_slices_repass(node_id)),
542 ));
543 self.overscroll_callback_id = Some(
544 self.motion_context
545 .overscroll()
546 .add_invalidate_callback(Box::new(move || {
547 crate::schedule_measure_repass(node_id);
548 schedule_modifier_slices_repass(node_id);
549 })),
550 );
551 }
552 }
553
554 fn detach_callbacks(&mut self) {
555 if let Some(id) = self.invalidation_callback_id.take() {
556 self.motion_context.remove_invalidate_callback(id);
557 }
558 if let Some(id) = self.overscroll_callback_id.take() {
559 self.motion_context
560 .overscroll()
561 .remove_invalidate_callback(id);
562 }
563 }
564}
565
566pub(crate) struct TranslatedContentContextNode {
567 state: NodeState,
568 identity: usize,
569 offset_source: TranslatedContentOffsetSource,
570 overscroll: crate::scroll::OverscrollEffect,
571 overscroll_callback_id: Option<u64>,
572 node_id: Option<NodeId>,
573}
574
575impl TranslatedContentContextNode {
576 fn new(
577 identity: usize,
578 offset_source: TranslatedContentOffsetSource,
579 overscroll: crate::scroll::OverscrollEffect,
580 ) -> Self {
581 Self {
582 state: NodeState::new(),
583 identity,
584 offset_source,
585 overscroll,
586 overscroll_callback_id: None,
587 node_id: None,
588 }
589 }
590
591 pub(crate) fn is_active(&self) -> bool {
592 true
593 }
594
595 pub(crate) fn identity(&self) -> usize {
596 self.identity
597 }
598
599 pub(crate) fn content_offset_reader(&self) -> Option<Rc<dyn Fn() -> Point>> {
600 self.offset_source
601 .content_offset_reader(self.overscroll.clone())
602 }
603
604 fn attach_callback(&mut self) {
605 if let Some(node_id) = self.node_id {
606 self.overscroll_callback_id =
607 Some(self.overscroll.add_invalidate_callback(Box::new(move || {
608 schedule_modifier_slices_repass(node_id);
609 })));
610 }
611 }
612
613 fn detach_callback(&mut self) {
614 if let Some(id) = self.overscroll_callback_id.take() {
615 self.overscroll.remove_invalidate_callback(id);
616 }
617 }
618}
619
620impl DelegatableNode for TranslatedContentContextNode {
621 fn node_state(&self) -> &NodeState {
622 &self.state
623 }
624}
625
626impl ModifierNode for TranslatedContentContextNode {
627 fn on_attach(&mut self, context: &mut dyn cranpose_foundation::ModifierNodeContext) {
628 self.node_id = context.node_id();
629 self.attach_callback();
630 }
631
632 fn on_detach(&mut self) {
633 self.detach_callback();
634 self.node_id = None;
635 }
636}
637
638impl DelegatableNode for MotionContextAnimatedNode {
639 fn node_state(&self) -> &NodeState {
640 &self.state
641 }
642}
643
644impl ModifierNode for MotionContextAnimatedNode {
645 fn on_attach(&mut self, context: &mut dyn cranpose_foundation::ModifierNodeContext) {
646 self.node_id = context.node_id();
647 self.attach_callbacks();
648 }
649
650 fn on_detach(&mut self) {
651 self.detach_callbacks();
652 self.node_id = None;
653 }
654}
655
656#[derive(Clone)]
657struct MotionContextAnimatedElement {
658 motion_context: ScrollMotionContext,
659}
660
661impl MotionContextAnimatedElement {
662 fn new(motion_context: ScrollMotionContext) -> Self {
663 Self { motion_context }
664 }
665}
666
667impl std::fmt::Debug for MotionContextAnimatedElement {
668 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
669 f.debug_struct("MotionContextAnimatedElement").finish()
670 }
671}
672
673impl PartialEq for MotionContextAnimatedElement {
674 fn eq(&self, other: &Self) -> bool {
675 self.motion_context.ptr_eq(&other.motion_context)
676 }
677}
678
679impl Eq for MotionContextAnimatedElement {}
680
681impl std::hash::Hash for MotionContextAnimatedElement {
682 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
683 self.motion_context.stable_key().hash(state);
684 }
685}
686
687impl ModifierNodeElement for MotionContextAnimatedElement {
688 type Node = MotionContextAnimatedNode;
689
690 fn create(&self) -> Self::Node {
691 MotionContextAnimatedNode::new(self.motion_context.clone())
692 }
693
694 fn update(&self, node: &mut Self::Node) {
695 if node.motion_context.ptr_eq(&self.motion_context) {
696 return;
697 }
698 node.detach_callbacks();
699 node.motion_context = self.motion_context.clone();
700 node.attach_callbacks();
701 }
702
703 fn capabilities(&self) -> NodeCapabilities {
704 NodeCapabilities::LAYOUT
705 }
706}
707
708#[derive(Clone)]
709enum TranslatedContentOffsetSource {
710 LayoutContentOffset,
711 LazyList {
712 state: LazyListState,
713 axis: Axis,
714 reverse_scrolling: bool,
715 },
716}
717
718impl TranslatedContentOffsetSource {
719 fn content_offset_reader(
720 &self,
721 overscroll: crate::scroll::OverscrollEffect,
722 ) -> Option<Rc<dyn Fn() -> Point>> {
723 match self {
724 Self::LayoutContentOffset => None,
725 Self::LazyList { state, axis, .. } => Some(Rc::new(lazy_list_content_offset_reader(
726 *state, *axis, overscroll,
727 ))),
728 }
729 }
730
731 fn axis(&self) -> Option<Axis> {
732 match self {
733 Self::LayoutContentOffset => None,
734 Self::LazyList { axis, .. } => Some(*axis),
735 }
736 }
737
738 fn reverse_scrolling(&self) -> Option<bool> {
739 match self {
740 Self::LayoutContentOffset => None,
741 Self::LazyList {
742 reverse_scrolling, ..
743 } => Some(*reverse_scrolling),
744 }
745 }
746}
747
748fn lazy_list_content_offset_reader(
749 state: LazyListState,
750 axis: Axis,
751 overscroll: crate::scroll::OverscrollEffect,
752) -> impl Fn() -> Point {
753 move || {
754 let Some((viewport, main_offset)) = state
755 .with_layout_info(|info| {
756 (!info.visible_items_info.is_empty())
757 .then_some((info.viewport_size, info.snap_anchor_offset))
758 })
759 .flatten()
760 else {
761 return Point::default();
762 };
763 overscroll.set_dimension(viewport);
764 let bounce = overscroll.offset();
765 if axis.is_vertical() {
766 Point::new(0.0, main_offset + bounce)
767 } else {
768 Point::new(main_offset + bounce, 0.0)
769 }
770 }
771}
772
773#[derive(Clone)]
774struct TranslatedContentContextElement {
775 identity: usize,
776 offset_source: TranslatedContentOffsetSource,
777 overscroll: crate::scroll::OverscrollEffect,
778}
779
780impl TranslatedContentContextElement {
781 fn new(
782 identity: usize,
783 offset_source: TranslatedContentOffsetSource,
784 overscroll: crate::scroll::OverscrollEffect,
785 ) -> Self {
786 Self {
787 identity,
788 offset_source,
789 overscroll,
790 }
791 }
792}
793
794impl std::fmt::Debug for TranslatedContentContextElement {
795 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
796 let offset_source = match &self.offset_source {
797 TranslatedContentOffsetSource::LayoutContentOffset => "layout",
798 TranslatedContentOffsetSource::LazyList { .. } => "lazy_list",
799 };
800 f.debug_struct("TranslatedContentContextElement")
801 .field("identity", &self.identity)
802 .field("offset_source", &offset_source)
803 .finish()
804 }
805}
806
807impl PartialEq for TranslatedContentContextElement {
808 fn eq(&self, other: &Self) -> bool {
809 self.identity == other.identity
810 && self.overscroll.ptr_eq(&other.overscroll)
811 && self.offset_source.axis() == other.offset_source.axis()
812 && self.offset_source.reverse_scrolling() == other.offset_source.reverse_scrolling()
813 }
814}
815
816impl Eq for TranslatedContentContextElement {}
817
818impl std::hash::Hash for TranslatedContentContextElement {
819 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
820 self.identity.hash(state);
821 self.offset_source.axis().hash(state);
822 self.offset_source.reverse_scrolling().hash(state);
823 }
824}
825
826impl ModifierNodeElement for TranslatedContentContextElement {
827 type Node = TranslatedContentContextNode;
828
829 fn create(&self) -> Self::Node {
830 TranslatedContentContextNode::new(
831 self.identity,
832 self.offset_source.clone(),
833 self.overscroll.clone(),
834 )
835 }
836
837 fn update(&self, node: &mut Self::Node) {
838 node.identity = self.identity;
839 node.offset_source = self.offset_source.clone();
840 if !node.overscroll.ptr_eq(&self.overscroll) {
841 node.detach_callback();
842 node.overscroll = self.overscroll.clone();
843 node.attach_callback();
844 }
845 }
846
847 fn capabilities(&self) -> NodeCapabilities {
848 NodeCapabilities::LAYOUT
849 }
850}
851
852impl Modifier {
853 pub fn horizontal_scroll(self, state: ScrollState, reverse_scrolling: bool) -> Self {
871 self.then(scroll_impl(
872 state,
873 Axis::Horizontal,
874 reverse_scrolling,
875 None,
876 (0.0, 0.0),
877 ))
878 }
879
880 pub fn vertical_scroll(self, state: ScrollState, reverse_scrolling: bool) -> Self {
889 self.then(scroll_impl(
890 state,
891 Axis::Vertical,
892 reverse_scrolling,
893 None,
894 (0.0, 0.0),
895 ))
896 }
897
898 pub fn vertical_scroll_with_content_padding(
903 self,
904 state: ScrollState,
905 reverse_scrolling: bool,
906 padding: cranpose_ui_graphics::EdgeInsets,
907 ) -> Self {
908 let density = crate::density();
909 self.then(scroll_impl(
910 state,
911 Axis::Vertical,
912 reverse_scrolling,
913 None,
914 (density.dp(padding.top), density.dp(padding.bottom)),
915 ))
916 .window_insets_padding(padding)
917 }
918
919 pub fn horizontal_scroll_with_content_padding(
924 self,
925 state: ScrollState,
926 reverse_scrolling: bool,
927 padding: cranpose_ui_graphics::EdgeInsets,
928 ) -> Self {
929 let density = crate::density();
930 self.then(scroll_impl(
931 state,
932 Axis::Horizontal,
933 reverse_scrolling,
934 None,
935 (density.dp(padding.left), density.dp(padding.right)),
936 ))
937 .window_insets_padding(padding)
938 }
939
940 pub fn horizontal_scroll_without_gestures(
947 self,
948 state: ScrollState,
949 reverse_scrolling: bool,
950 ) -> Self {
951 self.then(scroll_impl(
952 state,
953 Axis::Horizontal,
954 reverse_scrolling,
955 Some(Rc::new(|| false)),
956 (0.0, 0.0),
957 ))
958 }
959
960 pub fn vertical_scroll_without_gestures(
964 self,
965 state: ScrollState,
966 reverse_scrolling: bool,
967 ) -> Self {
968 self.then(scroll_impl(
969 state,
970 Axis::Vertical,
971 reverse_scrolling,
972 Some(Rc::new(|| false)),
973 (0.0, 0.0),
974 ))
975 }
976
977 pub fn lazy_vertical_scroll(self, state: LazyListState, reverse_scrolling: bool) -> Self {
988 let motion_context = scroll_motion_context_for_key(ScrollMotionContextKey::LazyList {
989 state_identity: state.inner_ptr() as usize,
990 axis: Axis::Vertical,
991 reverse_scrolling,
992 });
993 self.lazy_vertical_scroll_with_context(state, reverse_scrolling, (0.0, 0.0), motion_context)
994 }
995
996 pub(crate) fn lazy_vertical_scroll_with_context(
997 self,
998 state: LazyListState,
999 reverse_scrolling: bool,
1000 content_padding: (f32, f32),
1001 motion_context: ScrollMotionContext,
1002 ) -> Self {
1003 self.then(lazy_scroll_impl(
1004 state,
1005 Axis::Vertical,
1006 reverse_scrolling,
1007 content_padding,
1008 motion_context,
1009 ))
1010 }
1011
1012 pub(crate) fn lazy_horizontal_scroll_with_context(
1013 self,
1014 state: LazyListState,
1015 reverse_scrolling: bool,
1016 content_padding: (f32, f32),
1017 motion_context: ScrollMotionContext,
1018 ) -> Self {
1019 self.then(lazy_scroll_impl(
1020 state,
1021 Axis::Horizontal,
1022 reverse_scrolling,
1023 content_padding,
1024 motion_context,
1025 ))
1026 }
1027
1028 pub fn draggable(self, axis: Axis, state: DraggableState) -> Self {
1040 self.then(draggable_impl(axis, state, None))
1041 }
1042
1043 pub fn scrollable(self, axis: Axis, state: ScrollableState) -> Self {
1049 let identity = state.identity();
1050 let motion_context = scroll_motion_context_for_key(ScrollMotionContextKey::Draggable {
1051 state_identity: identity,
1052 axis,
1053 });
1054 self.then(Self::with_element(MotionContextAnimatedElement::new(
1055 motion_context.clone(),
1056 )))
1057 .then(nested_drag_gesture_input(
1058 (identity, axis),
1059 DragGesture {
1060 target: state,
1061 axis,
1062 reverse_input: false,
1063 motion_context,
1064 guard: None,
1065 },
1066 ))
1067 }
1068
1069 pub fn draggable_guarded(
1075 self,
1076 axis: Axis,
1077 state: DraggableState,
1078 guard: impl Fn() -> bool + 'static,
1079 ) -> Self {
1080 self.then(draggable_impl(axis, state, Some(Rc::new(guard))))
1081 }
1082}
1083
1084fn scroll_impl(
1085 state: ScrollState,
1086 axis: Axis,
1087 reverse_scrolling: bool,
1088 guard: Option<Rc<dyn Fn() -> bool>>,
1089 content_padding: (f32, f32),
1090) -> Modifier {
1091 let motion_context = scroll_motion_context_for_key(ScrollMotionContextKey::ScrollState {
1092 state_id: state.id(),
1093 axis,
1094 reverse_scrolling,
1095 });
1096 motion_context
1097 .observe_activity(|| Box::new(move |active| state.set_scroll_in_progress(active)));
1098
1099 let pointer_input = nested_drag_gesture_input(
1100 (state.id(), axis),
1101 DragGesture {
1102 target: state,
1103 axis,
1104 reverse_input: false,
1105 motion_context: motion_context.clone(),
1106 guard,
1107 },
1108 );
1109
1110 let overscroll = motion_context.overscroll();
1111 let element = ScrollElement::new(state, overscroll.clone(), axis, reverse_scrolling);
1112 let layout_modifier =
1113 Modifier::with_element(element).with_inspector_metadata(inspector_metadata(
1114 if axis.is_vertical() {
1115 "verticalScroll"
1116 } else {
1117 "horizontalScroll"
1118 },
1119 move |info| {
1120 info.add_property("isVertical", axis.is_vertical().to_string());
1121 info.add_property("reverseScrolling", reverse_scrolling.to_string());
1122 },
1123 ));
1124 let motion_modifier = Modifier::with_element(MotionContextAnimatedElement::new(motion_context));
1125 let translated_content_modifier = Modifier::with_element(TranslatedContentContextElement::new(
1126 state.id() as usize,
1127 TranslatedContentOffsetSource::LayoutContentOffset,
1128 overscroll,
1129 ));
1130
1131 pointer_input
1135 .clip_to_bounds()
1136 .then(motion_modifier)
1137 .then(translated_content_modifier)
1138 .then(layout_modifier)
1139 .semantics(scroll_semantics(
1140 state,
1141 axis,
1142 reverse_scrolling,
1143 content_padding,
1144 ))
1145}
1146
1147fn scroll_semantics(
1152 state: ScrollState,
1153 axis: Axis,
1154 reverse_scrolling: bool,
1155 content_padding: (f32, f32),
1156) -> impl Fn(&mut cranpose_foundation::SemanticsConfiguration) + 'static {
1157 let spec = current_bring_into_view_spec();
1158 move |config| {
1159 let range = cranpose_foundation::ScrollAxisRange::new(
1160 state.value(),
1161 state.max_value(),
1162 reverse_scrolling,
1163 )
1164 .with_content_padding(content_padding.0, content_padding.1)
1165 .with_bring_into_view_spec(spec);
1166 if axis.is_vertical() {
1167 config.vertical_scroll = Some(range);
1168 } else {
1169 config.horizontal_scroll = Some(range);
1170 }
1171 config.scroll_by = Some(cranpose_foundation::SemanticsScrollBy::new(
1172 move |dx, dy| {
1173 let delta = if axis.is_vertical() { dy } else { dx };
1174 state.dispatch_raw_delta(delta).abs() > f32::EPSILON
1175 },
1176 ));
1177 }
1178}
1179
1180fn lazy_scroll_impl(
1181 state: LazyListState,
1182 axis: Axis,
1183 reverse_scrolling: bool,
1184 content_padding: (f32, f32),
1185 motion_context: ScrollMotionContext,
1186) -> Modifier {
1187 let list_state = state;
1188 let state_id = state.inner_ptr() as usize;
1189 let key = (state_id, axis, reverse_scrolling);
1190 motion_context
1191 .observe_activity(|| Box::new(move |active| state.set_gesture_scroll_active(active)));
1192 let overscroll = motion_context.overscroll();
1193 let translated_content_modifier = Modifier::with_element(TranslatedContentContextElement::new(
1194 state_id,
1195 TranslatedContentOffsetSource::LazyList {
1196 state,
1197 axis,
1198 reverse_scrolling,
1199 },
1200 overscroll,
1201 ));
1202
1203 Modifier::with_element(MotionContextAnimatedElement::new(motion_context.clone()))
1204 .then(translated_content_modifier)
1205 .then(nested_drag_gesture_input(
1206 key,
1207 DragGesture {
1208 target: list_state,
1209 axis,
1210 reverse_input: reverse_scrolling,
1211 motion_context,
1212 guard: None,
1213 },
1214 ))
1215 .semantics(lazy_scroll_semantics(
1216 list_state,
1217 axis,
1218 reverse_scrolling,
1219 content_padding,
1220 ))
1221}
1222
1223fn draggable_impl(
1224 axis: Axis,
1225 state: DraggableState,
1226 guard: Option<Rc<dyn Fn() -> bool>>,
1227) -> Modifier {
1228 let identity = state.identity();
1229 drag_gesture_input(
1230 (identity, axis),
1231 DragGesture {
1232 target: state,
1233 axis,
1234 reverse_input: false,
1235 motion_context: scroll_motion_context_for_key(ScrollMotionContextKey::Draggable {
1236 state_identity: identity,
1237 axis,
1238 }),
1239 guard,
1240 },
1241 )
1242}