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 IntoElement for SwipeContent {
581 type Element = Self;
582
583 fn into_element(self) -> Self {
584 self
585 }
586}
587
588impl Element for SwipeContent {
589 type RequestLayoutState = ();
590 type PrepaintState = (bool, Option<Hitbox>);
591
592 fn id(&self) -> Option<ElementId> {
593 None
594 }
595
596 fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
597 None
598 }
599
600 fn request_layout(
601 &mut self,
602 _: Option<&GlobalElementId>,
603 _: Option<&InspectorElementId>,
604 window: &mut Window,
605 cx: &mut App,
606 ) -> (LayoutId, ()) {
607 (self.content.request_layout(window, cx), ())
608 }
609
610 fn prepaint(
611 &mut self,
612 _: Option<&GlobalElementId>,
613 _: Option<&InspectorElementId>,
614 bounds: Bounds<Pixels>,
615 _: &mut (),
616 window: &mut Window,
617 cx: &mut App,
618 ) -> Self::PrepaintState {
619 let (offset, visible) = self
620 .state
621 .update(cx, |state, cx| {
622 if state.width != bounds.size.width {
623 state.width = bounds.size.width;
624 if state.position != 0. || state.moving {
625 cx.notify();
626 }
627 }
628 (state.offset(), state.shows_foreground())
629 })
630 .unwrap_or((px(0.), true));
631 if visible {
632 window.set_focus_handle(&self.focus, cx);
633 window.with_element_offset(point(offset, px(0.)), |window| {
634 self.content.prepaint(window, cx);
635 });
636 }
637 let hitbox = self.state.upgrade().and_then(|state| {
638 let state = state.read(cx);
639 (state.can_start() || !matches!(state.input, SwipeInput::None))
640 .then(|| window.insert_hitbox(bounds, HitboxBehavior::Normal))
641 });
642 (visible, hitbox)
643 }
644
645 fn paint(
646 &mut self,
647 _: Option<&GlobalElementId>,
648 _: Option<&InspectorElementId>,
649 _: Bounds<Pixels>,
650 _: &mut (),
651 (visible, hitbox): &mut Self::PrepaintState,
652 window: &mut Window,
653 cx: &mut App,
654 ) {
655 if *visible {
656 self.content.paint(window, cx);
657 }
658 if let Some(hitbox) = hitbox {
659 listen_for_swipes(self.state.clone(), hitbox.clone(), window);
660 }
661 }
662}
663
664fn listen_for_swipes(state: WeakEntity<SwipeToDismissState>, hitbox: Hitbox, window: &mut Window) {
665 window.on_mouse_event({
666 let state = state.clone();
667 let hitbox = hitbox.clone();
668 move |event: &MouseDownEvent, phase, window, cx| {
669 if phase.bubble() && event.button == MouseButton::Left && hitbox.is_hovered(window) {
670 let _ = state.update(cx, |state, _| {
671 if state.can_start()
672 && matches!(state.input, SwipeInput::None | SwipeInput::SuppressMouseUp)
673 {
674 state.input = SwipeInput::Pressed(event.position);
675 }
676 });
677 }
678 }
679 });
680 window.on_mouse_event({
681 let state = state.clone();
682 let hitbox = hitbox.clone();
683 move |event: &MouseMoveEvent, phase, window, cx| {
684 if !phase.bubble() {
685 return;
686 }
687 let _ = state.update(cx, |swipe, cx| {
688 if event.pressed_button != Some(MouseButton::Left) {
689 if !matches!(swipe.input, SwipeInput::Touch)
690 && swipe.cancel_input(window, false)
691 {
692 swipe.move_to(SwipeToDismissValue::Settled, window, cx);
693 }
694 return;
695 }
696 match swipe.input {
697 SwipeInput::Pressed(origin) => {
698 let delta = event.position - origin;
699 if delta.x.abs().max(delta.y.abs()) >= SWIPE_SLOP {
700 if swipe.options.can_start(delta)
701 && !cx.has_active_drag()
702 && window.captured_hitbox().is_none()
703 {
704 window.capture_pointer(hitbox.id);
705 swipe.input = watch_mouse_swipe(state.clone(), origin, window, cx);
706 swipe.drag_to(delta.x, window, cx);
707 cx.stop_propagation();
708 } else {
709 swipe.input = SwipeInput::None;
710 }
711 }
712 }
713 SwipeInput::Mouse { origin, .. } => {
714 swipe.drag_to(event.position.x - origin.x, window, cx);
715 cx.stop_propagation();
716 }
717 SwipeInput::SuppressMouseUp => cx.stop_propagation(),
718 _ => {}
719 }
720 });
721 }
722 });
723 window.on_mouse_event({
724 let state = state.clone();
725 move |event: &MouseUpEvent, phase, window, cx| {
726 if !phase.bubble() || event.button != MouseButton::Left {
727 return;
728 }
729 let _ = state.update(cx, |state, cx| match state.input {
730 SwipeInput::Mouse { origin, .. } => {
731 state.release(event.position.x - origin.x, window, cx);
732 cx.stop_propagation();
733 }
734 SwipeInput::SuppressMouseUp => {
735 state.input = SwipeInput::None;
736 cx.stop_propagation();
737 }
738 SwipeInput::Pressed(_) => state.input = SwipeInput::None,
739 _ => {}
740 });
741 }
742 });
743 window.on_mouse_event(move |event: &TouchDragEvent, phase, window, cx| {
744 if !phase.bubble() {
745 return;
746 }
747 let _ = state.update(cx, |state, cx| {
748 let delta = event.position - event.start_position;
749 match event.phase {
750 TouchPhase::Started
751 if hitbox.is_hovered_at(event.start_position, window)
752 && state.can_start()
753 && matches!(state.input, SwipeInput::None)
754 && state.options.can_start(delta) =>
755 {
756 state.input = SwipeInput::Touch;
757 state.drag_to(delta.x, window, cx);
758 window.prevent_default();
759 cx.stop_propagation();
760 }
761 TouchPhase::Moved | TouchPhase::Ended
762 if matches!(state.input, SwipeInput::Touch) =>
763 {
764 if event.phase == TouchPhase::Ended {
765 state.release(delta.x, window, cx);
766 } else {
767 state.drag_to(delta.x, window, cx);
768 }
769 cx.stop_propagation();
770 }
771 TouchPhase::Cancelled if matches!(state.input, SwipeInput::Touch) => {
772 state.cancel_interaction(window, cx);
773 cx.stop_propagation();
774 }
775 _ => {}
776 }
777 });
778 });
779}
780
781fn watch_mouse_swipe(
782 state: WeakEntity<SwipeToDismissState>,
783 origin: Point<Pixels>,
784 window: &Window,
785 cx: &mut App,
786) -> SwipeInput {
787 let window_id = window.window_handle().window_id();
788 let escape = cx.intercept_keystrokes({
789 let state = state.clone();
790 move |event, window, cx| {
791 if event.keystroke.key == "escape" && window.window_handle().window_id() == window_id {
792 let cancelled = state.update(cx, |state, cx| state.cancel_interaction(window, cx));
793 if cancelled.unwrap_or(false) {
794 cx.stop_propagation();
795 }
796 }
797 }
798 });
799 let capture = DragCapture::watch_pointer(window, cx, move |window, cx| {
800 let _ = state.update(cx, |state, cx| {
801 state.cancel_interaction(window, cx);
802 });
803 });
804 SwipeInput::Mouse {
805 origin,
806 _capture: capture,
807 _escape: escape,
808 }
809}