Skip to main content

gpui_material_components/swipe_to_dismiss/
state.rs

1use std::mem;
2
3use gpui::{
4    Context, ElementId, EntityId, EventEmitter, FocusHandle, Pixels, Point, Subscription, Window,
5    px,
6};
7use gpui_material_foundation::{DragCapture, animate, current_material_theme};
8use gpui_material_theme::{Direction, MotionKind, MotionSpec, MotionSpeed};
9
10const DEFAULT_THRESHOLD: Pixels = px(56.);
11pub(super) const SWIPE_SLOP: Pixels = px(6.);
12
13/// The resting anchor or a logical dismissal direction.
14#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
15pub enum SwipeToDismissValue {
16    /// Resting, undismissed position.
17    #[default]
18    Settled,
19    /// Dismissed from leading edge toward trailing edge (left-to-right in LTR, right-to-left in RTL).
20    StartToEnd,
21    /// Dismissed from trailing edge toward leading edge (right-to-left in LTR, left-to-right in RTL).
22    EndToStart,
23}
24
25impl SwipeToDismissValue {
26    fn position(self) -> f32 {
27        match self {
28            Self::Settled => 0.,
29            Self::StartToEnd => 1.,
30            Self::EndToStart => -1.,
31        }
32    }
33
34    fn from_position(position: f32) -> Self {
35        if position > 0. {
36            Self::StartToEnd
37        } else if position < 0. {
38            Self::EndToStart
39        } else {
40            Self::Settled
41        }
42    }
43}
44
45#[derive(Clone, Copy, PartialEq, Eq)]
46pub(super) struct SwipeOptions {
47    pub(super) direction: Direction,
48    pub(super) start_to_end: bool,
49    pub(super) end_to_start: bool,
50    pub(super) gestures_enabled: bool,
51}
52
53impl Default for SwipeOptions {
54    fn default() -> Self {
55        Self {
56            direction: Direction::Ltr,
57            start_to_end: true,
58            end_to_start: true,
59            gestures_enabled: true,
60        }
61    }
62}
63
64impl SwipeOptions {
65    fn allows(self, value: SwipeToDismissValue) -> bool {
66        match value {
67            SwipeToDismissValue::Settled => true,
68            SwipeToDismissValue::StartToEnd => self.start_to_end,
69            SwipeToDismissValue::EndToStart => self.end_to_start,
70        }
71    }
72
73    fn sign(self) -> f32 {
74        match self.direction {
75            Direction::Ltr => 1.,
76            Direction::Rtl => -1.,
77        }
78    }
79
80    pub(super) fn can_start(self, delta: Point<Pixels>) -> bool {
81        delta.x.abs() >= SWIPE_SLOP
82            && delta.x.abs() > delta.y.abs()
83            && self.allows(SwipeToDismissValue::from_position(
84                f32::from(delta.x) * self.sign(),
85            ))
86    }
87}
88
89#[derive(Default)]
90pub(super) enum SwipeInput {
91    #[default]
92    None,
93    Pressed(Point<Pixels>),
94    Mouse {
95        origin: Point<Pixels>,
96        _capture: DragCapture,
97        _escape: Subscription,
98    },
99    Touch,
100    SuppressMouseUp,
101}
102
103pub(super) struct Dismissed(pub(super) SwipeToDismissValue);
104
105/// Retained swipe state. Give each mounted swipe container its own entity.
106pub struct SwipeToDismissState {
107    pub(super) width: Pixels,
108    pub(super) position: f32,
109    target: SwipeToDismissValue,
110    pub(super) settled: SwipeToDismissValue,
111    pub(super) moving: bool,
112    rebase_motion: bool,
113    pub(super) options: SwipeOptions,
114    threshold: Option<Box<dyn Fn(Pixels) -> Pixels>>,
115    pub(super) input: SwipeInput,
116    pub(super) mount: Option<(EntityId, FocusHandle)>,
117}
118
119impl Default for SwipeToDismissState {
120    fn default() -> Self {
121        Self {
122            width: px(0.),
123            position: 0.,
124            target: SwipeToDismissValue::Settled,
125            settled: SwipeToDismissValue::Settled,
126            moving: false,
127            rebase_motion: false,
128            options: SwipeOptions::default(),
129            threshold: None,
130            input: SwipeInput::None,
131            mount: None,
132        }
133    }
134}
135
136impl EventEmitter<Dismissed> for SwipeToDismissState {}
137
138impl SwipeToDismissState {
139    /// Creates a new swipe state settled at [`SwipeToDismissValue::Settled`].
140    pub fn new() -> Self {
141        Self::default()
142    }
143
144    /// Selects the initial anchor before mounting the state.
145    pub fn initial_value(mut self, value: SwipeToDismissValue) -> Self {
146        self.position = value.position();
147        self.target = value;
148        self.settled = value;
149        self
150    }
151
152    /// Computes the release threshold from the current width in logical pixels.
153    /// The default is 56 logical pixels, limited by the available travel.
154    pub fn positional_threshold(mut self, threshold: impl Fn(Pixels) -> Pixels + 'static) -> Self {
155        self.threshold = Some(Box::new(threshold));
156        self
157    }
158
159    /// Returns the nearest anchor to the current foreground position.
160    pub fn current_value(&self) -> SwipeToDismissValue {
161        SwipeToDismissValue::from_position(self.position.round())
162    }
163
164    /// Returns the anchor where the current interaction would land.
165    pub fn target_value(&self) -> SwipeToDismissValue {
166        self.target
167    }
168
169    /// Returns the last fully reached anchor.
170    pub fn settled_value(&self) -> SwipeToDismissValue {
171        self.settled
172    }
173
174    /// Returns the logical direction of the current offset.
175    pub fn dismiss_direction(&self) -> SwipeToDismissValue {
176        SwipeToDismissValue::from_position(self.position)
177    }
178
179    /// Returns the fraction of the width uncovered by the foreground.
180    pub fn progress(&self) -> f32 {
181        self.position.abs()
182    }
183
184    /// Returns the signed horizontal offset in window coordinates.
185    pub fn offset(&self) -> Pixels {
186        self.width * (self.position * self.options.sign())
187    }
188
189    /// Animates to an enabled dismissal direction. Returns whether it was accepted.
190    pub fn dismiss(
191        &mut self,
192        direction: SwipeToDismissValue,
193        window: &mut Window,
194        cx: &mut Context<Self>,
195    ) -> bool {
196        if direction == SwipeToDismissValue::Settled || !self.options.allows(direction) {
197            return false;
198        }
199        self.cancel_input(window, true);
200        self.move_to(direction, window, cx);
201        true
202    }
203
204    /// Animates the foreground back to its resting position.
205    pub fn reset(&mut self, window: &mut Window, cx: &mut Context<Self>) {
206        self.cancel_input(window, true);
207        self.move_to(SwipeToDismissValue::Settled, window, cx);
208    }
209
210    /// Moves immediately to an enabled anchor. Returns whether it was accepted.
211    pub fn snap_to(
212        &mut self,
213        value: SwipeToDismissValue,
214        window: &mut Window,
215        cx: &mut Context<Self>,
216    ) -> bool {
217        if !self.options.allows(value) {
218            return false;
219        }
220        let cancelled = self.cancel_input(window, true);
221        let settled = self.settle(value, window, cx);
222        if cancelled || settled {
223            window.refresh();
224        }
225        true
226    }
227
228    pub(crate) fn shows_foreground(&self) -> bool {
229        self.moving || self.settled == SwipeToDismissValue::Settled
230    }
231
232    pub(crate) fn is_dragging(&self) -> bool {
233        matches!(self.input, SwipeInput::Mouse { .. } | SwipeInput::Touch)
234    }
235
236    pub(super) fn move_to(
237        &mut self,
238        value: SwipeToDismissValue,
239        window: &mut Window,
240        cx: &mut Context<Self>,
241    ) {
242        if self.moving && self.target == value {
243            return;
244        }
245        let changed = if cx.reduce_motion() || self.position == value.position() {
246            self.settle(value, window, cx)
247        } else {
248            if !self.moving {
249                self.rebase_motion = true;
250            }
251            self.target = value;
252            self.moving = true;
253            cx.notify();
254            true
255        };
256        if changed {
257            window.refresh();
258        }
259    }
260
261    pub(super) fn settle(
262        &mut self,
263        value: SwipeToDismissValue,
264        window: &mut Window,
265        cx: &mut Context<Self>,
266    ) -> bool {
267        let changed = self.position != value.position() || self.target != value || self.moving;
268        self.position = value.position();
269        self.target = value;
270        self.moving = false;
271        self.rebase_motion = false;
272        if self.settled != value {
273            self.settled = value;
274            if value != SwipeToDismissValue::Settled {
275                if self
276                    .mount
277                    .as_ref()
278                    .is_some_and(|(_, focus)| focus.contains_focused(window, cx))
279                {
280                    window.blur(cx);
281                }
282                cx.emit(Dismissed(value));
283            }
284            cx.notify();
285            true
286        } else if changed {
287            cx.notify();
288            true
289        } else {
290            false
291        }
292    }
293
294    pub(super) fn sample_motion(
295        &mut self,
296        id: &ElementId,
297        window: &mut Window,
298        cx: &mut Context<Self>,
299    ) {
300        if !self.moving {
301            return;
302        }
303        let motion_id = (id.clone(), "swipe-offset");
304        if mem::take(&mut self.rebase_motion) {
305            animate(
306                motion_id.clone(),
307                self.position,
308                MotionSpec::Instant,
309                window,
310                cx,
311            );
312        }
313        let target = self.target.position();
314        let spec = current_material_theme(window, cx).motion.spec(
315            MotionKind::Spatial,
316            MotionSpeed::Fast,
317            cx.reduce_motion(),
318        );
319        let position = animate(motion_id, target, spec, window, cx);
320        if position == target {
321            self.settle(self.target, window, cx);
322        } else {
323            let position = position.clamp(-1., 1.);
324            if self.position != position {
325                self.position = position;
326                cx.notify();
327            }
328        }
329    }
330
331    pub(super) fn configure(
332        &mut self,
333        options: SwipeOptions,
334        mount: (EntityId, FocusHandle),
335        window: &mut Window,
336        cx: &mut Context<Self>,
337    ) {
338        self.mount = Some(mount);
339        let previous = mem::replace(&mut self.options, options);
340        if previous != options {
341            if !options.allows(self.target) || !options.allows(self.settled) {
342                self.cancel_input(window, true);
343                self.settle(SwipeToDismissValue::Settled, window, cx);
344            } else if !options.gestures_enabled
345                || previous.direction != options.direction
346                || !options.allows(self.dismiss_direction())
347            {
348                self.cancel_interaction(window, cx);
349            }
350            cx.notify();
351        }
352    }
353
354    pub(super) fn can_start(&self) -> bool {
355        self.options.gestures_enabled
356            && (self.options.start_to_end || self.options.end_to_start)
357            && self.width > px(0.)
358            && self.settled == SwipeToDismissValue::Settled
359            && !self.moving
360    }
361
362    pub(super) fn drag_to(&mut self, delta: Pixels, window: &mut Window, cx: &mut Context<Self>) {
363        let position = if self.width > px(0.) {
364            (delta / self.width * self.options.sign()).clamp(-1., 1.)
365        } else {
366            0.
367        };
368        let direction = SwipeToDismissValue::from_position(position);
369        let position = if self.options.allows(direction) {
370            position
371        } else {
372            0.
373        };
374        let threshold = self
375            .threshold
376            .as_ref()
377            .map_or(DEFAULT_THRESHOLD, |f| f(self.width));
378        let threshold = if f32::from(threshold).is_finite() {
379            threshold
380        } else {
381            DEFAULT_THRESHOLD
382        };
383        let threshold = threshold.clamp(px(0.), self.width);
384        let target = if self.width * position.abs() >= threshold {
385            SwipeToDismissValue::from_position(position)
386        } else {
387            SwipeToDismissValue::Settled
388        };
389        if self.position != position || self.target != target {
390            self.position = position;
391            self.target = target;
392            cx.notify();
393            window.refresh();
394        }
395    }
396
397    pub(super) fn cancel_input(&mut self, window: &mut Window, suppress_mouse_up: bool) -> bool {
398        match mem::take(&mut self.input) {
399            SwipeInput::Mouse { .. } => {
400                window.release_pointer();
401                if suppress_mouse_up {
402                    self.input = SwipeInput::SuppressMouseUp;
403                }
404                true
405            }
406            SwipeInput::Touch => true,
407            SwipeInput::SuppressMouseUp if suppress_mouse_up => {
408                self.input = SwipeInput::SuppressMouseUp;
409                false
410            }
411            _ => false,
412        }
413    }
414
415    pub(super) fn cancel_interaction(
416        &mut self,
417        window: &mut Window,
418        cx: &mut Context<Self>,
419    ) -> bool {
420        let cancelled = self.cancel_input(window, true);
421        if cancelled {
422            self.move_to(SwipeToDismissValue::Settled, window, cx);
423        }
424        cancelled
425    }
426
427    pub(super) fn release(&mut self, delta: Pixels, window: &mut Window, cx: &mut Context<Self>) {
428        self.drag_to(delta, window, cx);
429        self.cancel_input(window, false);
430        self.move_to(self.target, window, cx);
431    }
432}