Skip to main content

blit_widget/interact/
drag.rs

1use blit::{Axis, ContactId, ContactSource, InteractCx, Phase, Point, Scalar, builder, input::MouseButton};
2
3use crate::Context;
4
5builder! {
6    /// follows one primary mouse press once it moves [`Context::MOUSE_SLOP`] or touch once it moves [`Context::SLOP`]
7    ///
8    /// with an `axis`, starts only when movement is mostly along it
9    #[derive(Clone, Copy, Debug)]
10    pub struct Interact {
11        new(),
12        #[into]
13        axis: Option<Axis> = None,
14        /// accepts only touch contacts
15        touch_only: bool = false,
16    }
17}
18
19/// the response of [`Interact`]
20///
21/// `activated` implies `active` unless `deactivated`, and `released` implies `deactivated`
22#[derive(Clone, Copy, Debug, Default, PartialEq)]
23pub struct Response<T> {
24    /// a contact is being dragged
25    pub active: bool,
26    pub activated: bool,
27    pub deactivated: bool,
28    /// the drag ended by letting go rather than by cancellation or its widget disappearing
29    pub released: bool,
30    pub position: Point<T>,
31    /// movement since the previous update, or since the press when activated
32    pub delta: Point<T>,
33}
34
35impl<C: Context> blit::Interact<C> for Interact {
36    /// the dragged contact
37    type State = Option<ContactId>;
38    type Response = Response<C::Scalar>;
39
40    fn update(&self, drag: &mut Option<ContactId>, cx: &mut InteractCx<'_, C::Scalar>) -> Self::Response {
41        if let Some(id) = *drag {
42            let Some(contact) = cx.contacts().find(|contact| contact.id == id && contact.free) else {
43                *drag = None;
44                // a contact this widget lost ends the drag without a release
45                return Response {
46                    deactivated: true,
47                    ..Response::default()
48                };
49            };
50            let active = !matches!(contact.phase, Phase::Ended | Phase::Cancelled);
51            if !active {
52                *drag = None;
53            }
54            return Response {
55                active,
56                activated: false,
57                deactivated: !active,
58                released: contact.phase == Phase::Ended,
59                position: contact.position,
60                delta: contact.delta,
61            };
62        }
63        let touch_slop = C::SLOP.to_f32();
64        let mouse_slop = C::MOUSE_SLOP.to_f32();
65        let contact = cx.contacts().find(|contact| {
66            let x = (contact.position.x - contact.origin.x).to_f32();
67            let y = (contact.position.y - contact.origin.y).to_f32();
68            let distance = x * x + y * y;
69            matches!(contact.phase, Phase::Changed | Phase::Ended)
70                && contact.free
71                && match contact.source {
72                    ContactSource::Touch(_) => distance >= touch_slop * touch_slop,
73                    ContactSource::Mouse(button) => {
74                        !self.touch_only && button == MouseButton::Primary && distance >= mouse_slop * mouse_slop
75                    }
76                }
77                && distance > 0.0
78                && self
79                    .axis
80                    .is_none_or(|axis| (axis == Axis::Horizontal) == (x.abs() >= y.abs()))
81        });
82        let Some(mut contact) = contact else {
83            return Response::default();
84        };
85        if !contact.capture() {
86            return Response::default();
87        }
88        // a release past the threshold starts and ends in one update
89        let active = contact.phase == Phase::Changed;
90        if active {
91            *drag = Some(contact.id);
92        }
93        Response {
94            active,
95            activated: true,
96            deactivated: !active,
97            released: !active,
98            position: contact.position,
99            delta: Point::new(
100                contact.position.x - contact.origin.x,
101                contact.position.y - contact.origin.y,
102            ),
103        }
104    }
105}
106
107#[cfg(test)]
108mod tests {
109    use std::cell::Cell;
110
111    use blit::{
112        Scope, Tree, Ui,
113        input::{
114            Input,
115            TouchPhase::{Down, Move, Up},
116        },
117    };
118
119    use super::*;
120    use crate::{
121        interact,
122        test::{TestContext, pointer, step},
123    };
124
125    /// a horizontal slider inside a vertical pan
126    fn slider(mut ui: Ui<'_, TestContext>) -> (Response<f32>, Response<f32>) {
127        let pan = ui.interact(interact::drag().axis(Axis::Vertical));
128        let slider = ui
129            .layout(())
130            .child()
131            .build(|mut ui: Ui<'_, TestContext>| ui.interact(interact::drag().axis(Axis::Horizontal)));
132        (pan, slider)
133    }
134
135    fn dragging(x: f32, y: f32, dx: f32, dy: f32) -> Response<f32> {
136        Response {
137            active: true,
138            position: Point::new(x, y),
139            delta: Point::new(dx, dy),
140            ..Response::default()
141        }
142    }
143
144    fn let_go(x: f32, y: f32, dx: f32, dy: f32) -> Response<f32> {
145        Response {
146            active: false,
147            deactivated: true,
148            released: true,
149            ..dragging(x, y, dx, dy)
150        }
151    }
152
153    #[test]
154    fn drags_pick_contacts_by_axis() {
155        let idle = Response::default();
156        let mut tree = Tree::default();
157        let mut next = |input| step(&mut tree, input, slider);
158        next(Input::None);
159        next(pointer(Some(1), Down, 10.0, 10.0));
160        assert_eq!(next(pointer(Some(1), Move, 12.0, 10.0)), (idle, idle));
161        let started = next(pointer(Some(1), Move, 30.0, 10.0));
162        let activated = Response {
163            activated: true,
164            ..dragging(30.0, 10.0, 20.0, 0.0)
165        };
166        assert_eq!(started, (idle, activated));
167        // a held drag stays active and ignores a second contact
168        let held = dragging(30.0, 10.0, 0.0, 0.0);
169        assert_eq!(next(pointer(Some(2), Down, 50.0, 50.0)), (idle, held));
170        assert_eq!(next(pointer(Some(2), Move, 80.0, 50.0)), (idle, held));
171        let ended = next(pointer(Some(1), Up, 35.0, 10.0));
172        assert_eq!(ended, (idle, let_go(35.0, 10.0, 5.0, 0.0)));
173        // once free, the slider takes the other contact on its next move
174        let taken = next(pointer(Some(2), Move, 90.0, 50.0));
175        assert!(taken.1.activated && taken.1.active && taken.1.delta == Point::new(40.0, 0.0));
176        next(pointer(Some(2), Up, 90.0, 50.0));
177
178        // vertical movement goes to the pan and the slider never takes it later
179        next(pointer(Some(3), Down, 10.0, 10.0));
180        let panned = next(pointer(Some(3), Move, 10.0, 30.0));
181        assert!(panned.0.activated && panned.1 == idle);
182        let sideways = next(pointer(Some(3), Move, 60.0, 30.0));
183        assert_eq!(sideways, (dragging(60.0, 30.0, 50.0, 0.0), idle));
184        let cancelled = next(Input::Cancel);
185        let cancelled_state = Response {
186            released: false,
187            ..let_go(60.0, 30.0, 0.0, 0.0)
188        };
189        assert_eq!(cancelled, (cancelled_state, idle));
190    }
191
192    #[test]
193    fn removing_the_dragged_widget_cancels() {
194        let handle = 1000;
195        let mut tree = Tree::<TestContext>::default();
196        let mounted = Cell::new(true);
197        let build = |mut ui: Ui<'_, TestContext>| {
198            let handle_id = ui.resolve(Scope::ROOT, handle);
199            let drag = ui.node(handle_id).interact(interact::drag());
200            if mounted.get() {
201                ui.layout(())
202                    .child_in(Scope::ROOT, handle)
203                    .build(|_: Ui<'_, TestContext>| {});
204            }
205            drag
206        };
207        let mut next = |input| step(&mut tree, input, build);
208        next(Input::None);
209        next(pointer(Some(1), Down, 10.0, 10.0));
210        assert!(next(pointer(Some(1), Move, 40.0, 10.0)).active);
211        mounted.set(false);
212        next(pointer(Some(1), Move, 50.0, 10.0));
213        let removed = next(Input::None);
214        assert!(removed.deactivated && !removed.released && !removed.active);
215    }
216}