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