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,
98 Cancel,
99 Escape,
100 OutsideClick,
101 WindowClose,
102 Programmatic,
103}
104
105#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
107pub enum DialogVariant {
108 #[default]
109 Basic,
110 FullScreen,
113}
114
115#[derive(Clone, Copy, Debug, Eq, PartialEq)]
117pub struct DialogProperties {
118 pub dismiss_on_escape: bool,
119 pub dismiss_on_outside_click: bool,
120}
121
122impl Default for DialogProperties {
123 fn default() -> Self {
124 Self {
125 dismiss_on_escape: true,
126 dismiss_on_outside_click: true,
127 }
128 }
129}
130
131#[derive(Clone, Copy, Debug, Default)]
133pub struct DialogColors {
134 pub container: Option<Hsla>,
135 pub icon: Option<Hsla>,
136 pub title: Option<Hsla>,
137 pub text: Option<Hsla>,
138}
139
140type Confirm = Rc<dyn Fn(&mut Window, &mut App) -> bool>;
141pub(super) type ModalDismissRequest = Rc<dyn Fn(DialogCloseReason, &mut Window, &mut App) -> bool>;
142pub(super) type ModalClosed = Rc<dyn Fn(DialogCloseReason, &mut Window, &mut App)>;
143type ActionSlot = Box<dyn FnOnce(DialogAction) -> AnyElement>;
144type BodySlot = Box<dyn FnOnce(DialogAction, DialogAction) -> AnyElement>;
145
146#[derive(Clone)]
148pub struct DialogAction {
149 session: ModalSession,
150 reason: DialogCloseReason,
151 validate: Option<Confirm>,
152}
153
154impl DialogAction {
155 pub fn activate(&self, window: &mut Window, cx: &mut App) {
157 if self.session.current(window, cx)
158 && self
159 .validate
160 .as_ref()
161 .is_none_or(|validate| validate(window, cx))
162 {
163 self.session.finish(self.reason, window, cx);
164 }
165 }
166}
167
168#[derive(IntoElement)]
170pub struct Dialog {
171 id: ElementId,
172 state: Entity<DialogState>,
173 title: SharedString,
174 show_title: bool,
175 title_content: Option<AnyElement>,
176 icon: Option<AnyElement>,
177 description: Option<SharedString>,
178 body: Option<BodySlot>,
179 variant: DialogVariant,
180 unstructured: bool,
181 confirm: Option<(SharedString, Confirm)>,
182 confirm_tone: SemanticTone,
183 confirm_content: Option<ActionSlot>,
184 dismiss_content: Option<ActionSlot>,
185 cancel: SharedString,
186 show_cancel: bool,
187 layer: usize,
188 properties: DialogProperties,
189 shape: Option<CornerShape>,
190 colors: DialogColors,
191 tonal_elevation: Option<Elevation>,
192 shadow_elevation: Option<Elevation>,
193 scrim_color: Option<Hsla>,
194 scrim_opacity: f32,
195 width: Pixels,
196 dismiss_request: Option<ModalDismissRequest>,
197 on_close: Option<ModalClosed>,
198}
199
200impl Dialog {
201 pub fn new(
202 id: impl Into<ElementId>,
203 state: &Entity<DialogState>,
204 title: impl Into<SharedString>,
205 ) -> Self {
206 Self {
207 id: id.into(),
208 state: state.clone(),
209 title: title.into(),
210 show_title: true,
211 title_content: None,
212 icon: None,
213 description: None,
214 body: None,
215 variant: DialogVariant::Basic,
216 unstructured: false,
217 confirm: None,
218 confirm_tone: SemanticTone::Default,
219 confirm_content: None,
220 dismiss_content: None,
221 cancel: "Cancel".into(),
222 show_cancel: true,
223 layer: 0,
224 properties: DialogProperties::default(),
225 shape: None,
226 colors: DialogColors::default(),
227 tonal_elevation: None,
228 shadow_elevation: None,
229 scrim_color: None,
230 scrim_opacity: 0.32,
231 width: px(560.),
232 dismiss_request: None,
233 on_close: None,
234 }
235 }
236
237 pub fn alert(
239 id: impl Into<ElementId>,
240 state: &Entity<DialogState>,
241 title: impl Into<SharedString>,
242 description: impl Into<SharedString>,
243 ) -> Self {
244 Self::new(id, state, title)
245 .description(description)
246 .show_cancel(false)
247 }
248
249 pub fn unstructured(
251 id: impl Into<ElementId>,
252 state: &Entity<DialogState>,
253 accessibility_label: impl Into<SharedString>,
254 ) -> Self {
255 Self {
256 unstructured: true,
257 ..Self::new(id, state, accessibility_label)
258 }
259 }
260
261 pub fn open_window(
265 state: &Entity<DialogState>,
266 parent: &mut Window,
267 mut options: WindowOptions,
268 cx: &mut App,
269 build: impl Fn(&Entity<DialogState>, &mut Window, &mut App) -> Self + 'static,
270 ) -> gpui::Result<Option<AnyWindowHandle>> {
271 let current = state.read(cx);
272 if current.is_open() {
273 return Ok(current.native.as_ref().map(|native| native.child));
274 }
275 let parent_handle = parent.window_handle();
276 if cx
277 .active_window()
278 .is_none_or(|active| active.window_id() != parent_handle.window_id())
279 {
280 return Err(std::io::Error::new(
281 std::io::ErrorKind::InvalidInput,
282 "the dialog's parent window must be active",
283 )
284 .into());
285 }
286 options.kind = WindowKind::Dialog;
287 options.focus = true;
288 options.show = true;
289 let previous = parent.focused(cx);
290 let theme = current_material_theme(parent, cx).clone();
291 let state = state.clone();
292 let window = MaterialRoot::open_window(options, cx, move |window, cx| {
293 set_window_material_theme(Some(theme), window, cx);
294 let child = window.window_handle();
295 let weak = state.downgrade();
296 let closed = cx.on_window_closed(move |cx, id| {
297 if id == child.window_id()
298 && let Some(state) = weak.upgrade()
299 {
300 state.update(cx, |state, cx| {
301 if let Some(native) = state.native.take() {
302 state.open = false;
303 state.last_close_reason = Some(DialogCloseReason::Programmatic);
304 restore_parent(native.parent, state.previous.take(), cx);
305 cx.notify();
306 }
307 });
308 }
309 });
310 state.update(cx, |state, cx| {
311 state.native = Some(NativeDialog {
312 parent: parent_handle,
313 child,
314 _closed: closed,
315 });
316 state.begin(previous, window, cx);
317 });
318 cx.new(|cx: &mut Context<NativeDialogView>| {
319 cx.observe(&state, |_, _, cx| cx.notify()).detach();
320 NativeDialogView {
321 state,
322 build: Box::new(build),
323 }
324 })
325 })?;
326 Ok(Some(window.into()))
327 }
328
329 pub fn variant(mut self, variant: DialogVariant) -> Self {
330 self.variant = variant;
331 self
332 }
333
334 pub fn icon(mut self, icon: impl IntoElement) -> Self {
335 self.icon = Some(icon.into_any_element());
336 self
337 }
338
339 pub fn title_content(mut self, title: impl IntoElement) -> Self {
341 self.title_content = Some(title.into_any_element());
342 self
343 }
344
345 pub fn show_title(mut self, show: bool) -> Self {
346 self.show_title = show;
347 self
348 }
349
350 pub fn description(mut self, description: impl Into<SharedString>) -> Self {
351 self.description = Some(description.into());
352 self
353 }
354
355 pub fn body(mut self, body: impl IntoElement) -> Self {
356 let body = body.into_any_element();
357 self.body = Some(Box::new(|_, _| body));
358 self
359 }
360
361 pub fn body_content<E: IntoElement>(
363 mut self,
364 body: impl FnOnce(DialogAction, DialogAction) -> E + 'static,
365 ) -> Self {
366 self.body = Some(Box::new(move |confirm, dismiss| {
367 body(confirm, dismiss).into_any_element()
368 }));
369 self
370 }
371
372 pub fn confirm(
374 mut self,
375 label: impl Into<SharedString>,
376 action: impl Fn(&mut Window, &mut App) -> bool + 'static,
377 ) -> Self {
378 self.confirm = Some((label.into(), Rc::new(action)));
379 self
380 }
381
382 pub fn on_confirm(
384 self,
385 label: impl Into<SharedString>,
386 action: impl Fn(&mut Window, &mut App) + 'static,
387 ) -> Self {
388 self.confirm(label, move |window, cx| {
389 action(window, cx);
390 true
391 })
392 }
393
394 pub fn confirm_tone(mut self, tone: SemanticTone) -> Self {
396 self.confirm_tone = tone;
397 self
398 }
399
400 pub fn confirm_content<E: IntoElement>(
402 mut self,
403 content: impl FnOnce(DialogAction) -> E + 'static,
404 ) -> Self {
405 self.confirm_content = Some(Box::new(move |confirm| content(confirm).into_any_element()));
406 self
407 }
408
409 pub fn dismiss_content<E: IntoElement>(
411 mut self,
412 content: impl FnOnce(DialogAction) -> E + 'static,
413 ) -> Self {
414 self.dismiss_content = Some(Box::new(move |dismiss| content(dismiss).into_any_element()));
415 self
416 }
417
418 pub fn cancel_label(mut self, label: impl Into<SharedString>) -> Self {
419 self.cancel = label.into();
420 self
421 }
422
423 pub fn show_cancel(mut self, show: bool) -> Self {
425 self.show_cancel = show;
426 self
427 }
428
429 pub fn layer(mut self, layer: usize) -> Self {
431 self.layer = layer;
432 self
433 }
434
435 pub fn properties(mut self, properties: DialogProperties) -> Self {
436 self.properties = properties;
437 self
438 }
439
440 pub fn on_dismiss_request(
442 mut self,
443 request: impl Fn(DialogCloseReason, &mut Window, &mut App) -> bool + 'static,
444 ) -> Self {
445 self.dismiss_request = Some(Rc::new(request));
446 self
447 }
448
449 pub fn on_close(
451 mut self,
452 close: impl Fn(DialogCloseReason, &mut Window, &mut App) + 'static,
453 ) -> Self {
454 self.on_close = Some(Rc::new(close));
455 self
456 }
457
458 pub fn shape(mut self, shape: CornerShape) -> Self {
459 self.shape = Some(shape);
460 self
461 }
462
463 pub fn colors(mut self, colors: DialogColors) -> Self {
464 self.colors = colors;
465 self
466 }
467
468 pub fn tonal_elevation(mut self, elevation: Elevation) -> Self {
470 self.tonal_elevation = Some(elevation);
471 self
472 }
473
474 pub fn shadow_elevation(mut self, elevation: Elevation) -> Self {
475 self.shadow_elevation = Some(elevation);
476 self
477 }
478
479 pub fn scrim_color(mut self, color: Hsla) -> Self {
480 self.scrim_color = Some(color);
481 self
482 }
483
484 pub fn scrim_opacity(mut self, opacity: f32) -> Self {
486 self.scrim_opacity = if opacity.is_nan() {
487 0.32
488 } else {
489 opacity.clamp(0., 1.)
490 };
491 self
492 }
493
494 pub fn width(mut self, width: Pixels) -> Self {
496 if f32::from(width).is_finite() {
497 self.width = width.max(px(0.));
498 }
499 self
500 }
501}