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