fc_ui/capabilities/overlays/
dialog.rs1use 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 .debug_selector(|| "dialog-content".to_string())
258 .role(Role::Dialog)
259 .when_some(self.title.clone(), |this, title| this.aria_label(title))
260 .when_some(self.description.clone(), |this, description| {
261 this.aria_description(description)
262 })
263 .aria_modal(true)
264 .occlude()
265 .key_context("Dialog")
266 .track_focus(&self.focus_handle)
267 .when(self.close_on_backdrop_click, |this| {
268 this.on_mouse_down_out(cx.listener(|this, _, window, cx| {
269 this.handle_close(window, cx);
270 }))
271 })
272 .on_action(cx.listener(|this, _: &DialogCancel, window, cx| {
273 if this.close_on_escape {
274 this.handle_close(window, cx);
275 }
276 }))
277 .w(self.size.width())
278 .max_h(self.size.max_height())
279 .flex()
280 .flex_col()
281 .bg(theme.tokens.card)
282 .border_1()
283 .border_color(theme.tokens.border)
284 .rounded(theme.tokens.radius_lg)
285 .shadow_xl()
286 .overflow_hidden()
287 .when(has_header, |this| {
288 if has_slot_header {
289 this.child(header.unwrap())
290 } else {
291 this.child(
292 div()
293 .flex()
294 .flex_col()
295 .gap(px(8.0))
296 .px(px(24.0))
297 .pt(px(24.0))
298 .pb(px(16.0))
299 .when(footer.is_none() && !has_children, |this| {
300 this.pb(px(24.0))
301 })
302 .child(
303 div()
304 .flex()
305 .items_start()
306 .justify_between()
307 .gap(px(16.0))
308 .child(
309 div()
310 .flex()
311 .flex_col()
312 .gap(px(4.0))
313 .flex_1()
314 .when_some(self.title.clone(), |this, title| {
315 this.child(
316 div()
317 .text_size(px(18.0))
318 .font_family(
319 theme
320 .tokens
321 .font_family
322 .clone(),
323 )
324 .font_weight(FontWeight::SEMIBOLD)
325 .text_color(theme.tokens.foreground)
326 .line_height(relative(1.2))
327 .child(title),
328 )
329 })
330 .when_some(
331 self.description.clone(),
332 |this, desc| {
333 this.child(
334 div()
335 .text_size(px(14.0))
336 .font_family(
337 theme
338 .tokens
339 .font_family
340 .clone(),
341 )
342 .text_color(
343 theme
344 .tokens
345 .muted_foreground,
346 )
347 .line_height(relative(1.5))
348 .child(desc),
349 )
350 },
351 ),
352 )
353 .when(self.show_close_button, |this| {
354 let dialog_entity = dialog_entity.clone();
355 this.child(
356 Button::new("dialog-close-btn", "×")
357 .aria_label("Close dialog")
358 .variant(ButtonVariant::Ghost)
359 .size(ButtonSize::Icon)
360 .on_click(move |_, window, cx| {
361 cx.update_entity(
362 &dialog_entity,
363 |dialog, cx| {
364 dialog.handle_close(window, cx);
365 },
366 );
367 }),
368 )
369 }),
370 ),
371 )
372 }
373 })
374 .when(has_children, |this| {
375 this.child(
376 div()
377 .flex()
378 .flex_col()
379 .gap(px(16.0))
380 .px(px(24.0))
381 .py(px(16.0))
382 .flex_1()
383 .children(children),
384 )
385 })
386 .map(|this| {
387 let mut div = this;
388 div.style().refine(&user_style);
389 div
390 })
391 .when_some(footer, |this, footer| {
392 this.child(
393 div()
394 .flex()
395 .items_center()
396 .justify_end()
397 .gap(px(8.0))
398 .px(px(24.0))
399 .py(px(16.0))
400 .border_t_1()
401 .border_color(theme.tokens.border)
402 .child(footer),
403 )
404 })
405 .with_animation(
406 if dismissing {
407 "dialog-content-exit"
408 } else {
409 "dialog-content-enter"
410 },
411 Animation::new(Duration::from_millis(if dismissing { 200 } else { 250 }))
412 .with_easing(if dismissing {
413 easings::ease_in_cubic as fn(f32) -> f32
414 } else {
415 easings::ease_out_cubic as fn(f32) -> f32
416 }),
417 move |el, delta| {
418 if dismissing {
419 el.opacity(1.0 - delta).mt(px(8.0 * delta))
420 } else {
421 el.opacity(delta).mt(px(12.0 * (1.0 - delta)))
422 }
423 },
424 ),
425 )
426 .with_animation(
427 if dismissing {
428 "dialog-backdrop-exit"
429 } else {
430 "dialog-backdrop-fade"
431 },
432 Animation::new(Duration::from_millis(200)).with_easing(if dismissing {
433 easings::ease_in_cubic as fn(f32) -> f32
434 } else {
435 easings::ease_out_cubic as fn(f32) -> f32
436 }),
437 move |el, delta| {
438 if dismissing {
439 el.opacity(1.0 - delta)
440 } else {
441 el.opacity(delta)
442 }
443 },
444 )
445 .into_any_element()
446 }
447}
448
449impl Focusable for Dialog {
450 fn focus_handle(&self, _: &App) -> FocusHandle {
451 self.focus_handle.clone()
452 }
453}
454
455impl EventEmitter<()> for Dialog {}
456
457pub fn init_dialog(cx: &mut App) {
458 if !crate::capabilities::foundation::initialization::begin(cx, "dialog") {
459 return;
460 }
461 cx.bind_keys([KeyBinding::new("escape", DialogCancel, Some("Dialog"))]);
462}