Skip to main content

cranpose_ui/modifier/
scroll.rs

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 draggable;
15mod release_motion;
16mod scroll_target;
17use drag_gesture::{DragGesture, nested_drag_gesture_input};
18use scroll_target::{NestedTarget, ScrollTarget};
19
20use super::{Modifier, Point, PointerEvent, PointerEventKind, inspector_metadata};
21use crate::{
22    bring_into_view_spec::current_bring_into_view_spec,
23    draggable::ScrollableState,
24    fling_animation::{
25        FlingAnimation, MIN_FLING_VELOCITY, SettleAnimation, SpringParams, fling_rest_position,
26    },
27    gesture_velocity::GestureVelocity,
28    render_state::schedule_modifier_slices_repass,
29    scroll::{
30        ScrollElement, ScrollMotionContext, ScrollMotionContextKey, ScrollState,
31        scroll_motion_context_for_key,
32    },
33    scroll_semantics::lazy_scroll_semantics,
34};
35
36/// The velocity of the last fling that started in the current app context, in dp per second.
37#[cfg(feature = "test-helpers")]
38pub fn last_fling_velocity() -> f32 {
39    crate::render_state::debug_last_fling_velocity()
40}
41
42/// Sets the value that [`last_fling_velocity`] returns to zero.
43#[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    /// Whether the press stopped a scroll animation the app started, so
62    /// letting go settles even without a drag.
63    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    // The running scroll of the target that the fling or the settle holds.
78    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    // A delta of the pointer as the scroll target takes it.
175    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 = event.position;
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(event, self.along_axis(event.global_position));
215
216        false
217    }
218
219    fn on_move(&self, position: Point, buttons: PointerButtons, event: &PointerEvent) -> bool {
220        let mut gs = self.gesture_state.borrow_mut();
221
222        if !buttons.contains(PointerButton::Primary) && gs.drag_down_position.is_some() {
223            if gs.is_dragging {
224                self.scroll_target.set_dragging(false);
225            }
226            gs.drag_down_position = None;
227            gs.last_position = None;
228            gs.is_dragging = false;
229            gs.axis_locked_out = false;
230            gs.velocity.clear();
231            self.motion_context.set_active(false);
232            return false;
233        }
234
235        let Some(down_pos) = gs.drag_down_position else {
236            return false;
237        };
238
239        let Some(last_pos) = gs.last_position else {
240            gs.last_position = Some(position);
241            return false;
242        };
243
244        let incremental_delta = delta_along(last_pos, position, self.axis);
245
246        let mut edge_candidate = false;
247        if !gs.is_dragging && !gs.axis_locked_out {
248            let signed_main_delta = delta_along(down_pos, position, self.axis);
249            let main_delta = signed_main_delta.abs();
250            let cross_delta = delta_along(down_pos, position, self.axis.cross_axis()).abs();
251            if main_delta > DRAG_THRESHOLD && main_delta >= cross_delta {
252                if self
253                    .scroll_target
254                    .can_consume(self.toward_target(signed_main_delta))
255                {
256                    gs.is_dragging = true;
257                    self.scroll_target.set_dragging(true);
258                    self.motion_context.set_active(true);
259                } else if self.scroll_target.can_scroll() {
260                    edge_candidate = true;
261                }
262            } else if cross_delta > DRAG_THRESHOLD && cross_delta > main_delta {
263                gs.axis_locked_out = true;
264            }
265        }
266
267        gs.last_position = Some(position);
268
269        // In the window: an element that follows the finger barely moves under it.
270        gs.velocity
271            .add(event, self.along_axis(event.global_position));
272
273        if gs.is_dragging {
274            drop(gs);
275            let delta = self.toward_target(incremental_delta);
276            let overscroll = self.overscroll.clone();
277            overscroll.apply_to_scroll(delta, |delta| self.scroll_target.apply_delta(delta));
278            self.scroll_target.invalidate();
279            true
280        } else if gs.is_overscrolling {
281            drop(gs);
282            let delta = self.toward_target(incremental_delta);
283            self.apply_overscroll_delta(delta)
284        } else if edge_candidate {
285            drop(gs);
286            let delta = self.toward_target(incremental_delta);
287            let detector = self.clone_for_watcher();
288            event.defer_post_dispatch_action(move || detector.apply_overscroll_candidate(delta));
289            false
290        } else {
291            false
292        }
293    }
294
295    fn apply_overscroll_delta(&self, delta: f32) -> bool {
296        self.motion_context.set_active(true);
297        let overscroll = self.overscroll.clone();
298        let target_consumed = Cell::new(0.0);
299        let before_overscroll = overscroll.offset();
300        overscroll.apply_to_scroll(delta, |delta| {
301            let consumed = self.scroll_target.apply_delta(delta);
302            target_consumed.set(consumed);
303            consumed
304        });
305        self.scroll_target.invalidate();
306        let consumed = target_consumed.get().abs() > 0.001
307            || (overscroll.offset() - before_overscroll).abs() > 0.001;
308        if !consumed {
309            self.motion_context.set_active(false);
310        }
311        consumed
312    }
313
314    fn apply_overscroll_candidate(&self, delta: f32) -> bool {
315        if self.gesture_state.borrow().disposed {
316            return false;
317        }
318        let consumed = self.apply_overscroll_delta(delta);
319        if consumed {
320            self.gesture_state.borrow_mut().is_overscrolling = true;
321        }
322        consumed
323    }
324
325    fn on_scroll(&self, axis_delta: f32, event: &PointerEvent) -> bool {
326        if axis_delta.abs() <= f32::EPSILON {
327            return false;
328        }
329
330        let delta = self.toward_target(axis_delta);
331        if !self.scroll_target.can_consume(delta) && self.scroll_target.can_scroll() {
332            let detector = self.clone_for_watcher();
333            event.defer_post_dispatch_action(move || detector.apply_wheel_delta(delta));
334            return false;
335        }
336        self.apply_wheel_delta(delta)
337    }
338
339    fn apply_wheel_delta(&self, delta: f32) -> bool {
340        {
341            let mut gs = self.gesture_state.borrow_mut();
342            if gs.disposed {
343                return false;
344            }
345            if let Some(fling) = gs.fling_animation.take() {
346                fling.cancel();
347            }
348            if let Some(settle) = gs.settle_animation.take() {
349                settle.cancel();
350            }
351            gs.drag_down_position = None;
352            gs.last_position = None;
353            gs.is_dragging = false;
354            gs.axis_locked_out = false;
355            gs.velocity.clear();
356        }
357
358        self.motion_context.activate_for_current_frame();
359        let overscroll = self.overscroll.clone();
360        let consumed =
361            overscroll.apply_to_scroll(delta, |delta| self.scroll_target.apply_wheel_delta(delta));
362        let overscroll_active = self.overscroll.offset().abs() > 0.001;
363        if consumed.abs() > 0.001 {
364            self.scroll_target.invalidate();
365        }
366        if consumed.abs() > 0.001 || overscroll_active {
367            self.ensure_wheel_settle_watcher();
368            true
369        } else {
370            false
371        }
372    }
373
374    fn ensure_wheel_settle_watcher(&self) {
375        if self.scroll_target.settle_policy().is_none() && self.overscroll.offset().abs() <= 0.001 {
376            return;
377        }
378        {
379            let gs = self.gesture_state.borrow();
380            if gs
381                .wheel_settle_watcher
382                .as_ref()
383                .is_some_and(|watcher| watcher.is_running.get())
384            {
385                return;
386            }
387        }
388        let Some(runtime) = current_runtime_handle() else {
389            return;
390        };
391
392        let is_running = Rc::new(Cell::new(true));
393        let registration = Rc::new(RefCell::new(None));
394
395        struct WheelSettleLoop<S: ScrollTarget> {
396            detector: ScrollGestureDetector<S>,
397            gesture_state: Rc<RefCell<ScrollGestureState>>,
398            frame_clock: cranpose_core::internal::FrameClock,
399            is_running: Rc<Cell<bool>>,
400            registration: Rc<RefCell<Option<FrameCallbackRegistration>>>,
401            last_offset: Rc<Cell<f32>>,
402            idle_nanos: Rc<Cell<u64>>,
403            last_frame: Rc<Cell<Option<u64>>>,
404        }
405
406        impl<S: ScrollTarget + 'static> WheelSettleLoop<S> {
407            fn next(&self) -> Self {
408                Self {
409                    detector: self.detector.clone_for_watcher(),
410                    gesture_state: Rc::clone(&self.gesture_state),
411                    frame_clock: self.frame_clock.clone(),
412                    is_running: Rc::clone(&self.is_running),
413                    registration: Rc::clone(&self.registration),
414                    last_offset: Rc::clone(&self.last_offset),
415                    idle_nanos: Rc::clone(&self.idle_nanos),
416                    last_frame: Rc::clone(&self.last_frame),
417                }
418            }
419
420            fn schedule(self) {
421                let continuation = self.next();
422                let registration_slot = Rc::clone(&self.registration);
423                let new_registration = self.frame_clock.with_frame_nanos(move |frame_time_nanos| {
424                    let this = &continuation;
425                    if !this.is_running.get() {
426                        return;
427                    }
428                    {
429                        let gs = this.gesture_state.borrow();
430                        let animating = gs.is_dragging
431                            || gs
432                                .fling_animation
433                                .as_ref()
434                                .is_some_and(FlingAnimation::is_running)
435                            || gs
436                                .settle_animation
437                                .as_ref()
438                                .is_some_and(SettleAnimation::is_running);
439                        if animating {
440                            this.is_running.set(false);
441                            return;
442                        }
443                    }
444
445                    let offset = this.detector.scroll_target.current_offset();
446                    let dt = this
447                        .last_frame
448                        .get()
449                        .map_or(0, |last| frame_time_nanos.saturating_sub(last));
450                    this.last_frame.set(Some(frame_time_nanos));
451                    if (offset - this.last_offset.get()).abs() > 0.01 {
452                        this.last_offset.set(offset);
453                        this.idle_nanos.set(0);
454                    } else {
455                        this.idle_nanos.set(this.idle_nanos.get() + dt);
456                    }
457
458                    if this.idle_nanos.get() >= WHEEL_SETTLE_IDLE_NANOS {
459                        this.is_running.set(false);
460                        if this.detector.overscroll.offset().abs() > 0.001 {
461                            this.detector.start_overscroll_settle(0.0);
462                            return;
463                        }
464                        if let Some(policy) = this.detector.scroll_target.settle_policy() {
465                            let target = policy(offset, 0.0);
466                            if (target - offset).abs() > 0.5 {
467                                this.detector.start_settle_animation(target, 0.0);
468                            }
469                        }
470                        return;
471                    }
472
473                    continuation.next().schedule();
474                });
475                *registration_slot.borrow_mut() = Some(new_registration);
476            }
477        }
478
479        WheelSettleLoop {
480            detector: self.clone_for_watcher(),
481            gesture_state: Rc::clone(&self.gesture_state),
482            frame_clock: runtime.frame_clock(),
483            is_running: Rc::clone(&is_running),
484            registration: Rc::clone(&registration),
485            last_offset: Rc::new(Cell::new(self.scroll_target.current_offset())),
486            idle_nanos: Rc::new(Cell::new(0u64)),
487            last_frame: Rc::new(Cell::new(None::<u64>)),
488        }
489        .schedule();
490
491        self.gesture_state.borrow_mut().wheel_settle_watcher = Some(WheelSettleWatcher {
492            is_running,
493            registration,
494        });
495    }
496
497    fn clone_for_watcher(&self) -> Self {
498        Self {
499            gesture_state: Rc::clone(&self.gesture_state),
500            scroll_target: self.scroll_target.clone(),
501            axis: self.axis,
502            reverse_scrolling: self.reverse_scrolling,
503            overscroll: self.overscroll.clone(),
504            motion_context: self.motion_context.clone(),
505        }
506    }
507}
508
509pub(crate) struct MotionContextAnimatedNode {
510    state: NodeState,
511    motion_context: ScrollMotionContext,
512    invalidation_callback_id: Option<u64>,
513    overscroll_callback_id: Option<u64>,
514    node_id: Option<NodeId>,
515}
516
517impl MotionContextAnimatedNode {
518    fn new(motion_context: ScrollMotionContext) -> Self {
519        Self {
520            state: NodeState::new(),
521            motion_context,
522            invalidation_callback_id: None,
523            overscroll_callback_id: None,
524            node_id: None,
525        }
526    }
527
528    pub(crate) fn is_active(&self) -> bool {
529        self.motion_context.is_active()
530    }
531
532    fn attach_callbacks(&mut self) {
533        if let Some(node_id) = self.node_id {
534            self.invalidation_callback_id = Some(self.motion_context.add_invalidate_callback(
535                Box::new(move || schedule_modifier_slices_repass(node_id)),
536            ));
537            self.overscroll_callback_id = Some(
538                self.motion_context
539                    .overscroll()
540                    .add_invalidate_callback(Box::new(move || {
541                        crate::schedule_measure_repass(node_id);
542                        schedule_modifier_slices_repass(node_id);
543                    })),
544            );
545        }
546    }
547
548    fn detach_callbacks(&mut self) {
549        if let Some(id) = self.invalidation_callback_id.take() {
550            self.motion_context.remove_invalidate_callback(id);
551        }
552        if let Some(id) = self.overscroll_callback_id.take() {
553            self.motion_context
554                .overscroll()
555                .remove_invalidate_callback(id);
556        }
557    }
558}
559
560pub(crate) struct TranslatedContentContextNode {
561    state: NodeState,
562    identity: usize,
563    offset_source: TranslatedContentOffsetSource,
564    overscroll: crate::scroll::OverscrollEffect,
565    overscroll_callback_id: Option<u64>,
566    node_id: Option<NodeId>,
567}
568
569impl TranslatedContentContextNode {
570    fn new(
571        identity: usize,
572        offset_source: TranslatedContentOffsetSource,
573        overscroll: crate::scroll::OverscrollEffect,
574    ) -> Self {
575        Self {
576            state: NodeState::new(),
577            identity,
578            offset_source,
579            overscroll,
580            overscroll_callback_id: None,
581            node_id: None,
582        }
583    }
584
585    pub(crate) fn is_active(&self) -> bool {
586        true
587    }
588
589    pub(crate) fn identity(&self) -> usize {
590        self.identity
591    }
592
593    pub(crate) fn content_offset_reader(&self) -> Option<Rc<dyn Fn() -> Point>> {
594        self.offset_source
595            .content_offset_reader(self.overscroll.clone())
596    }
597
598    fn attach_callback(&mut self) {
599        if let Some(node_id) = self.node_id {
600            self.overscroll_callback_id =
601                Some(self.overscroll.add_invalidate_callback(Box::new(move || {
602                    schedule_modifier_slices_repass(node_id);
603                })));
604        }
605    }
606
607    fn detach_callback(&mut self) {
608        if let Some(id) = self.overscroll_callback_id.take() {
609            self.overscroll.remove_invalidate_callback(id);
610        }
611    }
612}
613
614impl DelegatableNode for TranslatedContentContextNode {
615    fn node_state(&self) -> &NodeState {
616        &self.state
617    }
618}
619
620impl ModifierNode for TranslatedContentContextNode {
621    fn on_attach(&mut self, context: &mut dyn cranpose_foundation::ModifierNodeContext) {
622        self.node_id = context.node_id();
623        self.attach_callback();
624    }
625
626    fn on_detach(&mut self) {
627        self.detach_callback();
628        self.node_id = None;
629    }
630}
631
632impl DelegatableNode for MotionContextAnimatedNode {
633    fn node_state(&self) -> &NodeState {
634        &self.state
635    }
636}
637
638impl ModifierNode for MotionContextAnimatedNode {
639    fn on_attach(&mut self, context: &mut dyn cranpose_foundation::ModifierNodeContext) {
640        self.node_id = context.node_id();
641        self.attach_callbacks();
642    }
643
644    fn on_detach(&mut self) {
645        self.detach_callbacks();
646        self.node_id = None;
647    }
648}
649
650#[derive(Clone)]
651struct MotionContextAnimatedElement {
652    motion_context: ScrollMotionContext,
653}
654
655impl MotionContextAnimatedElement {
656    fn new(motion_context: ScrollMotionContext) -> Self {
657        Self { motion_context }
658    }
659}
660
661impl std::fmt::Debug for MotionContextAnimatedElement {
662    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
663        f.debug_struct("MotionContextAnimatedElement").finish()
664    }
665}
666
667impl PartialEq for MotionContextAnimatedElement {
668    fn eq(&self, other: &Self) -> bool {
669        self.motion_context.ptr_eq(&other.motion_context)
670    }
671}
672
673impl Eq for MotionContextAnimatedElement {}
674
675impl std::hash::Hash for MotionContextAnimatedElement {
676    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
677        self.motion_context.stable_key().hash(state);
678    }
679}
680
681impl ModifierNodeElement for MotionContextAnimatedElement {
682    type Node = MotionContextAnimatedNode;
683
684    fn create(&self) -> Self::Node {
685        MotionContextAnimatedNode::new(self.motion_context.clone())
686    }
687
688    fn update(&self, node: &mut Self::Node) {
689        if node.motion_context.ptr_eq(&self.motion_context) {
690            return;
691        }
692        node.detach_callbacks();
693        node.motion_context = self.motion_context.clone();
694        node.attach_callbacks();
695    }
696
697    fn capabilities(&self) -> NodeCapabilities {
698        NodeCapabilities::LAYOUT
699    }
700}
701
702#[derive(Clone)]
703enum TranslatedContentOffsetSource {
704    LayoutContentOffset,
705    LazyList {
706        state: LazyListState,
707        axis: Axis,
708        reverse_scrolling: bool,
709    },
710}
711
712impl TranslatedContentOffsetSource {
713    fn content_offset_reader(
714        &self,
715        overscroll: crate::scroll::OverscrollEffect,
716    ) -> Option<Rc<dyn Fn() -> Point>> {
717        match self {
718            Self::LayoutContentOffset => None,
719            Self::LazyList { state, axis, .. } => Some(Rc::new(lazy_list_content_offset_reader(
720                *state, *axis, overscroll,
721            ))),
722        }
723    }
724
725    fn axis(&self) -> Option<Axis> {
726        match self {
727            Self::LayoutContentOffset => None,
728            Self::LazyList { axis, .. } => Some(*axis),
729        }
730    }
731
732    fn reverse_scrolling(&self) -> Option<bool> {
733        match self {
734            Self::LayoutContentOffset => None,
735            Self::LazyList {
736                reverse_scrolling, ..
737            } => Some(*reverse_scrolling),
738        }
739    }
740}
741
742fn lazy_list_content_offset_reader(
743    state: LazyListState,
744    axis: Axis,
745    overscroll: crate::scroll::OverscrollEffect,
746) -> impl Fn() -> Point {
747    move || {
748        let Some((viewport, main_offset)) = state
749            .with_layout_info(|info| {
750                (!info.visible_items_info.is_empty())
751                    .then_some((info.viewport_size, info.snap_anchor_offset))
752            })
753            .flatten()
754        else {
755            return Point::default();
756        };
757        overscroll.set_dimension(viewport);
758        let bounce = overscroll.offset();
759        if axis.is_vertical() {
760            Point::new(0.0, main_offset + bounce)
761        } else {
762            Point::new(main_offset + bounce, 0.0)
763        }
764    }
765}
766
767#[derive(Clone)]
768struct TranslatedContentContextElement {
769    identity: usize,
770    offset_source: TranslatedContentOffsetSource,
771    overscroll: crate::scroll::OverscrollEffect,
772}
773
774impl TranslatedContentContextElement {
775    fn new(
776        identity: usize,
777        offset_source: TranslatedContentOffsetSource,
778        overscroll: crate::scroll::OverscrollEffect,
779    ) -> Self {
780        Self {
781            identity,
782            offset_source,
783            overscroll,
784        }
785    }
786}
787
788impl std::fmt::Debug for TranslatedContentContextElement {
789    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
790        let offset_source = match &self.offset_source {
791            TranslatedContentOffsetSource::LayoutContentOffset => "layout",
792            TranslatedContentOffsetSource::LazyList { .. } => "lazy_list",
793        };
794        f.debug_struct("TranslatedContentContextElement")
795            .field("identity", &self.identity)
796            .field("offset_source", &offset_source)
797            .finish()
798    }
799}
800
801impl PartialEq for TranslatedContentContextElement {
802    fn eq(&self, other: &Self) -> bool {
803        self.identity == other.identity
804            && self.overscroll.ptr_eq(&other.overscroll)
805            && self.offset_source.axis() == other.offset_source.axis()
806            && self.offset_source.reverse_scrolling() == other.offset_source.reverse_scrolling()
807    }
808}
809
810impl Eq for TranslatedContentContextElement {}
811
812impl std::hash::Hash for TranslatedContentContextElement {
813    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
814        self.identity.hash(state);
815        self.offset_source.axis().hash(state);
816        self.offset_source.reverse_scrolling().hash(state);
817    }
818}
819
820impl ModifierNodeElement for TranslatedContentContextElement {
821    type Node = TranslatedContentContextNode;
822
823    fn create(&self) -> Self::Node {
824        TranslatedContentContextNode::new(
825            self.identity,
826            self.offset_source.clone(),
827            self.overscroll.clone(),
828        )
829    }
830
831    fn update(&self, node: &mut Self::Node) {
832        node.identity = self.identity;
833        node.offset_source = self.offset_source.clone();
834        if !node.overscroll.ptr_eq(&self.overscroll) {
835            node.detach_callback();
836            node.overscroll = self.overscroll.clone();
837            node.attach_callback();
838        }
839    }
840
841    fn capabilities(&self) -> NodeCapabilities {
842        NodeCapabilities::LAYOUT
843    }
844}
845
846impl Modifier {
847    /// Creates a horizontally scrollable modifier.
848    ///
849    /// # Arguments
850    /// * `state` - The ScrollState to control scroll position
851    /// * `reverse_scrolling` - If true, reverses the scroll direction in layout.
852    ///   Note: This affects how scroll offset is applied to content (via `ScrollNode`),
853    ///   NOT the drag direction. Drag gestures always follow natural touch semantics:
854    ///   drag right = scroll left (content moves right under finger).
855    ///
856    /// # Example
857    /// ```text
858    /// let scroll_state = ScrollState::new(0.0);
859    /// Row(
860    ///     Modifier::empty().horizontal_scroll(scroll_state, false),
861    ///     // ... content
862    /// );
863    /// ```
864    pub fn horizontal_scroll(self, state: ScrollState, reverse_scrolling: bool) -> Self {
865        self.then(scroll_impl(
866            state,
867            Axis::Horizontal,
868            reverse_scrolling,
869            None,
870            (0.0, 0.0),
871        ))
872    }
873
874    /// Creates a vertically scrollable modifier.
875    ///
876    /// # Arguments
877    /// * `state` - The ScrollState to control scroll position
878    /// * `reverse_scrolling` - If true, reverses the scroll direction in layout.
879    ///   Note: This affects how scroll offset is applied to content (via `ScrollNode`),
880    ///   NOT the drag direction. Drag gestures always follow natural touch semantics:
881    ///   drag down = scroll up (content moves down under finger).
882    pub fn vertical_scroll(self, state: ScrollState, reverse_scrolling: bool) -> Self {
883        self.then(scroll_impl(
884            state,
885            Axis::Vertical,
886            reverse_scrolling,
887            None,
888            (0.0, 0.0),
889        ))
890    }
891
892    /// Adds a vertical scroll container with content padding in logical pixels.
893    ///
894    /// The padding scrolls with the content. Keyboard and accessibility focus
895    /// keep controls inside the padded viewport, clear of overlaid system UI.
896    pub fn vertical_scroll_with_content_padding(
897        self,
898        state: ScrollState,
899        reverse_scrolling: bool,
900        padding: cranpose_ui_graphics::EdgeInsets,
901    ) -> Self {
902        let density = crate::density();
903        self.then(scroll_impl(
904            state,
905            Axis::Vertical,
906            reverse_scrolling,
907            None,
908            (density.dp(padding.top), density.dp(padding.bottom)),
909        ))
910        .window_insets_padding(padding)
911    }
912
913    /// Adds a horizontal scroll container with content padding in logical pixels.
914    ///
915    /// The padding scrolls with the content. Keyboard and accessibility focus
916    /// keep controls inside the padded viewport. Insets use physical edges.
917    pub fn horizontal_scroll_with_content_padding(
918        self,
919        state: ScrollState,
920        reverse_scrolling: bool,
921        padding: cranpose_ui_graphics::EdgeInsets,
922    ) -> Self {
923        let density = crate::density();
924        self.then(scroll_impl(
925            state,
926            Axis::Horizontal,
927            reverse_scrolling,
928            None,
929            (density.dp(padding.left), density.dp(padding.right)),
930        ))
931        .window_insets_padding(padding)
932    }
933
934    /// A horizontal scroll that never claims a pointer gesture.
935    ///
936    /// The position still moves through [`ScrollState`], but drags and wheel
937    /// events pass straight through, so an owner can run its own
938    /// `pointer_input` on the same row -- a drag-to-reorder list, say --
939    /// without the two competing for the gesture.
940    pub fn horizontal_scroll_without_gestures(
941        self,
942        state: ScrollState,
943        reverse_scrolling: bool,
944    ) -> Self {
945        self.then(scroll_impl(
946            state,
947            Axis::Horizontal,
948            reverse_scrolling,
949            Some(Rc::new(|| false)),
950            (0.0, 0.0),
951        ))
952    }
953
954    /// A vertical scroll that never claims a pointer gesture.
955    ///
956    /// The vertical counterpart of [`Modifier::horizontal_scroll_without_gestures`].
957    pub fn vertical_scroll_without_gestures(
958        self,
959        state: ScrollState,
960        reverse_scrolling: bool,
961    ) -> Self {
962        self.then(scroll_impl(
963            state,
964            Axis::Vertical,
965            reverse_scrolling,
966            Some(Rc::new(|| false)),
967            (0.0, 0.0),
968        ))
969    }
970
971    /// Creates a vertically scrollable modifier for lazy lists.
972    ///
973    /// This connects pointer gestures to LazyListState for scroll handling.
974    /// Unlike regular vertical_scroll, no layout offset is applied here
975    /// since LazyListState manages item positioning internally.
976    /// Creates a vertically scrollable modifier for lazy lists.
977    ///
978    /// This connects pointer gestures to LazyListState for scroll handling.
979    /// Unlike regular vertical_scroll, no layout offset is applied here
980    /// since LazyListState manages item positioning internally.
981    pub fn lazy_vertical_scroll(self, state: LazyListState, reverse_scrolling: bool) -> Self {
982        let motion_context = scroll_motion_context_for_key(ScrollMotionContextKey::LazyList {
983            state_identity: state.inner_ptr() as usize,
984            axis: Axis::Vertical,
985            reverse_scrolling,
986        });
987        self.lazy_vertical_scroll_with_context(state, reverse_scrolling, (0.0, 0.0), motion_context)
988    }
989
990    pub(crate) fn lazy_vertical_scroll_with_context(
991        self,
992        state: LazyListState,
993        reverse_scrolling: bool,
994        content_padding: (f32, f32),
995        motion_context: ScrollMotionContext,
996    ) -> Self {
997        self.then(lazy_scroll_impl(
998            state,
999            Axis::Vertical,
1000            reverse_scrolling,
1001            content_padding,
1002            motion_context,
1003        ))
1004    }
1005
1006    pub(crate) fn lazy_horizontal_scroll_with_context(
1007        self,
1008        state: LazyListState,
1009        reverse_scrolling: bool,
1010        content_padding: (f32, f32),
1011        motion_context: ScrollMotionContext,
1012    ) -> Self {
1013        self.then(lazy_scroll_impl(
1014            state,
1015            Axis::Horizontal,
1016            reverse_scrolling,
1017            content_padding,
1018            motion_context,
1019        ))
1020    }
1021
1022    /// Scrolls content with custom placement along `axis`.
1023    ///
1024    /// Supplies drag, wheel and inertial scrolling without translating or
1025    /// clipping layout. A new pointer press interrupts the fling. The state's
1026    /// consumption handler stops it when the content reaches a boundary.
1027    pub fn scrollable(self, axis: Axis, state: ScrollableState) -> Self {
1028        let identity = state.identity();
1029        let motion_context = scroll_motion_context_for_key(ScrollMotionContextKey::Draggable {
1030            state_identity: identity,
1031            axis,
1032        });
1033        self.then(Self::with_element(MotionContextAnimatedElement::new(
1034            motion_context.clone(),
1035        )))
1036        .then(nested_drag_gesture_input(
1037            (identity, axis),
1038            DragGesture {
1039                target: state,
1040                axis,
1041                reverse_input: false,
1042                motion_context,
1043                guard: None,
1044            },
1045        ))
1046    }
1047}
1048
1049fn scroll_impl(
1050    state: ScrollState,
1051    axis: Axis,
1052    reverse_scrolling: bool,
1053    guard: Option<Rc<dyn Fn() -> bool>>,
1054    content_padding: (f32, f32),
1055) -> Modifier {
1056    let motion_context = scroll_motion_context_for_key(ScrollMotionContextKey::ScrollState {
1057        state_id: state.id(),
1058        axis,
1059        reverse_scrolling,
1060    });
1061    motion_context
1062        .observe_activity(|| Box::new(move |active| state.set_scroll_in_progress(active)));
1063
1064    let pointer_input = nested_drag_gesture_input(
1065        (state.id(), axis),
1066        DragGesture {
1067            target: state,
1068            axis,
1069            reverse_input: false,
1070            motion_context: motion_context.clone(),
1071            guard,
1072        },
1073    );
1074
1075    let overscroll = motion_context.overscroll();
1076    let element = ScrollElement::new(state, overscroll.clone(), axis, reverse_scrolling);
1077    let layout_modifier =
1078        Modifier::with_element(element).with_inspector_metadata(inspector_metadata(
1079            if axis.is_vertical() {
1080                "verticalScroll"
1081            } else {
1082                "horizontalScroll"
1083            },
1084            move |info| {
1085                info.add_property("isVertical", axis.is_vertical().to_string());
1086                info.add_property("reverseScrolling", reverse_scrolling.to_string());
1087            },
1088        ));
1089    let motion_modifier = Modifier::with_element(MotionContextAnimatedElement::new(motion_context));
1090    let translated_content_modifier = Modifier::with_element(TranslatedContentContextElement::new(
1091        state.id() as usize,
1092        TranslatedContentOffsetSource::LayoutContentOffset,
1093        overscroll,
1094    ));
1095
1096    // The clip wraps the scroll layout, as Compose's `scrollingContainer`
1097    // clips before it scrolls: it cuts at the viewport, not at the content
1098    // the layout moves.
1099    pointer_input
1100        .clip_to_bounds()
1101        .then(motion_modifier)
1102        .then(translated_content_modifier)
1103        .then(layout_modifier)
1104        .semantics(scroll_semantics(
1105            state,
1106            axis,
1107            reverse_scrolling,
1108            content_padding,
1109        ))
1110}
1111
1112/// What a screen reader learns about a scroll container: how far it has
1113/// scrolled, whether it can go on, and how to page it. Compose's
1114/// `verticalScrollAxisRange` / `horizontalScrollAxisRange` and `scrollBy`.
1115/// Without this a reader's cursor stops at the last row it can see.
1116fn scroll_semantics(
1117    state: ScrollState,
1118    axis: Axis,
1119    reverse_scrolling: bool,
1120    content_padding: (f32, f32),
1121) -> impl Fn(&mut cranpose_foundation::SemanticsConfiguration) + 'static {
1122    let spec = current_bring_into_view_spec();
1123    move |config| {
1124        let range = cranpose_foundation::ScrollAxisRange::new(
1125            state.value(),
1126            state.max_value(),
1127            reverse_scrolling,
1128        )
1129        .with_content_padding(content_padding.0, content_padding.1)
1130        .with_bring_into_view_spec(spec);
1131        if axis.is_vertical() {
1132            config.vertical_scroll = Some(range);
1133        } else {
1134            config.horizontal_scroll = Some(range);
1135        }
1136        config.scroll_by = Some(cranpose_foundation::SemanticsScrollBy::new(
1137            move |dx, dy| {
1138                let delta = if axis.is_vertical() { dy } else { dx };
1139                state.dispatch_raw_delta(delta).abs() > f32::EPSILON
1140            },
1141        ));
1142    }
1143}
1144
1145fn lazy_scroll_impl(
1146    state: LazyListState,
1147    axis: Axis,
1148    reverse_scrolling: bool,
1149    content_padding: (f32, f32),
1150    motion_context: ScrollMotionContext,
1151) -> Modifier {
1152    let list_state = state;
1153    let state_id = state.inner_ptr() as usize;
1154    let key = (state_id, axis, reverse_scrolling);
1155    motion_context
1156        .observe_activity(|| Box::new(move |active| state.set_gesture_scroll_active(active)));
1157    let overscroll = motion_context.overscroll();
1158    let translated_content_modifier = Modifier::with_element(TranslatedContentContextElement::new(
1159        state_id,
1160        TranslatedContentOffsetSource::LazyList {
1161            state,
1162            axis,
1163            reverse_scrolling,
1164        },
1165        overscroll,
1166    ));
1167
1168    Modifier::with_element(MotionContextAnimatedElement::new(motion_context.clone()))
1169        .then(translated_content_modifier)
1170        .then(nested_drag_gesture_input(
1171            key,
1172            DragGesture {
1173                target: list_state,
1174                axis,
1175                reverse_input: reverse_scrolling,
1176                motion_context,
1177                guard: None,
1178            },
1179        ))
1180        .semantics(lazy_scroll_semantics(
1181            list_state,
1182            axis,
1183            reverse_scrolling,
1184            content_padding,
1185        ))
1186}