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