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