Skip to main content

gpui_material_components/
swipe_to_dismiss.rs

1mod element;
2mod state;
3
4use std::{cell::RefCell, rc::Rc};
5
6use gpui::InteractiveElement as _;
7use gpui::{
8    AnyElement, App, ElementId, Entity, FocusHandle, IntoElement, ParentElement, RenderOnce,
9    Styled, Subscription, Window, div,
10};
11use gpui_base::TestSupportExt as _;
12use gpui_material_foundation::current_material_theme;
13
14use element::SwipeContent;
15use state::{Dismissed, SwipeOptions};
16
17pub use state::{SwipeToDismissState, SwipeToDismissValue};
18
19type OnDismiss = Rc<dyn Fn(SwipeToDismissValue, &mut Window, &mut App)>;
20
21struct SwipeMount {
22    callback: Rc<RefCell<Option<OnDismiss>>>,
23    focus: FocusHandle,
24    _dismiss: Subscription,
25    _activation: Subscription,
26}
27
28/// A foreground and background with logical horizontal swipe gestures.
29/// The caller owns the content, action commands, and resulting data changes.
30#[derive(IntoElement)]
31pub struct SwipeToDismiss {
32    id: ElementId,
33    state: Entity<SwipeToDismissState>,
34    content: AnyElement,
35    background: Option<AnyElement>,
36    options: SwipeOptions,
37    on_dismiss: Option<OnDismiss>,
38}
39
40impl SwipeToDismiss {
41    /// Creates a swipe-to-dismiss container wrapping `content` and bound to `state`.
42    pub fn new(
43        id: impl Into<ElementId>,
44        state: &Entity<SwipeToDismissState>,
45        content: impl IntoElement,
46    ) -> Self {
47        Self {
48            id: id.into(),
49            state: state.clone(),
50            content: content.into_any_element(),
51            background: None,
52            options: SwipeOptions::default(),
53            on_dismiss: None,
54        }
55    }
56
57    /// Sets the background element revealed behind the foreground while swiping.
58    pub fn background(mut self, background: impl IntoElement) -> Self {
59        self.background = Some(background.into_any_element());
60        self
61    }
62
63    /// Enables or disables start-to-end dismissal gestures and programmatic dismissal. Defaults to `true`.
64    pub fn enable_start_to_end(mut self, enabled: bool) -> Self {
65        self.options.start_to_end = enabled;
66        self
67    }
68
69    /// Enables or disables end-to-start dismissal gestures and programmatic dismissal. Defaults to `true`.
70    pub fn enable_end_to_start(mut self, enabled: bool) -> Self {
71        self.options.end_to_start = enabled;
72        self
73    }
74
75    /// Enables direct gestures. Programmatic and accessible commands stay available.
76    pub fn gestures_enabled(mut self, enabled: bool) -> Self {
77        self.options.gestures_enabled = enabled;
78        self
79    }
80
81    /// Runs once when the state settles at a new dismissal anchor.
82    pub fn on_dismiss(
83        mut self,
84        on_dismiss: impl Fn(SwipeToDismissValue, &mut Window, &mut App) + 'static,
85    ) -> Self {
86        self.on_dismiss = Some(Rc::new(on_dismiss));
87        self
88    }
89}
90
91impl RenderOnce for SwipeToDismiss {
92    fn render(mut self, window: &mut Window, cx: &mut App) -> impl IntoElement {
93        self.options.direction = current_material_theme(window, cx).layout.direction;
94        let mount = window.with_element_namespace((self.id.clone(), "material-swipe"), |window| {
95            window.use_keyed_state(("mount", self.state.entity_id()), cx, |window, cx| {
96                let callback = Rc::new(RefCell::new(None::<OnDismiss>));
97                let dismiss = window.subscribe(&self.state, cx, {
98                    let callback = callback.clone();
99                    move |_, event: &Dismissed, window, cx| {
100                        let callback = callback.borrow().clone();
101                        if let Some(callback) = callback {
102                            callback(event.0, window, cx);
103                        }
104                    }
105                });
106                let state = self.state.downgrade();
107                let activation = cx.observe_window_activation(window, {
108                    let state = state.clone();
109                    move |_, window, cx| {
110                        if !window.is_window_active() {
111                            let _ = state.update(cx, |state, cx| {
112                                state.cancel_interaction(window, cx);
113                            });
114                        }
115                    }
116                });
117                let handle = window.window_handle();
118                let mount = cx.entity_id();
119                cx.on_release(move |_: &mut SwipeMount, cx| {
120                    let state = state.clone();
121                    cx.defer(move |cx| {
122                        let _ = handle.update(cx, |_, window, cx| {
123                            let _ = state.update(cx, |state, cx| {
124                                if state.mount.as_ref().is_some_and(|(id, _)| *id == mount) {
125                                    state.mount = None;
126                                    state.cancel_input(window, false);
127                                    let settled = state.settled;
128                                    state.settle(settled, window, cx);
129                                }
130                            });
131                        });
132                    });
133                })
134                .detach();
135                SwipeMount {
136                    callback,
137                    focus: cx.focus_handle().tab_stop(false),
138                    _dismiss: dismiss,
139                    _activation: activation,
140                }
141            })
142        });
143        let mounted = mount.read(cx);
144        mounted.callback.replace(self.on_dismiss);
145        let focus = mounted.focus.clone();
146        self.state.update(cx, |state, cx| {
147            state.configure(self.options, (mount.entity_id(), focus.clone()), window, cx);
148            state.sample_motion(&self.id, window, cx);
149        });
150        div()
151            .id(self.id)
152            .test_support()
153            .overflow_hidden()
154            .children(
155                self.background
156                    .map(|background| div().absolute().inset_0().child(background)),
157            )
158            .child(SwipeContent {
159                content: self.content,
160                state: self.state.downgrade(),
161                focus,
162            })
163    }
164}