1use std::rc::Rc;
2
3use gpui::{
4 AnyElement, AnyWindowHandle, App, AppContext, Context, ElementId, Entity, Hsla, IntoElement,
5 Pixels, SharedString, Window, WindowKind, WindowOptions, px,
6};
7use gpui_material_foundation::{MaterialRoot, current_material_theme, set_window_material_theme};
8use gpui_material_theme::{CornerShape, Elevation};
9
10use crate::SemanticTone;
11
12mod render;
13mod state;
14
15pub use state::DialogState;
16pub(super) use state::ModalSession;
17use state::{NativeDialog, NativeDialogView, restore_parent};
18
19#[derive(Clone, Copy, Debug, Eq, PartialEq)]
21pub enum DialogCloseReason {
22 Confirm,
24 Cancel,
26 Escape,
28 OutsideClick,
30 WindowClose,
32 Programmatic,
34}
35
36#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
38pub enum DialogVariant {
39 #[default]
41 Basic,
42 FullScreen,
45}
46
47#[derive(Clone, Copy, Debug, Eq, PartialEq)]
49pub struct DialogProperties {
50 pub dismiss_on_escape: bool,
52 pub dismiss_on_outside_click: bool,
54}
55
56impl Default for DialogProperties {
57 fn default() -> Self {
58 Self {
59 dismiss_on_escape: true,
60 dismiss_on_outside_click: true,
61 }
62 }
63}
64
65#[derive(Clone, Copy, Debug, Default)]
67pub struct DialogColors {
68 pub container: Option<Hsla>,
70 pub icon: Option<Hsla>,
72 pub title: Option<Hsla>,
74 pub text: Option<Hsla>,
76}
77
78type Confirm = Rc<dyn Fn(&mut Window, &mut App) -> bool>;
79pub(super) type ModalDismissRequest = Rc<dyn Fn(DialogCloseReason, &mut Window, &mut App) -> bool>;
80pub(super) type ModalClosed = Rc<dyn Fn(DialogCloseReason, &mut Window, &mut App)>;
81type ActionSlot = Box<dyn FnOnce(DialogAction) -> AnyElement>;
82type BodySlot = Box<dyn FnOnce(DialogAction, DialogAction) -> AnyElement>;
83
84#[derive(Clone)]
86pub struct DialogAction {
87 session: ModalSession,
88 reason: DialogCloseReason,
89 validate: Option<Confirm>,
90}
91
92impl DialogAction {
93 pub fn activate(&self, window: &mut Window, cx: &mut App) {
95 if self.session.current(window, cx)
96 && self
97 .validate
98 .as_ref()
99 .is_none_or(|validate| validate(window, cx))
100 {
101 self.session.finish(self.reason, window, cx);
102 }
103 }
104}
105
106#[derive(IntoElement)]
108pub struct Dialog {
109 id: ElementId,
110 state: Entity<DialogState>,
111 title: SharedString,
112 show_title: bool,
113 title_content: Option<AnyElement>,
114 icon: Option<AnyElement>,
115 description: Option<SharedString>,
116 body: Option<BodySlot>,
117 variant: DialogVariant,
118 unstructured: bool,
119 confirm: Option<(SharedString, Confirm)>,
120 confirm_tone: SemanticTone,
121 confirm_disabled: bool,
122 confirm_loading: bool,
123 confirm_content: Option<ActionSlot>,
124 dismiss_content: Option<ActionSlot>,
125 cancel: SharedString,
126 show_cancel: bool,
127 layer: usize,
128 properties: DialogProperties,
129 shape: Option<CornerShape>,
130 colors: DialogColors,
131 tonal_elevation: Option<Elevation>,
132 shadow_elevation: Option<Elevation>,
133 scrim_color: Option<Hsla>,
134 scrim_opacity: f32,
135 width: Pixels,
136 dismiss_request: Option<ModalDismissRequest>,
137 on_closed: Option<ModalClosed>,
138}
139
140impl Dialog {
141 pub fn new(
143 id: impl Into<ElementId>,
144 state: &Entity<DialogState>,
145 title: impl Into<SharedString>,
146 ) -> Self {
147 Self {
148 id: id.into(),
149 state: state.clone(),
150 title: title.into(),
151 show_title: true,
152 title_content: None,
153 icon: None,
154 description: None,
155 body: None,
156 variant: DialogVariant::Basic,
157 unstructured: false,
158 confirm: None,
159 confirm_tone: SemanticTone::Default,
160 confirm_disabled: false,
161 confirm_loading: false,
162 confirm_content: None,
163 dismiss_content: None,
164 cancel: "Cancel".into(),
165 show_cancel: true,
166 layer: 0,
167 properties: DialogProperties::default(),
168 shape: None,
169 colors: DialogColors::default(),
170 tonal_elevation: None,
171 shadow_elevation: None,
172 scrim_color: None,
173 scrim_opacity: 0.32,
174 width: px(560.),
175 dismiss_request: None,
176 on_closed: None,
177 }
178 }
179
180 pub fn alert(
182 id: impl Into<ElementId>,
183 state: &Entity<DialogState>,
184 title: impl Into<SharedString>,
185 description: impl Into<SharedString>,
186 ) -> Self {
187 Self::new(id, state, title)
188 .description(description)
189 .show_cancel(false)
190 }
191
192 pub fn unstructured(
194 id: impl Into<ElementId>,
195 state: &Entity<DialogState>,
196 accessibility_label: impl Into<SharedString>,
197 ) -> Self {
198 Self {
199 unstructured: true,
200 ..Self::new(id, state, accessibility_label)
201 }
202 }
203
204 pub fn open_window(
208 state: &Entity<DialogState>,
209 parent: &mut Window,
210 mut options: WindowOptions,
211 cx: &mut App,
212 build: impl Fn(&Entity<DialogState>, &mut Window, &mut App) -> Self + 'static,
213 ) -> gpui::Result<Option<AnyWindowHandle>> {
214 let current = state.read(cx);
215 if current.is_open() {
216 return Ok(current.native.as_ref().map(|native| native.child));
217 }
218 let parent_handle = parent.window_handle();
219 if cx
220 .active_window()
221 .is_none_or(|active| active.window_id() != parent_handle.window_id())
222 {
223 return Err(std::io::Error::new(
224 std::io::ErrorKind::InvalidInput,
225 "the dialog's parent window must be active",
226 )
227 .into());
228 }
229 options.kind = WindowKind::Dialog;
230 options.focus = true;
231 options.show = true;
232 let previous = parent.focused(cx);
233 let theme = current_material_theme(parent, cx).clone();
234 let state = state.clone();
235 let window = MaterialRoot::open_window(options, cx, move |window, cx| {
236 set_window_material_theme(Some(theme), window, cx);
237 let child = window.window_handle();
238 let weak = state.downgrade();
239 let closed = cx.on_window_closed(move |cx, id| {
240 if id == child.window_id()
241 && let Some(state) = weak.upgrade()
242 {
243 state.update(cx, |state, cx| {
244 if let Some(native) = state.native.take() {
245 state.open = false;
246 state.last_close_reason = Some(DialogCloseReason::Programmatic);
247 restore_parent(native.parent, state.previous.take(), cx);
248 cx.notify();
249 }
250 });
251 }
252 });
253 state.update(cx, |state, cx| {
254 state.native = Some(NativeDialog {
255 parent: parent_handle,
256 child,
257 _closed: closed,
258 });
259 state.begin(previous, window, cx);
260 });
261 cx.new(|cx: &mut Context<NativeDialogView>| {
262 cx.observe(&state, |_, _, cx| cx.notify()).detach();
263 NativeDialogView {
264 state,
265 build: Box::new(build),
266 }
267 })
268 })?;
269 Ok(Some(window.into()))
270 }
271
272 pub fn variant(mut self, variant: DialogVariant) -> Self {
274 self.variant = variant;
275 self
276 }
277
278 pub fn icon(mut self, icon: impl IntoElement) -> Self {
280 self.icon = Some(icon.into_any_element());
281 self
282 }
283
284 pub fn title_content(mut self, title: impl IntoElement) -> Self {
286 self.title_content = Some(title.into_any_element());
287 self
288 }
289
290 pub fn show_title(mut self, show: bool) -> Self {
292 self.show_title = show;
293 self
294 }
295
296 pub fn description(mut self, description: impl Into<SharedString>) -> Self {
298 self.description = Some(description.into());
299 self
300 }
301
302 pub fn body(mut self, body: impl IntoElement) -> Self {
304 let body = body.into_any_element();
305 self.body = Some(Box::new(|_, _| body));
306 self
307 }
308
309 pub fn body_content<E: IntoElement>(
311 mut self,
312 body: impl FnOnce(DialogAction, DialogAction) -> E + 'static,
313 ) -> Self {
314 self.body = Some(Box::new(move |confirm, dismiss| {
315 body(confirm, dismiss).into_any_element()
316 }));
317 self
318 }
319
320 pub fn confirm(
322 mut self,
323 label: impl Into<SharedString>,
324 action: impl Fn(&mut Window, &mut App) -> bool + 'static,
325 ) -> Self {
326 self.confirm = Some((label.into(), Rc::new(action)));
327 self
328 }
329
330 pub fn on_confirm(
332 self,
333 label: impl Into<SharedString>,
334 action: impl Fn(&mut Window, &mut App) + 'static,
335 ) -> Self {
336 self.confirm(label, move |window, cx| {
337 action(window, cx);
338 true
339 })
340 }
341
342 pub fn confirm_tone(mut self, tone: SemanticTone) -> Self {
344 self.confirm_tone = tone;
345 self
346 }
347
348 pub fn confirm_disabled(mut self, disabled: bool) -> Self {
350 self.confirm_disabled = disabled;
351 self
352 }
353
354 pub fn confirm_loading(mut self, loading: bool) -> Self {
356 self.confirm_loading = loading;
357 self
358 }
359
360 pub fn confirm_content<E: IntoElement>(
362 mut self,
363 content: impl FnOnce(DialogAction) -> E + 'static,
364 ) -> Self {
365 self.confirm_content = Some(Box::new(move |confirm| content(confirm).into_any_element()));
366 self
367 }
368
369 pub fn dismiss_content<E: IntoElement>(
371 mut self,
372 content: impl FnOnce(DialogAction) -> E + 'static,
373 ) -> Self {
374 self.dismiss_content = Some(Box::new(move |dismiss| content(dismiss).into_any_element()));
375 self
376 }
377
378 pub fn cancel_label(mut self, label: impl Into<SharedString>) -> Self {
380 self.cancel = label.into();
381 self
382 }
383
384 pub fn show_cancel(mut self, show: bool) -> Self {
386 self.show_cancel = show;
387 self
388 }
389
390 pub fn layer(mut self, layer: usize) -> Self {
392 self.layer = layer;
393 self
394 }
395
396 pub fn properties(mut self, properties: DialogProperties) -> Self {
398 self.properties = properties;
399 self
400 }
401
402 pub fn on_dismiss_request(
404 mut self,
405 request: impl Fn(DialogCloseReason, &mut Window, &mut App) -> bool + 'static,
406 ) -> Self {
407 self.dismiss_request = Some(Rc::new(request));
408 self
409 }
410
411 pub fn on_closed(
413 mut self,
414 close: impl Fn(DialogCloseReason, &mut Window, &mut App) + 'static,
415 ) -> Self {
416 self.on_closed = Some(Rc::new(close));
417 self
418 }
419
420 pub fn shape(mut self, shape: CornerShape) -> Self {
422 self.shape = Some(shape);
423 self
424 }
425
426 pub fn colors(mut self, colors: DialogColors) -> Self {
428 self.colors = colors;
429 self
430 }
431
432 pub fn tonal_elevation(mut self, elevation: Elevation) -> Self {
434 self.tonal_elevation = Some(elevation);
435 self
436 }
437
438 pub fn shadow_elevation(mut self, elevation: Elevation) -> Self {
440 self.shadow_elevation = Some(elevation);
441 self
442 }
443
444 pub fn scrim_color(mut self, color: Hsla) -> Self {
446 self.scrim_color = Some(color);
447 self
448 }
449
450 pub fn scrim_opacity(mut self, opacity: f32) -> Self {
452 self.scrim_opacity = if opacity.is_nan() {
453 0.32
454 } else {
455 opacity.clamp(0., 1.)
456 };
457 self
458 }
459
460 pub fn width(mut self, width: Pixels) -> Self {
462 if f32::from(width).is_finite() {
463 self.width = width.max(px(0.));
464 }
465 self
466 }
467}