1use std::{cell::RefCell, mem, rc::Rc};
2
3use gpui::InteractiveElement as _;
4use gpui::{
5 AnyElement, App, Bounds, Context, Element, ElementId, Entity, EntityId, EventEmitter,
6 FocusHandle, GlobalElementId, Hitbox, HitboxBehavior, InspectorElementId, IntoElement,
7 LayoutId, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, ParentElement, Pixels,
8 Point, RenderOnce, Styled, Subscription, TouchDragEvent, TouchPhase, WeakEntity, Window, div,
9 point, px,
10};
11use gpui_base::TestSupportExt as _;
12use gpui_material_foundation::{DragCapture, animate, current_material_theme};
13use gpui_material_theme::{Direction, MotionKind, MotionSpec, MotionSpeed};
14
15const DEFAULT_THRESHOLD: Pixels = px(56.);
16const SWIPE_SLOP: Pixels = px(6.);
17
18#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
20pub enum SwipeToDismissValue {
21 #[default]
23 Settled,
24 StartToEnd,
26 EndToStart,
28}
29
30impl SwipeToDismissValue {
31 fn position(self) -> f32 {
32 match self {
33 Self::Settled => 0.,
34 Self::StartToEnd => 1.,
35 Self::EndToStart => -1.,
36 }
37 }
38
39 fn from_position(position: f32) -> Self {
40 if position > 0. {
41 Self::StartToEnd
42 } else if position < 0. {
43 Self::EndToStart
44 } else {
45 Self::Settled
46 }
47 }
48}
49
50#[derive(Clone, Copy, PartialEq, Eq)]
51struct SwipeOptions {
52 direction: Direction,
53 start_to_end: bool,
54 end_to_start: bool,
55 gestures_enabled: bool,
56}
57
58impl Default for SwipeOptions {
59 fn default() -> Self {
60 Self {
61 direction: Direction::Ltr,
62 start_to_end: true,
63 end_to_start: true,
64 gestures_enabled: true,
65 }
66 }
67}
68
69impl SwipeOptions {
70 fn allows(self, value: SwipeToDismissValue) -> bool {
71 match value {
72 SwipeToDismissValue::Settled => true,
73 SwipeToDismissValue::StartToEnd => self.start_to_end,
74 SwipeToDismissValue::EndToStart => self.end_to_start,
75 }
76 }
77
78 fn sign(self) -> f32 {
79 match self.direction {
80 Direction::Ltr => 1.,
81 Direction::Rtl => -1.,
82 }
83 }
84
85 fn can_start(self, delta: Point<Pixels>) -> bool {
86 delta.x.abs() >= SWIPE_SLOP
87 && delta.x.abs() > delta.y.abs()
88 && self.allows(SwipeToDismissValue::from_position(
89 f32::from(delta.x) * self.sign(),
90 ))
91 }
92}
93
94#[derive(Default)]
95enum SwipeInput {
96 #[default]
97 None,
98 Pressed(Point<Pixels>),
99 Mouse {
100 origin: Point<Pixels>,
101 _capture: DragCapture,
102 _escape: Subscription,
103 },
104 Touch,
105 SuppressMouseUp,
106}
107
108struct Dismissed(SwipeToDismissValue);
109
110pub struct SwipeToDismissState {
112 width: Pixels,
113 position: f32,
114 target: SwipeToDismissValue,
115 settled: SwipeToDismissValue,
116 moving: bool,
117 rebase_motion: bool,
118 options: SwipeOptions,
119 threshold: Option<Box<dyn Fn(Pixels) -> Pixels>>,
120 input: SwipeInput,
121 mount: Option<(EntityId, FocusHandle)>,
122}
123
124impl Default for SwipeToDismissState {
125 fn default() -> Self {
126 Self {
127 width: px(0.),
128 position: 0.,
129 target: SwipeToDismissValue::Settled,
130 settled: SwipeToDismissValue::Settled,
131 moving: false,
132 rebase_motion: false,
133 options: SwipeOptions::default(),
134 threshold: None,
135 input: SwipeInput::None,
136 mount: None,
137 }
138 }
139}
140
141impl EventEmitter<Dismissed> for SwipeToDismissState {}
142
143impl SwipeToDismissState {
144 pub fn new() -> Self {
146 Self::default()
147 }
148
149 pub fn initial_value(mut self, value: SwipeToDismissValue) -> Self {
151 self.position = value.position();
152 self.target = value;
153 self.settled = value;
154 self
155 }
156
157 pub fn positional_threshold(mut self, threshold: impl Fn(Pixels) -> Pixels + 'static) -> Self {
160 self.threshold = Some(Box::new(threshold));
161 self
162 }
163
164 pub fn current_value(&self) -> SwipeToDismissValue {
166 SwipeToDismissValue::from_position(self.position.round())
167 }
168
169 pub fn target_value(&self) -> SwipeToDismissValue {
171 self.target
172 }
173
174 pub fn settled_value(&self) -> SwipeToDismissValue {
176 self.settled
177 }
178
179 pub fn dismiss_direction(&self) -> SwipeToDismissValue {
181 SwipeToDismissValue::from_position(self.position)
182 }
183
184 pub fn progress(&self) -> f32 {
186 self.position.abs()
187 }
188
189 pub fn offset(&self) -> Pixels {
191 self.width * (self.position * self.options.sign())
192 }
193
194 pub fn dismiss(
196 &mut self,
197 direction: SwipeToDismissValue,
198 window: &mut Window,
199 cx: &mut Context<Self>,
200 ) -> bool {
201 if direction == SwipeToDismissValue::Settled || !self.options.allows(direction) {
202 return false;
203 }
204 self.cancel_input(window, true);
205 self.move_to(direction, window, cx);
206 true
207 }
208
209 pub fn reset(&mut self, window: &mut Window, cx: &mut Context<Self>) {
211 self.cancel_input(window, true);
212 self.move_to(SwipeToDismissValue::Settled, window, cx);
213 }
214
215 pub fn snap_to(
217 &mut self,
218 value: SwipeToDismissValue,
219 window: &mut Window,
220 cx: &mut Context<Self>,
221 ) -> bool {
222 if !self.options.allows(value) {
223 return false;
224 }
225 let cancelled = self.cancel_input(window, true);
226 let settled = self.settle(value, window, cx);
227 if cancelled || settled {
228 window.refresh();
229 }
230 true
231 }
232
233 pub(crate) fn shows_foreground(&self) -> bool {
234 self.moving || self.settled == SwipeToDismissValue::Settled
235 }
236
237 pub(crate) fn is_dragging(&self) -> bool {
238 matches!(self.input, SwipeInput::Mouse { .. } | SwipeInput::Touch)
239 }
240
241 fn move_to(&mut self, value: SwipeToDismissValue, window: &mut Window, cx: &mut Context<Self>) {
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 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 fn sample_motion(&mut self, id: &ElementId, window: &mut Window, cx: &mut Context<Self>) {
295 if !self.moving {
296 return;
297 }
298 let motion_id = (id.clone(), "swipe-offset");
299 if mem::take(&mut self.rebase_motion) {
300 animate(
301 motion_id.clone(),
302 self.position,
303 MotionSpec::Instant,
304 window,
305 cx,
306 );
307 }
308 let target = self.target.position();
309 let spec = current_material_theme(window, cx).motion.spec(
310 MotionKind::Spatial,
311 MotionSpeed::Fast,
312 cx.reduce_motion(),
313 );
314 let position = animate(motion_id, target, spec, window, cx);
315 if position == target {
316 self.settle(self.target, window, cx);
317 } else {
318 let position = position.clamp(-1., 1.);
319 if self.position != position {
320 self.position = position;
321 cx.notify();
322 }
323 }
324 }
325
326 fn configure(
327 &mut self,
328 options: SwipeOptions,
329 mount: (EntityId, FocusHandle),
330 window: &mut Window,
331 cx: &mut Context<Self>,
332 ) {
333 self.mount = Some(mount);
334 let previous = mem::replace(&mut self.options, options);
335 if previous != options {
336 if !options.allows(self.target) || !options.allows(self.settled) {
337 self.cancel_input(window, true);
338 self.settle(SwipeToDismissValue::Settled, window, cx);
339 } else if !options.gestures_enabled
340 || previous.direction != options.direction
341 || !options.allows(self.dismiss_direction())
342 {
343 self.cancel_interaction(window, cx);
344 }
345 cx.notify();
346 }
347 }
348
349 fn can_start(&self) -> bool {
350 self.options.gestures_enabled
351 && (self.options.start_to_end || self.options.end_to_start)
352 && self.width > px(0.)
353 && self.settled == SwipeToDismissValue::Settled
354 && !self.moving
355 }
356
357 fn drag_to(&mut self, delta: Pixels, window: &mut Window, cx: &mut Context<Self>) {
358 let position = if self.width > px(0.) {
359 (delta / self.width * self.options.sign()).clamp(-1., 1.)
360 } else {
361 0.
362 };
363 let direction = SwipeToDismissValue::from_position(position);
364 let position = if self.options.allows(direction) {
365 position
366 } else {
367 0.
368 };
369 let threshold = self
370 .threshold
371 .as_ref()
372 .map_or(DEFAULT_THRESHOLD, |f| f(self.width));
373 let threshold = if f32::from(threshold).is_finite() {
374 threshold
375 } else {
376 DEFAULT_THRESHOLD
377 };
378 let threshold = threshold.clamp(px(0.), self.width);
379 let target = if self.width * position.abs() >= threshold {
380 SwipeToDismissValue::from_position(position)
381 } else {
382 SwipeToDismissValue::Settled
383 };
384 if self.position != position || self.target != target {
385 self.position = position;
386 self.target = target;
387 cx.notify();
388 window.refresh();
389 }
390 }
391
392 fn cancel_input(&mut self, window: &mut Window, suppress_mouse_up: bool) -> bool {
393 match mem::take(&mut self.input) {
394 SwipeInput::Mouse { .. } => {
395 window.release_pointer();
396 if suppress_mouse_up {
397 self.input = SwipeInput::SuppressMouseUp;
398 }
399 true
400 }
401 SwipeInput::Touch => true,
402 SwipeInput::SuppressMouseUp if suppress_mouse_up => {
403 self.input = SwipeInput::SuppressMouseUp;
404 false
405 }
406 _ => false,
407 }
408 }
409
410 fn cancel_interaction(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
411 let cancelled = self.cancel_input(window, true);
412 if cancelled {
413 self.move_to(SwipeToDismissValue::Settled, window, cx);
414 }
415 cancelled
416 }
417
418 fn release(&mut self, delta: Pixels, window: &mut Window, cx: &mut Context<Self>) {
419 self.drag_to(delta, window, cx);
420 self.cancel_input(window, false);
421 self.move_to(self.target, window, cx);
422 }
423}
424
425type OnDismiss = Rc<dyn Fn(SwipeToDismissValue, &mut Window, &mut App)>;
426
427struct SwipeMount {
428 callback: Rc<RefCell<Option<OnDismiss>>>,
429 focus: FocusHandle,
430 _dismiss: Subscription,
431 _activation: Subscription,
432}
433
434#[derive(IntoElement)]
437pub struct SwipeToDismiss {
438 id: ElementId,
439 state: Entity<SwipeToDismissState>,
440 content: AnyElement,
441 background: Option<AnyElement>,
442 options: SwipeOptions,
443 on_dismiss: Option<OnDismiss>,
444}
445
446impl SwipeToDismiss {
447 pub fn new(
449 id: impl Into<ElementId>,
450 state: &Entity<SwipeToDismissState>,
451 content: impl IntoElement,
452 ) -> Self {
453 Self {
454 id: id.into(),
455 state: state.clone(),
456 content: content.into_any_element(),
457 background: None,
458 options: SwipeOptions::default(),
459 on_dismiss: None,
460 }
461 }
462
463 pub fn background(mut self, background: impl IntoElement) -> Self {
465 self.background = Some(background.into_any_element());
466 self
467 }
468
469 pub fn enable_start_to_end(mut self, enabled: bool) -> Self {
471 self.options.start_to_end = enabled;
472 self
473 }
474
475 pub fn enable_end_to_start(mut self, enabled: bool) -> Self {
477 self.options.end_to_start = enabled;
478 self
479 }
480
481 pub fn gestures_enabled(mut self, enabled: bool) -> Self {
483 self.options.gestures_enabled = enabled;
484 self
485 }
486
487 pub fn on_dismiss(
489 mut self,
490 on_dismiss: impl Fn(SwipeToDismissValue, &mut Window, &mut App) + 'static,
491 ) -> Self {
492 self.on_dismiss = Some(Rc::new(on_dismiss));
493 self
494 }
495}
496
497impl RenderOnce for SwipeToDismiss {
498 fn render(mut self, window: &mut Window, cx: &mut App) -> impl IntoElement {
499 self.options.direction = current_material_theme(window, cx).layout.direction;
500 let mount = window.with_element_namespace((self.id.clone(), "material-swipe"), |window| {
501 window.use_keyed_state(("mount", self.state.entity_id()), cx, |window, cx| {
502 let callback = Rc::new(RefCell::new(None::<OnDismiss>));
503 let dismiss = window.subscribe(&self.state, cx, {
504 let callback = callback.clone();
505 move |_, event: &Dismissed, window, cx| {
506 let callback = callback.borrow().clone();
507 if let Some(callback) = callback {
508 callback(event.0, window, cx);
509 }
510 }
511 });
512 let state = self.state.downgrade();
513 let activation = cx.observe_window_activation(window, {
514 let state = state.clone();
515 move |_, window, cx| {
516 if !window.is_window_active() {
517 let _ = state.update(cx, |state, cx| {
518 state.cancel_interaction(window, cx);
519 });
520 }
521 }
522 });
523 let handle = window.window_handle();
524 let mount = cx.entity_id();
525 cx.on_release(move |_: &mut SwipeMount, cx| {
526 let state = state.clone();
527 cx.defer(move |cx| {
528 let _ = handle.update(cx, |_, window, cx| {
529 let _ = state.update(cx, |state, cx| {
530 if state.mount.as_ref().is_some_and(|(id, _)| *id == mount) {
531 state.mount = None;
532 state.cancel_input(window, false);
533 let settled = state.settled;
534 state.settle(settled, window, cx);
535 }
536 });
537 });
538 });
539 })
540 .detach();
541 SwipeMount {
542 callback,
543 focus: cx.focus_handle().tab_stop(false),
544 _dismiss: dismiss,
545 _activation: activation,
546 }
547 })
548 });
549 let mounted = mount.read(cx);
550 mounted.callback.replace(self.on_dismiss);
551 let focus = mounted.focus.clone();
552 self.state.update(cx, |state, cx| {
553 state.configure(self.options, (mount.entity_id(), focus.clone()), window, cx);
554 state.sample_motion(&self.id, window, cx);
555 });
556 div()
557 .id(self.id)
558 .test_support()
559 .overflow_hidden()
560 .children(
561 self.background
562 .map(|background| div().absolute().inset_0().child(background)),
563 )
564 .child(SwipeContent {
565 content: self.content,
566 state: self.state.downgrade(),
567 focus,
568 })
569 }
570}
571
572struct SwipeContent {
575 content: AnyElement,
576 state: WeakEntity<SwipeToDismissState>,
577 focus: FocusHandle,
578}
579
580impl Element for SwipeContent {
581 type RequestLayoutState = ();
582 type PrepaintState = (bool, Option<Hitbox>);
583
584 fn id(&self) -> Option<ElementId> {
585 None
586 }
587
588 fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
589 None
590 }
591
592 fn request_layout(
593 &mut self,
594 _: Option<&GlobalElementId>,
595 _: Option<&InspectorElementId>,
596 window: &mut Window,
597 cx: &mut App,
598 ) -> (LayoutId, ()) {
599 (self.content.request_layout(window, cx), ())
600 }
601
602 fn prepaint(
603 &mut self,
604 _: Option<&GlobalElementId>,
605 _: Option<&InspectorElementId>,
606 bounds: Bounds<Pixels>,
607 _: &mut (),
608 window: &mut Window,
609 cx: &mut App,
610 ) -> Self::PrepaintState {
611 let (offset, visible) = self
612 .state
613 .update(cx, |state, cx| {
614 if state.width != bounds.size.width {
615 state.width = bounds.size.width;
616 if state.position != 0. || state.moving {
617 cx.notify();
618 }
619 }
620 (state.offset(), state.shows_foreground())
621 })
622 .unwrap_or((px(0.), true));
623 if visible {
624 window.set_focus_handle(&self.focus, cx);
625 window.with_element_offset(point(offset, px(0.)), |window| {
626 self.content.prepaint(window, cx);
627 });
628 }
629 let hitbox = self.state.upgrade().and_then(|state| {
630 let state = state.read(cx);
631 (state.can_start() || !matches!(state.input, SwipeInput::None))
632 .then(|| window.insert_hitbox(bounds, HitboxBehavior::Normal))
633 });
634 (visible, hitbox)
635 }
636
637 fn paint(
638 &mut self,
639 _: Option<&GlobalElementId>,
640 _: Option<&InspectorElementId>,
641 _: Bounds<Pixels>,
642 _: &mut (),
643 (visible, hitbox): &mut Self::PrepaintState,
644 window: &mut Window,
645 cx: &mut App,
646 ) {
647 if *visible {
648 self.content.paint(window, cx);
649 }
650 if let Some(hitbox) = hitbox {
651 listen_for_swipes(self.state.clone(), hitbox.clone(), window);
652 }
653 }
654}
655
656fn listen_for_swipes(state: WeakEntity<SwipeToDismissState>, hitbox: Hitbox, window: &mut Window) {
657 window.on_mouse_event({
658 let state = state.clone();
659 let hitbox = hitbox.clone();
660 move |event: &MouseDownEvent, phase, window, cx| {
661 if phase.bubble() && event.button == MouseButton::Left && hitbox.is_hovered(window) {
662 let _ = state.update(cx, |state, _| {
663 if state.can_start()
664 && matches!(state.input, SwipeInput::None | SwipeInput::SuppressMouseUp)
665 {
666 state.input = SwipeInput::Pressed(event.position);
667 }
668 });
669 }
670 }
671 });
672 window.on_mouse_event({
673 let state = state.clone();
674 let hitbox = hitbox.clone();
675 move |event: &MouseMoveEvent, phase, window, cx| {
676 if !phase.bubble() {
677 return;
678 }
679 let _ = state.update(cx, |swipe, cx| {
680 if event.pressed_button != Some(MouseButton::Left) {
681 if !matches!(swipe.input, SwipeInput::Touch)
682 && swipe.cancel_input(window, false)
683 {
684 swipe.move_to(SwipeToDismissValue::Settled, window, cx);
685 }
686 return;
687 }
688 match swipe.input {
689 SwipeInput::Pressed(origin) => {
690 let delta = event.position - origin;
691 if delta.x.abs().max(delta.y.abs()) >= SWIPE_SLOP {
692 if swipe.options.can_start(delta)
693 && !cx.has_active_drag()
694 && window.captured_hitbox().is_none()
695 {
696 window.capture_pointer(hitbox.id);
697 swipe.input = watch_mouse_swipe(state.clone(), origin, window, cx);
698 swipe.drag_to(delta.x, window, cx);
699 cx.stop_propagation();
700 } else {
701 swipe.input = SwipeInput::None;
702 }
703 }
704 }
705 SwipeInput::Mouse { origin, .. } => {
706 swipe.drag_to(event.position.x - origin.x, window, cx);
707 cx.stop_propagation();
708 }
709 SwipeInput::SuppressMouseUp => cx.stop_propagation(),
710 _ => {}
711 }
712 });
713 }
714 });
715 window.on_mouse_event({
716 let state = state.clone();
717 move |event: &MouseUpEvent, phase, window, cx| {
718 if !phase.bubble() || event.button != MouseButton::Left {
719 return;
720 }
721 let _ = state.update(cx, |state, cx| match state.input {
722 SwipeInput::Mouse { origin, .. } => {
723 state.release(event.position.x - origin.x, window, cx);
724 cx.stop_propagation();
725 }
726 SwipeInput::SuppressMouseUp => {
727 state.input = SwipeInput::None;
728 cx.stop_propagation();
729 }
730 SwipeInput::Pressed(_) => state.input = SwipeInput::None,
731 _ => {}
732 });
733 }
734 });
735 window.on_mouse_event(move |event: &TouchDragEvent, phase, window, cx| {
736 if !phase.bubble() {
737 return;
738 }
739 let _ = state.update(cx, |state, cx| {
740 let delta = event.position - event.start_position;
741 match event.phase {
742 TouchPhase::Started
743 if hitbox.is_hovered_at(event.start_position, window)
744 && state.can_start()
745 && matches!(state.input, SwipeInput::None)
746 && state.options.can_start(delta) =>
747 {
748 state.input = SwipeInput::Touch;
749 state.drag_to(delta.x, window, cx);
750 window.prevent_default();
751 cx.stop_propagation();
752 }
753 TouchPhase::Moved | TouchPhase::Ended
754 if matches!(state.input, SwipeInput::Touch) =>
755 {
756 if event.phase == TouchPhase::Ended {
757 state.release(delta.x, window, cx);
758 } else {
759 state.drag_to(delta.x, window, cx);
760 }
761 cx.stop_propagation();
762 }
763 TouchPhase::Cancelled if matches!(state.input, SwipeInput::Touch) => {
764 state.cancel_interaction(window, cx);
765 cx.stop_propagation();
766 }
767 _ => {}
768 }
769 });
770 });
771}
772
773fn watch_mouse_swipe(
774 state: WeakEntity<SwipeToDismissState>,
775 origin: Point<Pixels>,
776 window: &Window,
777 cx: &mut App,
778) -> SwipeInput {
779 let window_id = window.window_handle().window_id();
780 let escape = cx.intercept_keystrokes({
781 let state = state.clone();
782 move |event, window, cx| {
783 if event.keystroke.key == "escape" && window.window_handle().window_id() == window_id {
784 let cancelled = state.update(cx, |state, cx| state.cancel_interaction(window, cx));
785 if cancelled.unwrap_or(false) {
786 cx.stop_propagation();
787 }
788 }
789 }
790 });
791 let capture = DragCapture::watch_pointer(window, cx, move |window, cx| {
792 let _ = state.update(cx, |state, cx| {
793 state.cancel_interaction(window, cx);
794 });
795 });
796 SwipeInput::Mouse {
797 origin,
798 _capture: capture,
799 _escape: escape,
800 }
801}