Skip to main content

gpui_material_components/overlay/
dialog.rs

1use std::rc::Rc;
2
3use gpui::{
4    AnyElement, AnyWindowHandle, App, AppContext, Context, ElementId, Entity, Hsla, IntoElement,
5    Pixels, SharedString, Window, WindowKind, WindowOptions, px,
6};
7use gpui_material_foundation::{MaterialRoot, current_material_theme, set_window_material_theme};
8use gpui_material_theme::{CornerShape, Elevation};
9
10use crate::SemanticTone;
11
12mod render;
13mod state;
14
15pub use state::DialogState;
16pub(super) use state::ModalSession;
17use state::{NativeDialog, NativeDialogView, restore_parent};
18
19/// An accepted transition from an open to a closed Material dialog.
20#[derive(Clone, Copy, Debug, Eq, PartialEq)]
21pub enum DialogCloseReason {
22    /// Closed by activating the confirmation action.
23    Confirm,
24    /// Closed by activating the cancel or close action.
25    Cancel,
26    /// Closed by pressing the Escape key.
27    Escape,
28    /// Closed by clicking the modal scrim outside the surface.
29    OutsideClick,
30    /// Closed by the user closing a native dialog window.
31    WindowClose,
32    /// Closed programmatically via [`DialogState::close`].
33    Programmatic,
34}
35
36/// Window-relative presentation for a Material dialog.
37#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
38pub enum DialogVariant {
39    /// Standard centered modal dialog.
40    #[default]
41    Basic,
42    /// Uses a full-screen task surface in compact windows and a basic dialog
43    /// at wider breakpoints, as required by Material dialog guidance.
44    FullScreen,
45}
46
47/// User dismissal routes for a Material dialog.
48#[derive(Clone, Copy, Debug, Eq, PartialEq)]
49pub struct DialogProperties {
50    /// Whether pressing Escape requests dismissal (default `true`).
51    pub dismiss_on_escape: bool,
52    /// Whether clicking the backdrop scrim requests dismissal (default `true`).
53    pub dismiss_on_outside_click: bool,
54}
55
56impl Default for DialogProperties {
57    fn default() -> Self {
58        Self {
59            dismiss_on_escape: true,
60            dismiss_on_outside_click: true,
61        }
62    }
63}
64
65/// Local overrides for a dialog surface and its content slots.
66#[derive(Clone, Copy, Debug, Default)]
67pub struct DialogColors {
68    /// Background color override for the dialog container.
69    pub container: Option<Hsla>,
70    /// Foreground color override for the optional header icon.
71    pub icon: Option<Hsla>,
72    /// Foreground color override for the dialog title.
73    pub title: Option<Hsla>,
74    /// Foreground color override for the supporting description text.
75    pub text: Option<Hsla>,
76}
77
78type Confirm = Rc<dyn Fn(&mut Window, &mut App) -> bool>;
79pub(super) type ModalDismissRequest = Rc<dyn Fn(DialogCloseReason, &mut Window, &mut App) -> bool>;
80pub(super) type ModalClosed = Rc<dyn Fn(DialogCloseReason, &mut Window, &mut App)>;
81type ActionSlot = Box<dyn FnOnce(DialogAction) -> AnyElement>;
82type BodySlot = Box<dyn FnOnce(DialogAction, DialogAction) -> AnyElement>;
83
84/// Activation for a dialog slot, valid while that open dialog owns input.
85#[derive(Clone)]
86pub struct DialogAction {
87    session: ModalSession,
88    reason: DialogCloseReason,
89    validate: Option<Confirm>,
90}
91
92impl DialogAction {
93    /// Routes user activation through the dialog's policy and close callback.
94    pub fn activate(&self, window: &mut Window, cx: &mut App) {
95        if self.session.current(window, cx)
96            && self
97                .validate
98                .as_ref()
99                .is_none_or(|validate| validate(window, cx))
100        {
101            self.session.finish(self.reason, window, cx);
102        }
103    }
104}
105
106/// A named Material modal with optional structured slots or caller-defined content.
107#[derive(IntoElement)]
108pub struct Dialog {
109    id: ElementId,
110    state: Entity<DialogState>,
111    title: SharedString,
112    show_title: bool,
113    title_content: Option<AnyElement>,
114    icon: Option<AnyElement>,
115    description: Option<SharedString>,
116    body: Option<BodySlot>,
117    variant: DialogVariant,
118    unstructured: bool,
119    confirm: Option<(SharedString, Confirm)>,
120    confirm_tone: SemanticTone,
121    confirm_disabled: bool,
122    confirm_loading: bool,
123    confirm_content: Option<ActionSlot>,
124    dismiss_content: Option<ActionSlot>,
125    cancel: SharedString,
126    show_cancel: bool,
127    layer: usize,
128    properties: DialogProperties,
129    shape: Option<CornerShape>,
130    colors: DialogColors,
131    tonal_elevation: Option<Elevation>,
132    shadow_elevation: Option<Elevation>,
133    scrim_color: Option<Hsla>,
134    scrim_opacity: f32,
135    width: Pixels,
136    dismiss_request: Option<ModalDismissRequest>,
137    on_closed: Option<ModalClosed>,
138}
139
140impl Dialog {
141    /// Creates a basic Material dialog bound to `state` with the given accessible title.
142    pub fn new(
143        id: impl Into<ElementId>,
144        state: &Entity<DialogState>,
145        title: impl Into<SharedString>,
146    ) -> Self {
147        Self {
148            id: id.into(),
149            state: state.clone(),
150            title: title.into(),
151            show_title: true,
152            title_content: None,
153            icon: None,
154            description: None,
155            body: None,
156            variant: DialogVariant::Basic,
157            unstructured: false,
158            confirm: None,
159            confirm_tone: SemanticTone::Default,
160            confirm_disabled: false,
161            confirm_loading: false,
162            confirm_content: None,
163            dismiss_content: None,
164            cancel: "Cancel".into(),
165            show_cancel: true,
166            layer: 0,
167            properties: DialogProperties::default(),
168            shape: None,
169            colors: DialogColors::default(),
170            tonal_elevation: None,
171            shadow_elevation: None,
172            scrim_color: None,
173            scrim_opacity: 0.32,
174            width: px(560.),
175            dismiss_request: None,
176            on_closed: None,
177        }
178    }
179
180    /// Creates a basic alert dialog with a description and no default cancel button.
181    pub fn alert(
182        id: impl Into<ElementId>,
183        state: &Entity<DialogState>,
184        title: impl Into<SharedString>,
185        description: impl Into<SharedString>,
186    ) -> Self {
187        Self::new(id, state, title)
188            .description(description)
189            .show_cancel(false)
190    }
191
192    /// Creates a modal shell whose body owns the structure and scrolling.
193    pub fn unstructured(
194        id: impl Into<ElementId>,
195        state: &Entity<DialogState>,
196        accessibility_label: impl Into<SharedString>,
197    ) -> Self {
198        Self {
199            unstructured: true,
200            ..Self::new(id, state, accessibility_label)
201        }
202    }
203
204    /// Opens a separate GPUI modal window, with the active window as its native parent.
205    /// Supply the invoking window and build a fresh dialog on each render. An already
206    /// open state returns its native window handle, or None for an in-window dialog.
207    pub fn open_window(
208        state: &Entity<DialogState>,
209        parent: &mut Window,
210        mut options: WindowOptions,
211        cx: &mut App,
212        build: impl Fn(&Entity<DialogState>, &mut Window, &mut App) -> Self + 'static,
213    ) -> gpui::Result<Option<AnyWindowHandle>> {
214        let current = state.read(cx);
215        if current.is_open() {
216            return Ok(current.native.as_ref().map(|native| native.child));
217        }
218        let parent_handle = parent.window_handle();
219        if cx
220            .active_window()
221            .is_none_or(|active| active.window_id() != parent_handle.window_id())
222        {
223            return Err(std::io::Error::new(
224                std::io::ErrorKind::InvalidInput,
225                "the dialog's parent window must be active",
226            )
227            .into());
228        }
229        options.kind = WindowKind::Dialog;
230        options.focus = true;
231        options.show = true;
232        let previous = parent.focused(cx);
233        let theme = current_material_theme(parent, cx).clone();
234        let state = state.clone();
235        let window = MaterialRoot::open_window(options, cx, move |window, cx| {
236            set_window_material_theme(Some(theme), window, cx);
237            let child = window.window_handle();
238            let weak = state.downgrade();
239            let closed = cx.on_window_closed(move |cx, id| {
240                if id == child.window_id()
241                    && let Some(state) = weak.upgrade()
242                {
243                    state.update(cx, |state, cx| {
244                        if let Some(native) = state.native.take() {
245                            state.open = false;
246                            state.last_close_reason = Some(DialogCloseReason::Programmatic);
247                            restore_parent(native.parent, state.previous.take(), cx);
248                            cx.notify();
249                        }
250                    });
251                }
252            });
253            state.update(cx, |state, cx| {
254                state.native = Some(NativeDialog {
255                    parent: parent_handle,
256                    child,
257                    _closed: closed,
258                });
259                state.begin(previous, window, cx);
260            });
261            cx.new(|cx: &mut Context<NativeDialogView>| {
262                cx.observe(&state, |_, _, cx| cx.notify()).detach();
263                NativeDialogView {
264                    state,
265                    build: Box::new(build),
266                }
267            })
268        })?;
269        Ok(Some(window.into()))
270    }
271
272    /// Sets the presentation variant (default [`DialogVariant::Basic`]).
273    pub fn variant(mut self, variant: DialogVariant) -> Self {
274        self.variant = variant;
275        self
276    }
277
278    /// Adds a decorative icon above the dialog title.
279    pub fn icon(mut self, icon: impl IntoElement) -> Self {
280        self.icon = Some(icon.into_any_element());
281        self
282    }
283
284    /// Replaces the visual heading, keeping the constructor's accessible name.
285    pub fn title_content(mut self, title: impl IntoElement) -> Self {
286        self.title_content = Some(title.into_any_element());
287        self
288    }
289
290    /// Shows or hides the visible title while preserving the accessible dialog name.
291    pub fn show_title(mut self, show: bool) -> Self {
292        self.show_title = show;
293        self
294    }
295
296    /// Sets the supporting text displayed beneath the dialog title.
297    pub fn description(mut self, description: impl Into<SharedString>) -> Self {
298        self.description = Some(description.into());
299        self
300    }
301
302    /// Sets custom body content rendered inside the dialog's scrollable body region.
303    pub fn body(mut self, body: impl IntoElement) -> Self {
304        let body = body.into_any_element();
305        self.body = Some(Box::new(|_, _| body));
306        self
307    }
308
309    /// Builds the body with the confirmation and cancellation activation handles.
310    pub fn body_content<E: IntoElement>(
311        mut self,
312        body: impl FnOnce(DialogAction, DialogAction) -> E + 'static,
313    ) -> Self {
314        self.body = Some(Box::new(move |confirm, dismiss| {
315            body(confirm, dismiss).into_any_element()
316        }));
317        self
318    }
319
320    /// Sets the default action and validation. Returning false keeps the dialog open.
321    pub fn confirm(
322        mut self,
323        label: impl Into<SharedString>,
324        action: impl Fn(&mut Window, &mut App) -> bool + 'static,
325    ) -> Self {
326        self.confirm = Some((label.into(), Rc::new(action)));
327        self
328    }
329
330    /// Sets a non-validating confirmation action that always closes the dialog after running.
331    pub fn on_confirm(
332        self,
333        label: impl Into<SharedString>,
334        action: impl Fn(&mut Window, &mut App) + 'static,
335    ) -> Self {
336        self.confirm(label, move |window, cx| {
337            action(window, cx);
338            true
339        })
340    }
341
342    /// Applies a Material 3 semantic tone to the default confirmation button.
343    pub fn confirm_tone(mut self, tone: SemanticTone) -> Self {
344        self.confirm_tone = tone;
345        self
346    }
347
348    /// Disables the default confirmation button and suppresses Enter confirmation.
349    pub fn confirm_disabled(mut self, disabled: bool) -> Self {
350        self.confirm_disabled = disabled;
351        self
352    }
353
354    /// Shows an inline busy spinner on the default confirmation button and suppresses Enter confirmation.
355    pub fn confirm_loading(mut self, loading: bool) -> Self {
356        self.confirm_loading = loading;
357        self
358    }
359
360    /// Builds a custom confirmation control. Wire its activation to the supplied action.
361    pub fn confirm_content<E: IntoElement>(
362        mut self,
363        content: impl FnOnce(DialogAction) -> E + 'static,
364    ) -> Self {
365        self.confirm_content = Some(Box::new(move |confirm| content(confirm).into_any_element()));
366        self
367    }
368
369    /// Builds a custom cancellation control. Wire its activation to the supplied action.
370    pub fn dismiss_content<E: IntoElement>(
371        mut self,
372        content: impl FnOnce(DialogAction) -> E + 'static,
373    ) -> Self {
374        self.dismiss_content = Some(Box::new(move |dismiss| content(dismiss).into_any_element()));
375        self
376    }
377
378    /// Overrides the label of the default cancellation button (default `"Cancel"`).
379    pub fn cancel_label(mut self, label: impl Into<SharedString>) -> Self {
380        self.cancel = label.into();
381        self
382    }
383
384    /// Sets whether to include a default cancellation control when there is no custom one.
385    pub fn show_cancel(mut self, show: bool) -> Self {
386        self.show_cancel = show;
387        self
388    }
389
390    /// Set a higher layer for a nested modal. Only the top modal can receive input.
391    pub fn layer(mut self, layer: usize) -> Self {
392        self.layer = layer;
393        self
394    }
395
396    /// Configures Escape and outside-click dismissal behavior.
397    pub fn properties(mut self, properties: DialogProperties) -> Self {
398        self.properties = properties;
399        self
400    }
401
402    /// Handles Escape, outside-click, and system window-close requests. Return false to veto.
403    pub fn on_dismiss_request(
404        mut self,
405        request: impl Fn(DialogCloseReason, &mut Window, &mut App) -> bool + 'static,
406    ) -> Self {
407        self.dismiss_request = Some(Rc::new(request));
408        self
409    }
410
411    /// Reports one accepted user close after the visibility state has changed.
412    pub fn on_closed(
413        mut self,
414        close: impl Fn(DialogCloseReason, &mut Window, &mut App) + 'static,
415    ) -> Self {
416        self.on_closed = Some(Rc::new(close));
417        self
418    }
419
420    /// Overrides the corner shape of the dialog surface.
421    pub fn shape(mut self, shape: CornerShape) -> Self {
422        self.shape = Some(shape);
423        self
424    }
425
426    /// Overrides the dialog's container, icon, title, and text colors.
427    pub fn colors(mut self, colors: DialogColors) -> Self {
428        self.colors = colors;
429        self
430    }
431
432    /// Selects a tonal Material surface when the container color uses the theme.
433    pub fn tonal_elevation(mut self, elevation: Elevation) -> Self {
434        self.tonal_elevation = Some(elevation);
435        self
436    }
437
438    /// Overrides the shadow elevation cast by the dialog surface.
439    pub fn shadow_elevation(mut self, elevation: Elevation) -> Self {
440        self.shadow_elevation = Some(elevation);
441        self
442    }
443
444    /// Overrides the backdrop scrim color.
445    pub fn scrim_color(mut self, color: Hsla) -> Self {
446        self.scrim_color = Some(color);
447        self
448    }
449
450    /// Sets in-window backdrop opacity, clamped to 0–1. NaN uses the default.
451    pub fn scrim_opacity(mut self, opacity: f32) -> Self {
452        self.scrim_opacity = if opacity.is_nan() {
453            0.32
454        } else {
455            opacity.clamp(0., 1.)
456        };
457        self
458    }
459
460    /// Sets the maximum width of the centered dialog in logical pixels.
461    pub fn width(mut self, width: Pixels) -> Self {
462        if f32::from(width).is_finite() {
463            self.width = width.max(px(0.));
464        }
465        self
466    }
467}