Skip to main content

gpui_material_components/overlay/
dialog.rs

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