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