Skip to main content

fc_ui/capabilities/overlays/
dialog.rs

1//! Dialog component with focus trap and backdrop.
2//!
3//! Note: this [`Dialog`] is a stateful entity; do not confuse it with
4//! [`super::confirm_dialog::Dialog`], a lightweight `RenderOnce` element for
5//! simple confirmation layouts without focus management.
6
7use gpui::{prelude::FluentBuilder as _, *};
8use std::rc::Rc;
9use std::time::Duration;
10
11use crate::capabilities::foundation::theme::use_theme;
12use crate::capabilities::motion::animations::easings;
13use crate::capabilities::primitives::button::{Button, ButtonSize, ButtonVariant};
14
15actions!(dialog, [DialogCancel]);
16
17#[derive(Copy, Clone, Debug, PartialEq, Eq)]
18pub enum DialogSize {
19    Sm,
20    Md,
21    Lg,
22    Xl,
23    Full,
24}
25
26impl DialogSize {
27    fn width(&self) -> Length {
28        match self {
29            Self::Sm => px(400.0).into(),
30            Self::Md => px(500.0).into(),
31            Self::Lg => px(600.0).into(),
32            Self::Xl => px(800.0).into(),
33            Self::Full => relative(0.95).into(),
34        }
35    }
36
37    fn max_height(&self) -> Length {
38        match self {
39            Self::Full => relative(0.95).into(),
40            _ => relative(0.85).into(),
41        }
42    }
43}
44
45type DialogElementBuilder = Rc<dyn Fn(&mut Window, &mut App) -> AnyElement>;
46
47fn dialog_element_builder<E, F>(builder: F) -> DialogElementBuilder
48where
49    E: IntoElement + 'static,
50    F: Fn(&mut Window, &mut App) -> E + 'static,
51{
52    Rc::new(move |window, cx| builder(window, cx).into_any_element())
53}
54
55pub struct Dialog {
56    focus_handle: FocusHandle,
57    header: Option<DialogElementBuilder>,
58    title: Option<SharedString>,
59    description: Option<SharedString>,
60    size: DialogSize,
61    children: Vec<DialogElementBuilder>,
62    footer: Option<DialogElementBuilder>,
63    show_close_button: bool,
64    close_on_backdrop_click: bool,
65    close_on_escape: bool,
66    on_close: Option<Rc<dyn Fn(&mut Window, &mut App)>>,
67    focused: bool,
68    dismissing: bool,
69    dismiss_complete: bool,
70    previous_focus: Option<FocusHandle>,
71    _focus_lost_subscription: Option<Subscription>,
72    style: StyleRefinement,
73}
74
75impl Dialog {
76    pub fn new(cx: &mut Context<Self>) -> Self {
77        Self {
78            focus_handle: cx.focus_handle(),
79            header: None,
80            title: None,
81            description: None,
82            size: DialogSize::Md,
83            children: vec![],
84            footer: None,
85            show_close_button: true,
86            close_on_backdrop_click: true,
87            close_on_escape: true,
88            on_close: None,
89            focused: false,
90            dismissing: false,
91            dismiss_complete: false,
92            previous_focus: None,
93            _focus_lost_subscription: None,
94            style: StyleRefinement::default(),
95        }
96    }
97
98    pub fn header<E, F>(mut self, header: F) -> Self
99    where
100        E: IntoElement + 'static,
101        F: Fn(&mut Window, &mut App) -> E + 'static,
102    {
103        self.header = Some(dialog_element_builder(header));
104        self
105    }
106
107    pub fn title(mut self, title: impl Into<SharedString>) -> Self {
108        self.title = Some(title.into());
109        self
110    }
111
112    pub fn description(mut self, description: impl Into<SharedString>) -> Self {
113        self.description = Some(description.into());
114        self
115    }
116
117    pub fn size(mut self, size: DialogSize) -> Self {
118        self.size = size;
119        self
120    }
121
122    pub fn child<E, F>(mut self, child: F) -> Self
123    where
124        E: IntoElement + 'static,
125        F: Fn(&mut Window, &mut App) -> E + 'static,
126    {
127        self.children.push(dialog_element_builder(child));
128        self
129    }
130
131    pub fn children<E, F>(mut self, children: impl IntoIterator<Item = F>) -> Self
132    where
133        E: IntoElement + 'static,
134        F: Fn(&mut Window, &mut App) -> E + 'static,
135    {
136        self.children
137            .extend(children.into_iter().map(dialog_element_builder));
138        self
139    }
140
141    pub fn footer<E, F>(mut self, footer: F) -> Self
142    where
143        E: IntoElement + 'static,
144        F: Fn(&mut Window, &mut App) -> E + 'static,
145    {
146        self.footer = Some(dialog_element_builder(footer));
147        self
148    }
149
150    pub fn show_close_button(mut self, show: bool) -> Self {
151        self.show_close_button = show;
152        self
153    }
154
155    pub fn close_on_backdrop_click(mut self, close: bool) -> Self {
156        self.close_on_backdrop_click = close;
157        self
158    }
159
160    pub fn close_on_escape(mut self, close: bool) -> Self {
161        self.close_on_escape = close;
162        self
163    }
164
165    pub fn on_close(mut self, handler: impl Fn(&mut Window, &mut App) + 'static) -> Self {
166        self.on_close = Some(Rc::new(handler));
167        self
168    }
169
170    fn restore_previous_focus(&mut self, window: &mut Window, cx: &App) {
171        if let Some(previous_focus) = self.previous_focus.take() {
172            window.focus(&previous_focus);
173        } else if let Some(restore_target) = window.focus_lost_restore_target(cx) {
174            window.focus(&restore_target);
175        }
176    }
177
178    fn handle_close(&mut self, window: &mut Window, cx: &mut Context<Self>) {
179        if self.dismissing {
180            return;
181        }
182        self.dismissing = true;
183        cx.notify();
184
185        cx.spawn_in(window, async move |this, cx| {
186            cx.background_executor()
187                .timer(Duration::from_millis(200))
188                .await;
189            let _ = this.update_in(cx, |dialog, window, cx| {
190                dialog.dismiss_complete = true;
191                dialog.restore_previous_focus(window, cx);
192                if let Some(handler) = dialog.on_close.take() {
193                    (handler)(window, cx);
194                }
195                cx.notify();
196            });
197        })
198        .detach();
199    }
200}
201
202impl Styled for Dialog {
203    fn style(&mut self) -> &mut StyleRefinement {
204        &mut self.style
205    }
206}
207
208impl Render for Dialog {
209    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
210        if self.dismiss_complete {
211            return div().into_any_element();
212        }
213
214        let theme = use_theme(cx);
215        let header = self.header.as_ref().map(|header| header(window, cx));
216        let children = self
217            .children
218            .iter()
219            .map(|child| child(window, cx))
220            .collect::<Vec<_>>();
221        let footer = self.footer.as_ref().map(|footer| footer(window, cx));
222        let has_slot_header = header.is_some();
223        let has_header = has_slot_header
224            || self.title.is_some()
225            || self.description.is_some()
226            || self.show_close_button;
227        let has_children = !children.is_empty();
228
229        let dialog_entity = cx.entity().clone();
230        let user_style = self.style.clone();
231        let dismissing = self.dismissing;
232
233        if !self.focused {
234            self.previous_focus = window.focused(cx);
235            window.focus(&self.focus_handle);
236            self.focused = true;
237            self._focus_lost_subscription = Some(cx.on_focus_lost(window, |this, window, cx| {
238                if this.focused {
239                    this.focused = false;
240                    this.restore_previous_focus(window, cx);
241                    cx.notify();
242                }
243            }));
244        }
245
246        div()
247            .id("dialog-overlay")
248            .absolute()
249            .inset_0()
250            .flex()
251            .items_center()
252            .justify_center()
253            .bg(gpui::black().opacity(0.5))
254            .child(
255                div()
256                    .id("dialog-content")
257                    .role(Role::Dialog)
258                    .when_some(self.title.clone(), |this, title| this.aria_label(title))
259                    .when_some(self.description.clone(), |this, description| {
260                        this.aria_description(description)
261                    })
262                    .aria_modal(true)
263                    .occlude()
264                    .key_context("Dialog")
265                    .track_focus(&self.focus_handle)
266                    .when(self.close_on_backdrop_click, |this| {
267                        this.on_mouse_down_out(cx.listener(|this, _, window, cx| {
268                            this.handle_close(window, cx);
269                        }))
270                    })
271                    .on_action(cx.listener(|this, _: &DialogCancel, window, cx| {
272                        if this.close_on_escape {
273                            this.handle_close(window, cx);
274                        }
275                    }))
276                    .w(self.size.width())
277                    .max_h(self.size.max_height())
278                    .flex()
279                    .flex_col()
280                    .bg(theme.tokens.card)
281                    .border_1()
282                    .border_color(theme.tokens.border)
283                    .rounded(theme.tokens.radius_lg)
284                    .shadow_xl()
285                    .overflow_hidden()
286                    .when(has_header, |this| {
287                        if has_slot_header {
288                            this.child(header.unwrap())
289                        } else {
290                            this.child(
291                                div()
292                                    .flex()
293                                    .flex_col()
294                                    .gap(px(8.0))
295                                    .px(px(24.0))
296                                    .pt(px(24.0))
297                                    .pb(px(16.0))
298                                    .when(footer.is_none() && !has_children, |this| {
299                                        this.pb(px(24.0))
300                                    })
301                                    .child(
302                                        div()
303                                            .flex()
304                                            .items_start()
305                                            .justify_between()
306                                            .gap(px(16.0))
307                                            .child(
308                                                div()
309                                                    .flex()
310                                                    .flex_col()
311                                                    .gap(px(4.0))
312                                                    .flex_1()
313                                                    .when_some(self.title.clone(), |this, title| {
314                                                        this.child(
315                                                            div()
316                                                                .text_size(px(18.0))
317                                                                .font_family(
318                                                                    theme
319                                                                        .tokens
320                                                                        .font_family
321                                                                        .clone(),
322                                                                )
323                                                                .font_weight(FontWeight::SEMIBOLD)
324                                                                .text_color(theme.tokens.foreground)
325                                                                .line_height(relative(1.2))
326                                                                .child(title),
327                                                        )
328                                                    })
329                                                    .when_some(
330                                                        self.description.clone(),
331                                                        |this, desc| {
332                                                            this.child(
333                                                                div()
334                                                                    .text_size(px(14.0))
335                                                                    .font_family(
336                                                                        theme
337                                                                            .tokens
338                                                                            .font_family
339                                                                            .clone(),
340                                                                    )
341                                                                    .text_color(
342                                                                        theme
343                                                                            .tokens
344                                                                            .muted_foreground,
345                                                                    )
346                                                                    .line_height(relative(1.5))
347                                                                    .child(desc),
348                                                            )
349                                                        },
350                                                    ),
351                                            )
352                                            .when(self.show_close_button, |this| {
353                                                let dialog_entity = dialog_entity.clone();
354                                                this.child(
355                                                    Button::new("dialog-close-btn", "×")
356                                                        .aria_label("Close dialog")
357                                                        .variant(ButtonVariant::Ghost)
358                                                        .size(ButtonSize::Icon)
359                                                        .on_click(move |_, window, cx| {
360                                                            cx.update_entity(
361                                                                &dialog_entity,
362                                                                |dialog, cx| {
363                                                                    dialog.handle_close(window, cx);
364                                                                },
365                                                            );
366                                                        }),
367                                                )
368                                            }),
369                                    ),
370                            )
371                        }
372                    })
373                    .when(has_children, |this| {
374                        this.child(
375                            div()
376                                .flex()
377                                .flex_col()
378                                .gap(px(16.0))
379                                .px(px(24.0))
380                                .py(px(16.0))
381                                .flex_1()
382                                .children(children),
383                        )
384                    })
385                    .map(|this| {
386                        let mut div = this;
387                        div.style().refine(&user_style);
388                        div
389                    })
390                    .when_some(footer, |this, footer| {
391                        this.child(
392                            div()
393                                .flex()
394                                .items_center()
395                                .justify_end()
396                                .gap(px(8.0))
397                                .px(px(24.0))
398                                .py(px(16.0))
399                                .border_t_1()
400                                .border_color(theme.tokens.border)
401                                .child(footer),
402                        )
403                    })
404                    .with_animation(
405                        if dismissing {
406                            "dialog-content-exit"
407                        } else {
408                            "dialog-content-enter"
409                        },
410                        Animation::new(Duration::from_millis(if dismissing { 200 } else { 250 }))
411                            .with_easing(if dismissing {
412                                easings::ease_in_cubic as fn(f32) -> f32
413                            } else {
414                                easings::ease_out_cubic as fn(f32) -> f32
415                            }),
416                        move |el, delta| {
417                            if dismissing {
418                                el.opacity(1.0 - delta).mt(px(8.0 * delta))
419                            } else {
420                                el.opacity(delta).mt(px(12.0 * (1.0 - delta)))
421                            }
422                        },
423                    ),
424            )
425            .with_animation(
426                if dismissing {
427                    "dialog-backdrop-exit"
428                } else {
429                    "dialog-backdrop-fade"
430                },
431                Animation::new(Duration::from_millis(200)).with_easing(if dismissing {
432                    easings::ease_in_cubic as fn(f32) -> f32
433                } else {
434                    easings::ease_out_cubic as fn(f32) -> f32
435                }),
436                move |el, delta| {
437                    if dismissing {
438                        el.opacity(1.0 - delta)
439                    } else {
440                        el.opacity(delta)
441                    }
442                },
443            )
444            .into_any_element()
445    }
446}
447
448impl Focusable for Dialog {
449    fn focus_handle(&self, _: &App) -> FocusHandle {
450        self.focus_handle.clone()
451    }
452}
453
454impl EventEmitter<()> for Dialog {}
455
456pub fn init_dialog(cx: &mut App) {
457    if !crate::capabilities::foundation::initialization::begin(cx, "dialog") {
458        return;
459    }
460    cx.bind_keys([KeyBinding::new("escape", DialogCancel, Some("Dialog"))]);
461}