Skip to main content

gpui_material_components/overlay/dialog/
state.rs

1use gpui::{
2    AnyWindowHandle, App, Context, Entity, FocusHandle, IntoElement, ParentElement, Render,
3    ScrollHandle, Styled, Subscription, WeakEntity, Window, div,
4};
5use gpui_base::active_focus_trap;
6
7use super::{Dialog, DialogCloseReason, ModalClosed, ModalDismissRequest};
8
9pub(super) struct NativeDialog {
10    pub(super) parent: AnyWindowHandle,
11    pub(super) child: AnyWindowHandle,
12    pub(super) _closed: Subscription,
13}
14
15/// Retains a dialog's visibility and focus scope across renders.
16pub struct DialogState {
17    pub(in crate::overlay) focus: FocusHandle,
18    pub(super) previous: Option<FocusHandle>,
19    pub(super) cancel_focus: FocusHandle,
20    pub(super) confirm_focus: FocusHandle,
21    pub(super) open: bool,
22    generation: u64,
23    pub(super) last_close_reason: Option<DialogCloseReason>,
24    pub(super) native: Option<NativeDialog>,
25    pub(in crate::overlay) scroll: ScrollHandle,
26}
27
28impl DialogState {
29    /// Creates a closed dialog state with freshly allocated focus and scroll handles.
30    pub fn new(cx: &mut Context<Self>) -> Self {
31        Self {
32            focus: cx.focus_handle(),
33            previous: None,
34            cancel_focus: cx.focus_handle(),
35            confirm_focus: cx.focus_handle(),
36            open: false,
37            generation: 0,
38            last_close_reason: None,
39            native: None,
40            scroll: ScrollHandle::new(),
41        }
42    }
43
44    /// Returns whether the dialog or sheet is currently open.
45    pub fn is_open(&self) -> bool {
46        self.open
47    }
48
49    /// Returns the most recent accepted close, including programmatic closes.
50    pub fn last_close_reason(&self) -> Option<DialogCloseReason> {
51        self.last_close_reason
52    }
53
54    /// Returns the modal container's retained focus handle.
55    pub fn focus_handle(&self) -> &FocusHandle {
56        &self.focus
57    }
58
59    /// Returns the retained scroll handle bound to the dialog or sheet body.
60    pub fn scroll_handle(&self) -> &ScrollHandle {
61        &self.scroll
62    }
63
64    pub(super) fn begin(
65        &mut self,
66        previous: Option<FocusHandle>,
67        window: &mut Window,
68        cx: &mut Context<Self>,
69    ) {
70        self.previous = previous;
71        self.open = true;
72        self.generation = self.generation.wrapping_add(1);
73        self.focus.focus(window, cx);
74        cx.notify();
75    }
76
77    /// Focuses the modal container. A caller can then focus a child editor.
78    pub fn open(&mut self, window: &mut Window, cx: &mut Context<Self>) {
79        if !self.open {
80            self.begin(window.focused(cx), window, cx);
81        }
82    }
83
84    /// Closes the dialog and restores its previous focus if it still owns focus.
85    /// A programmatic close updates the reason without firing the user close callback.
86    pub fn close(&mut self, window: &mut Window, cx: &mut Context<Self>) {
87        self.finish(DialogCloseReason::Programmatic, window, cx);
88    }
89
90    fn finish(&mut self, reason: DialogCloseReason, window: &mut Window, cx: &mut Context<Self>) {
91        if !self.open {
92            return;
93        }
94        self.open = false;
95        self.last_close_reason = Some(reason);
96        let previous = self.previous.take();
97        if let Some(native) = self.native.take() {
98            if reason != DialogCloseReason::WindowClose {
99                if native.child.window_id() == window.window_handle().window_id() {
100                    window.remove_window();
101                } else {
102                    native
103                        .child
104                        .update(cx, |_, window, _| window.remove_window())
105                        .ok();
106                }
107            }
108            restore_parent(native.parent, previous, cx);
109        } else if self.focus.contains_focused(window, cx) || self.focus.is_focused(window) {
110            if let Some(previous) = previous {
111                previous.focus(window, cx);
112            } else {
113                window.blur(cx);
114            }
115        }
116        cx.notify();
117    }
118}
119
120pub(super) fn restore_parent(parent: AnyWindowHandle, previous: Option<FocusHandle>, cx: &mut App) {
121    if let Some(previous) = previous {
122        cx.defer(move |cx| {
123            parent
124                .update(cx, |_, window, cx| {
125                    if window.focused(cx).is_none() {
126                        previous.focus(window, cx);
127                    }
128                })
129                .ok();
130        });
131    }
132}
133
134#[derive(Clone)]
135pub(in crate::overlay) struct ModalSession {
136    state: WeakEntity<DialogState>,
137    generation: u64,
138    dismiss_request: Option<ModalDismissRequest>,
139    on_close: Option<ModalClosed>,
140}
141
142impl ModalSession {
143    pub(in crate::overlay) fn new(
144        state: &Entity<DialogState>,
145        dismiss_request: Option<ModalDismissRequest>,
146        on_close: Option<ModalClosed>,
147        cx: &App,
148    ) -> Self {
149        Self {
150            state: state.downgrade(),
151            generation: state.read(cx).generation,
152            dismiss_request,
153            on_close,
154        }
155    }
156
157    pub(super) fn current(&self, window: &Window, cx: &App) -> bool {
158        self.state.upgrade().is_some_and(|state| {
159            let dialog = state.read(cx);
160            dialog.open
161                && dialog.generation == self.generation
162                && dialog.focus.contains_focused(window, cx)
163                && active_focus_trap(window, cx).is_none_or(|focus| focus == dialog.focus)
164        })
165    }
166
167    pub(in crate::overlay) fn dismiss(
168        &self,
169        reason: DialogCloseReason,
170        window: &mut Window,
171        cx: &mut App,
172    ) -> bool {
173        self.current(window, cx)
174            && self
175                .dismiss_request
176                .as_ref()
177                .is_none_or(|request| request(reason, window, cx))
178            && self.finish(reason, window, cx)
179    }
180
181    pub(super) fn finish(
182        &self,
183        reason: DialogCloseReason,
184        window: &mut Window,
185        cx: &mut App,
186    ) -> bool {
187        let Some(state) = self.state.upgrade() else {
188            return false;
189        };
190        let accepted = state.update(cx, |state, cx| {
191            if !state.open || state.generation != self.generation {
192                return false;
193            }
194            state.finish(reason, window, cx);
195            true
196        });
197        if accepted && let Some(on_close) = &self.on_close {
198            on_close(reason, window, cx);
199        }
200        accepted
201    }
202}
203
204pub(super) type BuildNativeDialog =
205    Box<dyn Fn(&Entity<DialogState>, &mut Window, &mut App) -> Dialog>;
206
207pub(super) struct NativeDialogView {
208    pub(super) state: Entity<DialogState>,
209    pub(super) build: BuildNativeDialog,
210}
211
212impl Render for NativeDialogView {
213    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
214        div()
215            .size_full()
216            .child((self.build)(&self.state, window, cx))
217    }
218}