1use std::{cell::RefCell, rc::Rc};
2
3use gpui::{
4 AnyElement, AnyWindowHandle, App, AppContext, Context, ElementId, Entity, Hsla,
5 InteractiveElement, IntoElement, MouseButton, ParentElement, Pixels, Role, SharedString,
6 StatefulInteractiveElement, Styled, Subscription, WeakFocusHandle, Window, WindowKind,
7 WindowOptions, div, px,
8};
9use gpui_material_foundation::{
10 MaterialRoot, Scrim, current_material_theme, set_window_material_theme,
11};
12use gpui_material_theme::{CornerShape, Elevation};
13
14use crate::SemanticTone;
15
16mod render;
17mod state;
18
19pub use state::DialogState;
20pub(super) use state::ModalSession;
21use state::{NativeDialog, NativeDialogView, restore_parent};
22
23pub(super) fn exiting_panel<E: StatefulInteractiveElement + ParentElement>(
24 panel: E,
25 id: &ElementId,
26 state: &Entity<DialogState>,
27 window: &mut Window,
28 cx: &mut App,
29) -> E {
30 let focus = state.read(cx).focus.clone();
31 let guard = window.use_keyed_state((id.clone(), "exiting-focus"), cx, |_, _| {
34 let previous = Rc::new(RefCell::new(None::<WeakFocusHandle>));
35 (previous, None::<Subscription>)
36 });
37 let target = window
38 .focused(cx)
39 .filter(|handle| !focus.contains(handle, window));
40 guard.update(cx, |(previous, guard), cx| {
41 if let Some(target) = target {
42 *previous.borrow_mut() = Some(target.downgrade());
43 }
44 if guard.is_none() {
45 let previous = previous.clone();
46 let state = state.downgrade();
47 *guard = Some(window.on_focus_in(&focus, cx, move |window, cx| {
48 if state
50 .upgrade()
51 .is_some_and(|state| state.read(cx).is_open())
52 {
53 return;
54 }
55 if let Some(handle) = previous
56 .borrow()
57 .as_ref()
58 .and_then(WeakFocusHandle::upgrade)
59 {
60 handle.focus(window, cx);
61 } else {
62 window.blur(cx);
63 }
64 }));
65 }
66 });
67 panel
68 .role(Role::Group)
69 .track_focus(&focus)
70 .capture_key_down(|_, _, cx| cx.stop_propagation())
71 .a11y_synthetic_children(|tree| tree.parent_node().set_hidden())
72 .child(div().absolute().inset_0().occlude())
73}
74
75pub(super) fn modal_backdrop(
77 scrim: Scrim,
78 dismiss: impl Fn(&mut Window, &mut App) + 'static,
79) -> impl IntoElement {
80 div()
81 .absolute()
82 .inset_0()
83 .occlude()
84 .on_any_mouse_down(move |event, window, cx| {
85 cx.stop_propagation();
86 if event.button == MouseButton::Left {
87 dismiss(window, cx);
88 }
89 })
90 .on_scroll(|_, _, cx| cx.stop_propagation())
91 .child(scrim)
92}
93
94#[derive(Clone, Copy, Debug, Eq, PartialEq)]
96pub enum DialogCloseReason {
97 Confirm,
99 Cancel,
101 Escape,
103 OutsideClick,
105 WindowClose,
107 Programmatic,
109}
110
111#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
113pub enum DialogVariant {
114 #[default]
116 Basic,
117 FullScreen,
120}
121
122#[derive(Clone, Copy, Debug, Eq, PartialEq)]
124pub struct DialogProperties {
125 pub dismiss_on_escape: bool,
127 pub dismiss_on_outside_click: bool,
129}
130
131impl Default for DialogProperties {
132 fn default() -> Self {
133 Self {
134 dismiss_on_escape: true,
135 dismiss_on_outside_click: true,
136 }
137 }
138}
139
140#[derive(Clone, Copy, Debug, Default)]
142pub struct DialogColors {
143 pub container: Option<Hsla>,
145 pub icon: Option<Hsla>,
147 pub title: Option<Hsla>,
149 pub text: Option<Hsla>,
151}
152
153type Confirm = Rc<dyn Fn(&mut Window, &mut App) -> bool>;
154pub(super) type ModalDismissRequest = Rc<dyn Fn(DialogCloseReason, &mut Window, &mut App) -> bool>;
155pub(super) type ModalClosed = Rc<dyn Fn(DialogCloseReason, &mut Window, &mut App)>;
156type ActionSlot = Box<dyn FnOnce(DialogAction) -> AnyElement>;
157type BodySlot = Box<dyn FnOnce(DialogAction, DialogAction) -> AnyElement>;
158
159#[derive(Clone)]
161pub struct DialogAction {
162 session: ModalSession,
163 reason: DialogCloseReason,
164 validate: Option<Confirm>,
165}
166
167impl DialogAction {
168 pub fn activate(&self, window: &mut Window, cx: &mut App) {
170 if self.session.current(window, cx)
171 && self
172 .validate
173 .as_ref()
174 .is_none_or(|validate| validate(window, cx))
175 {
176 self.session.finish(self.reason, window, cx);
177 }
178 }
179}
180
181#[derive(IntoElement)]
183pub struct Dialog {
184 id: ElementId,
185 state: Entity<DialogState>,
186 title: SharedString,
187 show_title: bool,
188 title_content: Option<AnyElement>,
189 icon: Option<AnyElement>,
190 description: Option<SharedString>,
191 body: Option<BodySlot>,
192 variant: DialogVariant,
193 unstructured: bool,
194 confirm: Option<(SharedString, Confirm)>,
195 confirm_tone: SemanticTone,
196 confirm_disabled: bool,
197 confirm_loading: bool,
198 confirm_content: Option<ActionSlot>,
199 dismiss_content: Option<ActionSlot>,
200 cancel: SharedString,
201 show_cancel: bool,
202 layer: usize,
203 properties: DialogProperties,
204 shape: Option<CornerShape>,
205 colors: DialogColors,
206 tonal_elevation: Option<Elevation>,
207 shadow_elevation: Option<Elevation>,
208 scrim_color: Option<Hsla>,
209 scrim_opacity: f32,
210 width: Pixels,
211 dismiss_request: Option<ModalDismissRequest>,
212 on_close: Option<ModalClosed>,
213}
214
215impl Dialog {
216 pub fn new(
218 id: impl Into<ElementId>,
219 state: &Entity<DialogState>,
220 title: impl Into<SharedString>,
221 ) -> Self {
222 Self {
223 id: id.into(),
224 state: state.clone(),
225 title: title.into(),
226 show_title: true,
227 title_content: None,
228 icon: None,
229 description: None,
230 body: None,
231 variant: DialogVariant::Basic,
232 unstructured: false,
233 confirm: None,
234 confirm_tone: SemanticTone::Default,
235 confirm_disabled: false,
236 confirm_loading: false,
237 confirm_content: None,
238 dismiss_content: None,
239 cancel: "Cancel".into(),
240 show_cancel: true,
241 layer: 0,
242 properties: DialogProperties::default(),
243 shape: None,
244 colors: DialogColors::default(),
245 tonal_elevation: None,
246 shadow_elevation: None,
247 scrim_color: None,
248 scrim_opacity: 0.32,
249 width: px(560.),
250 dismiss_request: None,
251 on_close: None,
252 }
253 }
254
255 pub fn alert(
257 id: impl Into<ElementId>,
258 state: &Entity<DialogState>,
259 title: impl Into<SharedString>,
260 description: impl Into<SharedString>,
261 ) -> Self {
262 Self::new(id, state, title)
263 .description(description)
264 .show_cancel(false)
265 }
266
267 pub fn unstructured(
269 id: impl Into<ElementId>,
270 state: &Entity<DialogState>,
271 accessibility_label: impl Into<SharedString>,
272 ) -> Self {
273 Self {
274 unstructured: true,
275 ..Self::new(id, state, accessibility_label)
276 }
277 }
278
279 pub fn open_window(
283 state: &Entity<DialogState>,
284 parent: &mut Window,
285 mut options: WindowOptions,
286 cx: &mut App,
287 build: impl Fn(&Entity<DialogState>, &mut Window, &mut App) -> Self + 'static,
288 ) -> gpui::Result<Option<AnyWindowHandle>> {
289 let current = state.read(cx);
290 if current.is_open() {
291 return Ok(current.native.as_ref().map(|native| native.child));
292 }
293 let parent_handle = parent.window_handle();
294 if cx
295 .active_window()
296 .is_none_or(|active| active.window_id() != parent_handle.window_id())
297 {
298 return Err(std::io::Error::new(
299 std::io::ErrorKind::InvalidInput,
300 "the dialog's parent window must be active",
301 )
302 .into());
303 }
304 options.kind = WindowKind::Dialog;
305 options.focus = true;
306 options.show = true;
307 let previous = parent.focused(cx);
308 let theme = current_material_theme(parent, cx).clone();
309 let state = state.clone();
310 let window = MaterialRoot::open_window(options, cx, move |window, cx| {
311 set_window_material_theme(Some(theme), window, cx);
312 let child = window.window_handle();
313 let weak = state.downgrade();
314 let closed = cx.on_window_closed(move |cx, id| {
315 if id == child.window_id()
316 && let Some(state) = weak.upgrade()
317 {
318 state.update(cx, |state, cx| {
319 if let Some(native) = state.native.take() {
320 state.open = false;
321 state.last_close_reason = Some(DialogCloseReason::Programmatic);
322 restore_parent(native.parent, state.previous.take(), cx);
323 cx.notify();
324 }
325 });
326 }
327 });
328 state.update(cx, |state, cx| {
329 state.native = Some(NativeDialog {
330 parent: parent_handle,
331 child,
332 _closed: closed,
333 });
334 state.begin(previous, window, cx);
335 });
336 cx.new(|cx: &mut Context<NativeDialogView>| {
337 cx.observe(&state, |_, _, cx| cx.notify()).detach();
338 NativeDialogView {
339 state,
340 build: Box::new(build),
341 }
342 })
343 })?;
344 Ok(Some(window.into()))
345 }
346
347 pub fn variant(mut self, variant: DialogVariant) -> Self {
349 self.variant = variant;
350 self
351 }
352
353 pub fn icon(mut self, icon: impl IntoElement) -> Self {
355 self.icon = Some(icon.into_any_element());
356 self
357 }
358
359 pub fn title_content(mut self, title: impl IntoElement) -> Self {
361 self.title_content = Some(title.into_any_element());
362 self
363 }
364
365 pub fn show_title(mut self, show: bool) -> Self {
367 self.show_title = show;
368 self
369 }
370
371 pub fn description(mut self, description: impl Into<SharedString>) -> Self {
373 self.description = Some(description.into());
374 self
375 }
376
377 pub fn body(mut self, body: impl IntoElement) -> Self {
379 let body = body.into_any_element();
380 self.body = Some(Box::new(|_, _| body));
381 self
382 }
383
384 pub fn body_content<E: IntoElement>(
386 mut self,
387 body: impl FnOnce(DialogAction, DialogAction) -> E + 'static,
388 ) -> Self {
389 self.body = Some(Box::new(move |confirm, dismiss| {
390 body(confirm, dismiss).into_any_element()
391 }));
392 self
393 }
394
395 pub fn confirm(
397 mut self,
398 label: impl Into<SharedString>,
399 action: impl Fn(&mut Window, &mut App) -> bool + 'static,
400 ) -> Self {
401 self.confirm = Some((label.into(), Rc::new(action)));
402 self
403 }
404
405 pub fn on_confirm(
407 self,
408 label: impl Into<SharedString>,
409 action: impl Fn(&mut Window, &mut App) + 'static,
410 ) -> Self {
411 self.confirm(label, move |window, cx| {
412 action(window, cx);
413 true
414 })
415 }
416
417 pub fn confirm_tone(mut self, tone: SemanticTone) -> Self {
419 self.confirm_tone = tone;
420 self
421 }
422
423 pub fn confirm_disabled(mut self, disabled: bool) -> Self {
425 self.confirm_disabled = disabled;
426 self
427 }
428
429 pub fn confirm_loading(mut self, loading: bool) -> Self {
431 self.confirm_loading = loading;
432 self
433 }
434
435 pub fn confirm_content<E: IntoElement>(
437 mut self,
438 content: impl FnOnce(DialogAction) -> E + 'static,
439 ) -> Self {
440 self.confirm_content = Some(Box::new(move |confirm| content(confirm).into_any_element()));
441 self
442 }
443
444 pub fn dismiss_content<E: IntoElement>(
446 mut self,
447 content: impl FnOnce(DialogAction) -> E + 'static,
448 ) -> Self {
449 self.dismiss_content = Some(Box::new(move |dismiss| content(dismiss).into_any_element()));
450 self
451 }
452
453 pub fn cancel_label(mut self, label: impl Into<SharedString>) -> Self {
455 self.cancel = label.into();
456 self
457 }
458
459 pub fn show_cancel(mut self, show: bool) -> Self {
461 self.show_cancel = show;
462 self
463 }
464
465 pub fn layer(mut self, layer: usize) -> Self {
467 self.layer = layer;
468 self
469 }
470
471 pub fn properties(mut self, properties: DialogProperties) -> Self {
473 self.properties = properties;
474 self
475 }
476
477 pub fn on_dismiss_request(
479 mut self,
480 request: impl Fn(DialogCloseReason, &mut Window, &mut App) -> bool + 'static,
481 ) -> Self {
482 self.dismiss_request = Some(Rc::new(request));
483 self
484 }
485
486 pub fn on_close(
488 mut self,
489 close: impl Fn(DialogCloseReason, &mut Window, &mut App) + 'static,
490 ) -> Self {
491 self.on_close = Some(Rc::new(close));
492 self
493 }
494
495 pub fn shape(mut self, shape: CornerShape) -> Self {
497 self.shape = Some(shape);
498 self
499 }
500
501 pub fn colors(mut self, colors: DialogColors) -> Self {
503 self.colors = colors;
504 self
505 }
506
507 pub fn tonal_elevation(mut self, elevation: Elevation) -> Self {
509 self.tonal_elevation = Some(elevation);
510 self
511 }
512
513 pub fn shadow_elevation(mut self, elevation: Elevation) -> Self {
515 self.shadow_elevation = Some(elevation);
516 self
517 }
518
519 pub fn scrim_color(mut self, color: Hsla) -> Self {
521 self.scrim_color = Some(color);
522 self
523 }
524
525 pub fn scrim_opacity(mut self, opacity: f32) -> Self {
527 self.scrim_opacity = if opacity.is_nan() {
528 0.32
529 } else {
530 opacity.clamp(0., 1.)
531 };
532 self
533 }
534
535 pub fn width(mut self, width: Pixels) -> Self {
537 if f32::from(width).is_finite() {
538 self.width = width.max(px(0.));
539 }
540 self
541 }
542}