Skip to main content

gpui_material_components/overlay/
dialog.rs

1use std::{cell::RefCell, rc::Rc};
2
3use gpui::{
4    AnyElement, App, Context, ElementId, Entity, FocusHandle, InteractiveElement, IntoElement,
5    ParentElement, RenderOnce, Role, ScrollHandle, SharedString, StatefulInteractiveElement,
6    Styled, Subscription, WeakFocusHandle, Window, anchored, div, point, prelude::FluentBuilder,
7    px,
8};
9use gpui_base::TestSupportExt;
10use gpui_material_foundation::{
11    Surface, color, isolated_scroll, scrim_color, window_material_theme,
12};
13use gpui_material_theme::{ColorRole, CornerRole, Elevation, TypeRole};
14
15use crate::{Button, ButtonVariant, IconButton, Text};
16
17pub(super) fn exiting_panel<E: StatefulInteractiveElement + ParentElement>(
18    panel: E,
19    id: &ElementId,
20    focus: &FocusHandle,
21    window: &mut Window,
22    cx: &mut App,
23) -> E {
24    // The body can contain caller-owned controls. Keep their layout through
25    // exit, but send focus back outside the panel and cover its hit targets.
26    let guard = window.use_keyed_state((id.clone(), "exiting-focus"), cx, |_, _| {
27        let previous = Rc::new(RefCell::new(None::<WeakFocusHandle>));
28        (previous, None::<Subscription>)
29    });
30    let target = window
31        .focused(cx)
32        .filter(|handle| !focus.contains(handle, window));
33    guard.update(cx, |(previous, guard), cx| {
34        if let Some(target) = target {
35            *previous.borrow_mut() = Some(target.downgrade());
36        }
37        if guard.is_none() {
38            let previous = previous.clone();
39            *guard = Some(window.on_focus_in(focus, cx, move |window, cx| {
40                if let Some(handle) = previous
41                    .borrow()
42                    .as_ref()
43                    .and_then(WeakFocusHandle::upgrade)
44                {
45                    handle.focus(window, cx);
46                } else {
47                    window.blur(cx);
48                }
49            }));
50        }
51    });
52    panel
53        .role(Role::Group)
54        .track_focus(focus)
55        .capture_key_down(|_, _, cx| cx.stop_propagation())
56        .a11y_synthetic_children(|tree| tree.parent_node().set_hidden())
57        .child(div().absolute().inset_0().occlude())
58}
59
60/// Retains one modal's focus scope and the focus to restore on close.
61pub struct DialogState {
62    pub(super) focus: FocusHandle,
63    previous: Option<FocusHandle>,
64    cancel_focus: FocusHandle,
65    confirm_focus: FocusHandle,
66    open: bool,
67    pub(super) scroll: ScrollHandle,
68}
69
70impl DialogState {
71    pub fn new(cx: &mut Context<Self>) -> Self {
72        Self {
73            focus: cx.focus_handle(),
74            previous: None,
75            cancel_focus: cx.focus_handle(),
76            confirm_focus: cx.focus_handle(),
77            open: false,
78            scroll: ScrollHandle::new(),
79        }
80    }
81
82    pub fn is_open(&self) -> bool {
83        self.open
84    }
85
86    /// Focuses the modal container. A caller can then focus a child editor.
87    pub fn open(&mut self, window: &mut Window, cx: &mut Context<Self>) {
88        if self.open {
89            return;
90        }
91        self.previous = window.focused(cx);
92        self.open = true;
93        self.focus.focus(window, cx);
94        cx.notify();
95    }
96
97    /// Closes the modal and restores the previous focus if its handle still exists.
98    pub fn close(&mut self, window: &mut Window, cx: &mut Context<Self>) {
99        if !self.open {
100            return;
101        }
102        self.open = false;
103        let previous = self.previous.take();
104        if self.focus.contains_focused(window, cx) || self.focus.is_focused(window) {
105            if let Some(previous) = previous {
106                previous.focus(window, cx);
107            } else {
108                window.blur(cx);
109            }
110        }
111        cx.notify();
112    }
113}
114
115/// Window-relative presentation for a Material dialog.
116#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
117pub enum DialogVariant {
118    #[default]
119    Basic,
120    /// Uses a full-screen task surface in compact windows, and a basic dialog
121    /// at wider breakpoints, as required by Material dialog guidance.
122    FullScreen,
123}
124
125type Confirm = Rc<dyn Fn(&mut Window, &mut App) -> bool>;
126
127/// A Material modal with a title and optional description, body, and actions.
128#[derive(IntoElement)]
129pub struct Dialog {
130    id: ElementId,
131    state: Entity<DialogState>,
132    title: SharedString,
133    description: Option<SharedString>,
134    body: Option<AnyElement>,
135    variant: DialogVariant,
136    confirm: Option<(SharedString, Confirm)>,
137    cancel: SharedString,
138    layer: usize,
139}
140
141impl Dialog {
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            description: None,
152            body: None,
153            variant: DialogVariant::Basic,
154            confirm: None,
155            cancel: "Cancel".into(),
156            layer: 0,
157        }
158    }
159
160    pub fn variant(mut self, variant: DialogVariant) -> Self {
161        self.variant = variant;
162        self
163    }
164
165    pub fn description(mut self, description: impl Into<SharedString>) -> Self {
166        self.description = Some(description.into());
167        self
168    }
169
170    pub fn body(mut self, body: impl IntoElement) -> Self {
171        self.body = Some(body.into_any_element());
172        self
173    }
174
175    /// Sets the default action. Returning false keeps the dialog open.
176    pub fn confirm(
177        mut self,
178        label: impl Into<SharedString>,
179        action: impl Fn(&mut Window, &mut App) -> bool + 'static,
180    ) -> Self {
181        self.confirm = Some((label.into(), Rc::new(action)));
182        self
183    }
184
185    pub fn cancel_label(mut self, label: impl Into<SharedString>) -> Self {
186        self.cancel = label.into();
187        self
188    }
189
190    /// Set a higher layer for a nested modal. Only the top modal can receive input.
191    pub fn layer(mut self, layer: usize) -> Self {
192        self.layer = layer;
193        self
194    }
195}
196
197impl RenderOnce for Dialog {
198    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
199        let state = self.state.read(cx);
200        let open = state.open;
201        let focus = state.focus.clone();
202        let scroll = state.scroll.clone();
203        let cancel_focus = state.cancel_focus.clone();
204        let confirm_focus = state.confirm_focus.clone();
205        let presence = crate::motion::presence(&self.id, open, 200, window, cx);
206        if !presence.should_render() {
207            return div().into_any_element();
208        }
209        let progress = presence.progress;
210        let viewport = window.viewport_size();
211        let full_screen = self.variant == DialogVariant::FullScreen && viewport.width < px(600.);
212        let theme = window_material_theme(window, cx);
213        let rtl = theme.layout.direction == gpui_material_theme::Direction::Rtl;
214        let radius = px(CornerRole::ExtraLarge
215            .shape()
216            .radii(280., 280., theme.layout.direction)[0]);
217        let scrim = scrim_color(theme, 0.32 * progress);
218        let width = if full_screen {
219            viewport.width
220        } else {
221            px(560.).min((viewport.width - px(48.)).max(px(0.)))
222        };
223        let motion_offset = px((1. - progress) * if full_screen { 32. } else { 8. });
224        let confirm_action = self.confirm.as_ref().map(|(_, action)| action.clone());
225        let close = self.state.clone();
226        let click_cancel = close.clone();
227        let click_confirm = close.clone();
228        let cancel = move |window: &mut Window, cx: &mut App| {
229            if open {
230                click_cancel.update(cx, |state, cx| state.close(window, cx));
231            }
232        };
233        let confirm = self.confirm.map(|(label, action)| {
234            Button::new("confirm", label)
235                .track_focus(&confirm_focus)
236                .variant(ButtonVariant::Text)
237                .on_activate(move |window, cx| {
238                    if open && action(window, cx) {
239                        click_confirm.update(cx, |state, cx| state.close(window, cx));
240                    }
241                })
242        });
243        let heading = if full_screen {
244            Text::new(self.title.clone())
245                .role(TypeRole::TitleLarge)
246                .into_any_element()
247        } else {
248            super::text_style(
249                div().child(self.title.clone()),
250                TypeRole::HeadlineSmall,
251                1.,
252                window,
253                cx,
254            )
255            .into_any_element()
256        };
257        let supporting = self.description.map(|description| {
258            super::text_style(
259                div()
260                    .id("description")
261                    .role(Role::Label)
262                    .text_color(color(theme.colors.color(ColorRole::OnSurfaceVariant)))
263                    .child(description),
264                TypeRole::BodyMedium,
265                1.,
266                window,
267                cx,
268            )
269        });
270        let mut surface = Surface::new(ColorRole::SurfaceContainerHigh)
271            .flex()
272            .flex_col()
273            .w(width)
274            .max_h(if full_screen {
275                viewport.height
276            } else {
277                (viewport.height - px(48.)).max(px(0.))
278            });
279        if full_screen {
280            // Full-screen dialogs are task surfaces with a persistent app bar,
281            // not enlarged alert dialogs with bottom-aligned confirmation.
282            surface = surface
283                .h(viewport.height)
284                .child(
285                    div()
286                        .id("dialog-app-bar")
287                        .test_support()
288                        .flex()
289                        .flex_none()
290                        .items_center()
291                        .h(px(56.))
292                        .px(px(4.))
293                        .gap(px(8.))
294                        .when(rtl, Styled::flex_row_reverse)
295                        .child(
296                            IconButton::new(
297                                "cancel",
298                                self.cancel,
299                                crate::Icon::new(crate::IconName::Close),
300                            )
301                            .track_focus(&cancel_focus)
302                            .on_activate(cancel),
303                        )
304                        .child(div().flex_1().min_w_0().child(heading))
305                        .children(confirm),
306                )
307                .child(
308                    isolated_scroll("dialog-content", &scroll)
309                        .test_support()
310                        .flex_1()
311                        .min_h_0()
312                        .p(px(24.))
313                        .flex()
314                        .flex_col()
315                        .gap(px(16.))
316                        .children(supporting)
317                        .children(self.body),
318                );
319        } else {
320            surface = surface
321                .rounded(radius)
322                .shadow_elevation(Elevation::Level3)
323                .p(px(24.))
324                .child(div().flex_none().mb(px(16.)).child(heading))
325                .child(
326                    isolated_scroll("dialog-content", &scroll)
327                        .test_support()
328                        .min_h_0()
329                        .flex()
330                        .flex_col()
331                        .gap(px(16.))
332                        .children(supporting)
333                        .children(self.body),
334                )
335                .child(
336                    div()
337                        .flex()
338                        .flex_none()
339                        .mt(px(24.))
340                        .when(rtl, Styled::flex_row_reverse)
341                        .justify_end()
342                        .flex_wrap()
343                        .gap(px(8.))
344                        .child(
345                            Button::new("cancel", self.cancel)
346                                .track_focus(&cancel_focus)
347                                .variant(ButtonVariant::Text)
348                                .on_activate(cancel),
349                        )
350                        .children(confirm),
351                );
352        }
353        let panel = div()
354            .id(self.id.clone())
355            .test_support()
356            .relative()
357            .opacity(progress)
358            .mt(motion_offset)
359            .when(open, |panel| panel.occlude())
360            .child(surface);
361        if !open {
362            return gpui::deferred(
363                anchored().position(point(px(0.), px(0.))).child(
364                    div()
365                        .id((self.id.clone(), "dialog-exit"))
366                        .absolute()
367                        .top_0()
368                        .left_0()
369                        .w(viewport.width)
370                        .h(viewport.height)
371                        .flex()
372                        .items_center()
373                        .justify_center()
374                        .child(div().absolute().inset_0().bg(scrim))
375                        .child(exiting_panel(panel, &self.id, &focus, window, cx)),
376                ),
377            )
378            .with_priority(10 + self.layer)
379            .into_any_element();
380        }
381        gpui_base::Dialog::new(cx)
382            .focus_handle(focus)
383            .layer(self.layer, true)
384            .accessibility_label(self.title.clone())
385            .backdrop(div().absolute().inset_0().bg(scrim))
386            .on_ok(move |_, window, cx| {
387                confirm_action
388                    .as_ref()
389                    .is_some_and(|action| action(window, cx))
390            })
391            .on_open_change(move |open, _, window, cx| {
392                if !open {
393                    close.update(cx, |state, cx| state.close(window, cx));
394                }
395            })
396            .popup(panel)
397            .into_any_element()
398    }
399}