Skip to main content

gpui_material_components/overlay/dialog/
render.rs

1use gpui::{
2    AnyElement, App, ElementId, Entity, FocusHandle, Hsla, InteractiveElement, IntoElement,
3    ParentElement, Pixels, RenderOnce, Role, ScrollHandle, SharedString, Size,
4    StatefulInteractiveElement, Styled, Window, div, prelude::FluentBuilder, px,
5};
6use gpui_base::{DialogChangeReason, TestSupportExt};
7use gpui_material_foundation::{
8    Scrim, Surface, ThemeScope, color, current_material_theme, isolated_scroll,
9};
10use gpui_material_theme::{
11    ColorRole, CornerRole, CornerShape, Direction, Elevation, MotionKind, MotionSpeed, TypeRole,
12};
13
14use crate::{Button, ButtonVariant, IconButton, SemanticTone};
15
16use super::super::modal::{ModalHost, ZLayer, modal_backdrop, motion_duration_ms};
17use super::{
18    ActionSlot, Confirm, Dialog, DialogAction, DialogCloseReason, DialogColors, DialogProperties,
19    DialogState, DialogVariant, ModalSession,
20};
21
22#[allow(clippy::too_many_arguments)]
23fn build_surface_shell(
24    max_height: Pixels,
25    text_color: Hsla,
26    colors: DialogColors,
27    tonal_elevation: Option<Elevation>,
28    shadow_elevation: Option<Elevation>,
29    shape: Option<CornerShape>,
30    full_screen: bool,
31    unstructured: bool,
32    native: bool,
33) -> Surface {
34    let role = if tonal_elevation.is_some() {
35        ColorRole::Surface
36    } else {
37        ColorRole::SurfaceContainerHigh
38    };
39    let mut surface = Surface::new(role)
40        .flex()
41        .flex_col()
42        .max_h(max_height)
43        .content_color(text_color);
44    if let Some(container) = colors.container {
45        surface = surface.container_color(container);
46    } else if unstructured && tonal_elevation.is_none() {
47        surface = surface.container_color(gpui::transparent_black());
48    }
49    if let Some(tonal) = tonal_elevation {
50        surface = surface.tonal_elevation(tonal);
51    }
52    if let Some(shape) = shape.or_else(|| {
53        (!full_screen && !unstructured && !native).then(|| CornerRole::ExtraLarge.shape())
54    }) {
55        surface = surface.shape(shape);
56    }
57    let shadow = shadow_elevation.unwrap_or(if full_screen || unstructured || native {
58        Elevation::Level0
59    } else {
60        Elevation::Level3
61    });
62    surface.shadow_elevation(shadow)
63}
64
65#[allow(clippy::too_many_arguments)]
66fn build_actions(
67    confirm: Option<(SharedString, Confirm)>,
68    confirm_tone: SemanticTone,
69    confirm_disabled: bool,
70    confirm_loading: bool,
71    confirm_content: Option<ActionSlot>,
72    confirm_action: DialogAction,
73    confirm_focus: &FocusHandle,
74    dismiss_content: Option<ActionSlot>,
75    dismiss_action: DialogAction,
76    cancel_focus: &FocusHandle,
77    cancel_label: SharedString,
78    show_cancel: bool,
79    full_screen: bool,
80) -> (Option<AnyElement>, Option<AnyElement>) {
81    let confirm_element = match confirm_content {
82        Some(content) => Some(content(confirm_action)),
83        None => confirm.map(|(label, _)| {
84            Button::new("confirm", label)
85                .track_focus(confirm_focus)
86                .variant(ButtonVariant::Text)
87                .tone(confirm_tone)
88                .disabled(confirm_disabled)
89                .loading(confirm_loading)
90                .on_activate(move |window, cx| confirm_action.activate(window, cx))
91                .into_any_element()
92        }),
93    };
94    let cancel_element = match dismiss_content {
95        Some(content) => Some(content(dismiss_action)),
96        None if show_cancel && full_screen => Some(
97            IconButton::new(
98                "cancel",
99                cancel_label,
100                crate::Icon::new(crate::IconName::Close),
101            )
102            .track_focus(cancel_focus)
103            .on_activate(move |window, cx| dismiss_action.activate(window, cx))
104            .into_any_element(),
105        ),
106        None if show_cancel => Some(
107            Button::new("cancel", cancel_label)
108                .track_focus(cancel_focus)
109                .variant(ButtonVariant::Text)
110                .on_activate(move |window, cx| dismiss_action.activate(window, cx))
111                .into_any_element(),
112        ),
113        None => None,
114    };
115    (cancel_element, confirm_element)
116}
117
118struct StructuredDialogParts {
119    icon: Option<AnyElement>,
120    heading: Option<gpui::Div>,
121    content: AnyElement,
122    cancel: Option<AnyElement>,
123    confirm: Option<AnyElement>,
124}
125
126fn populate_structured_surface(
127    surface: Surface,
128    parts: StructuredDialogParts,
129    width: Pixels,
130    viewport_height: Pixels,
131    full_screen: bool,
132    rtl: bool,
133) -> Surface {
134    let surface = surface.w(width);
135    if full_screen {
136        surface
137            .h(viewport_height)
138            .child(
139                div()
140                    .id("dialog-app-bar")
141                    .test_support()
142                    .flex()
143                    .flex_none()
144                    .items_center()
145                    .h(px(56.))
146                    .px(px(4.))
147                    .gap(px(8.))
148                    .when(rtl, Styled::flex_row_reverse)
149                    .children(parts.cancel)
150                    .children(parts.icon)
151                    .child(div().flex_1().min_w_0().children(parts.heading))
152                    .children(parts.confirm),
153            )
154            .child(parts.content)
155    } else {
156        surface
157            .p(px(24.))
158            .children(parts.icon.map(|icon| {
159                div()
160                    .flex_none()
161                    .flex()
162                    .justify_center()
163                    .mb(px(16.))
164                    .child(icon)
165            }))
166            .children(
167                parts
168                    .heading
169                    .map(|heading| div().flex_none().mb(px(16.)).child(heading)),
170            )
171            .child(parts.content)
172            .children(
173                (parts.cancel.is_some() || parts.confirm.is_some()).then(|| {
174                    div()
175                        .flex()
176                        .flex_none()
177                        .mt(px(24.))
178                        .when(rtl, Styled::flex_row_reverse)
179                        .justify_end()
180                        .flex_wrap()
181                        .gap(px(8.))
182                        .children(parts.cancel)
183                        .children(parts.confirm)
184                }),
185            )
186    }
187}
188
189#[allow(clippy::too_many_arguments)]
190fn build_structured_parts(
191    icon: Option<AnyElement>,
192    icon_color: Hsla,
193    show_title: bool,
194    title: SharedString,
195    title_content: Option<AnyElement>,
196    title_color: Hsla,
197    description: Option<SharedString>,
198    body: Option<AnyElement>,
199    scroll: &ScrollHandle,
200    cancel: Option<AnyElement>,
201    confirm: Option<AnyElement>,
202    full_screen: bool,
203    window: &Window,
204    cx: &App,
205) -> StructuredDialogParts {
206    let icon = icon.map(|icon| div().text_color(icon_color).child(icon).into_any_element());
207    let has_icon = icon.is_some();
208    let heading = show_title.then(|| {
209        let heading = title_content.unwrap_or_else(|| title.into_any_element());
210        super::super::text_style(
211            div()
212                .min_w_0()
213                .text_color(title_color)
214                .when(has_icon && !full_screen, Styled::text_center)
215                .child(heading),
216            if full_screen {
217                TypeRole::TitleLarge
218            } else {
219                TypeRole::HeadlineSmall
220            },
221            1.,
222            window,
223            cx,
224        )
225    });
226    let supporting = description.map(|description| {
227        super::super::text_style(
228            div().id("description").role(Role::Label).child(description),
229            TypeRole::BodyMedium,
230            1.,
231            window,
232            cx,
233        )
234    });
235    let content = isolated_scroll("dialog-content", scroll)
236        .test_support()
237        .min_h_0()
238        .flex()
239        .flex_col()
240        .gap(px(16.))
241        .when(full_screen, |content| content.flex_1().p(px(24.)))
242        .children(supporting)
243        .children(body)
244        .into_any_element();
245    StructuredDialogParts {
246        icon,
247        heading,
248        content,
249        cancel,
250        confirm,
251    }
252}
253
254#[allow(clippy::too_many_arguments)]
255fn render_exiting_dialog<E: StatefulInteractiveElement + ParentElement + IntoElement>(
256    id: ElementId,
257    state: &Entity<DialogState>,
258    panel: E,
259    backdrop: Scrim,
260    viewport: Size<Pixels>,
261    layer: usize,
262    window: &mut Window,
263    cx: &mut App,
264) -> AnyElement {
265    ModalHost::new(id, ZLayer::dialog(layer), viewport)
266        .centered()
267        .render_exiting("dialog-exit", state, backdrop, panel, window, cx)
268}
269
270#[allow(clippy::too_many_arguments)]
271fn render_active_dialog<E: IntoElement>(
272    title: SharedString,
273    panel: E,
274    backdrop: Scrim,
275    focus: FocusHandle,
276    session: ModalSession,
277    confirm_action: DialogAction,
278    keyboard_confirmation: bool,
279    layer: usize,
280    native: bool,
281    properties: DialogProperties,
282    window: &mut Window,
283    cx: &mut App,
284) -> AnyElement {
285    if native {
286        let session = session.clone();
287        window.on_window_should_close(cx, move |window, cx| {
288            session.dismiss(DialogCloseReason::WindowClose, window, cx)
289        });
290    }
291    let outside = session.clone();
292    let keyboard_focus = focus.clone();
293    gpui_base::Dialog::new(cx)
294        .focus_handle(focus)
295        .layer(ZLayer::dialog(layer).priority(), true)
296        .accessibility_label(title)
297        .close_on_backdrop_press(false)
298        .backdrop(ThemeScope::inherit(
299            modal_backdrop(backdrop, move |window, cx| {
300                if !native && properties.dismiss_on_outside_click {
301                    outside.dismiss(DialogCloseReason::OutsideClick, window, cx);
302                }
303            }),
304            window,
305            cx,
306        ))
307        .on_ok(move |_, window, cx| {
308            if keyboard_confirmation && keyboard_focus.is_focused(window) {
309                confirm_action.activate(window, cx);
310            } else {
311                // Let a focused control handle Enter through its own key listener.
312                cx.propagate();
313            }
314            false
315        })
316        .on_open_change(move |_, reason, window, cx| {
317            if reason == DialogChangeReason::Cancel && properties.dismiss_on_escape {
318                session.dismiss(DialogCloseReason::Escape, window, cx);
319            }
320        })
321        .popup(ThemeScope::inherit(panel, window, cx))
322        .into_any_element()
323}
324
325impl RenderOnce for Dialog {
326    fn render(mut self, window: &mut Window, cx: &mut App) -> impl IntoElement {
327        let state = self.state.read(cx);
328        let native = state.native.is_some();
329        if let Some(native) = &state.native
330            && native.child.window_id() != window.window_handle().window_id()
331        {
332            return div().into_any_element();
333        }
334        let open = state.open;
335        let focus = state.focus.clone();
336        let scroll = state.scroll.clone();
337        let cancel_focus = state.cancel_focus.clone();
338        let confirm_focus = state.confirm_focus.clone();
339        let session = ModalSession::new(
340            &self.state,
341            self.dismiss_request.take(),
342            self.on_closed.take(),
343            cx,
344        );
345        let theme = current_material_theme(window, cx);
346        let duration_ms = motion_duration_ms(theme.motion.spec(
347            MotionKind::Spatial,
348            if open {
349                MotionSpeed::Default
350            } else {
351                MotionSpeed::Fast
352            },
353            cx.reduce_motion(),
354        ));
355        let presence = crate::overlay::presence(&self.id, open, duration_ms, window, cx);
356        if !presence.should_render() {
357            return div().into_any_element();
358        }
359        let progress = if native { 1. } else { presence.progress };
360        let viewport = window.viewport_size();
361        let full_screen = self.variant == DialogVariant::FullScreen && viewport.width < px(600.);
362        let window_filling = full_screen || native;
363        let margin = if window_filling { px(0.) } else { px(48.) };
364        let available_width = (viewport.width - margin).max(px(0.));
365        let width = if full_screen {
366            available_width
367        } else {
368            self.width.min(available_width)
369        };
370        let max_height = (viewport.height - margin).max(px(0.));
371        let motion_offset = px((1. - progress) * if full_screen { 32. } else { 8. });
372        let rtl = theme.layout.direction == Direction::Rtl;
373        let colors = &theme.colors;
374        let icon_color = self
375            .colors
376            .icon
377            .unwrap_or_else(|| color(colors.color(ColorRole::Secondary)));
378        let title_color = self
379            .colors
380            .title
381            .unwrap_or_else(|| color(colors.color(ColorRole::OnSurface)));
382        let text_color = self
383            .colors
384            .text
385            .unwrap_or_else(|| color(colors.color(ColorRole::OnSurfaceVariant)));
386
387        let confirm_action = DialogAction {
388            session: session.clone(),
389            reason: DialogCloseReason::Confirm,
390            validate: self
391                .confirm
392                .as_ref()
393                .map(|(_, validator)| validator.clone()),
394        };
395        let dismiss_action = DialogAction {
396            session: session.clone(),
397            reason: DialogCloseReason::Cancel,
398            validate: None,
399        };
400        let keyboard_confirmation = self.confirm.is_some()
401            && self.confirm_content.is_none()
402            && !self.unstructured
403            && !self.confirm_disabled
404            && !self.confirm_loading;
405        let body = self
406            .body
407            .map(|body| body(confirm_action.clone(), dismiss_action.clone()));
408        let mut surface = build_surface_shell(
409            max_height,
410            text_color,
411            self.colors,
412            self.tonal_elevation,
413            self.shadow_elevation,
414            self.shape,
415            full_screen,
416            self.unstructured,
417            native,
418        );
419        if self.unstructured {
420            surface = surface
421                .min_w(px(280.).min(width))
422                .max_w(width)
423                .children(body);
424        } else {
425            let (cancel, confirm) = build_actions(
426                self.confirm,
427                self.confirm_tone,
428                self.confirm_disabled,
429                self.confirm_loading,
430                self.confirm_content,
431                confirm_action.clone(),
432                &confirm_focus,
433                self.dismiss_content,
434                dismiss_action,
435                &cancel_focus,
436                self.cancel,
437                self.show_cancel,
438                full_screen,
439            );
440            let parts = build_structured_parts(
441                self.icon,
442                icon_color,
443                self.show_title,
444                self.title.clone(),
445                self.title_content,
446                title_color,
447                self.description,
448                body,
449                &scroll,
450                cancel,
451                confirm,
452                full_screen,
453                window,
454                cx,
455            );
456            surface = populate_structured_surface(
457                surface,
458                parts,
459                width,
460                viewport.height,
461                full_screen,
462                rtl,
463            );
464        }
465
466        let panel = div()
467            .id(self.id.clone())
468            .test_support()
469            .relative()
470            .max_w(available_width)
471            .max_h(max_height)
472            .opacity(progress)
473            .mt(motion_offset)
474            .when(open, |panel| panel.occlude())
475            .child(surface);
476        let backdrop = Scrim::new((self.id.clone(), "scrim"))
477            .opacity(if native {
478                0.
479            } else {
480                self.scrim_opacity * progress
481            })
482            .when_some(self.scrim_color, Scrim::color);
483        if !open {
484            return render_exiting_dialog(
485                self.id,
486                &self.state,
487                panel,
488                backdrop,
489                viewport,
490                self.layer,
491                window,
492                cx,
493            );
494        }
495        render_active_dialog(
496            self.title,
497            panel,
498            backdrop,
499            focus,
500            session,
501            confirm_action,
502            keyboard_confirmation,
503            self.layer,
504            native,
505            self.properties,
506            window,
507            cx,
508        )
509    }
510}