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