1use gpui::{
5 AnyElement, App, Context, Entity, EventEmitter, FocusHandle, InteractiveElement as _,
6 IntoElement, KeyBinding, MouseButton, ParentElement, RenderOnce, Role, SharedString,
7 StatefulInteractiveElement as _, StyleRefinement, Styled, WeakFocusHandle, Window, anchored,
8 deferred, div, point, prelude::FluentBuilder as _, px,
9};
10use smallvec::SmallVec;
11
12use crate::{FocusTrapElement as _, StyledExt as _, TestSupportExt as _, actions::Cancel};
13
14const CONTEXT: &str = "Dialog";
15
16#[derive(Clone, Copy, Debug, Eq, PartialEq)]
18pub enum DialogChangeReason {
19 Cancel,
20 BackdropPress,
21 CloseButton,
22 Imperative,
23}
24
25#[derive(Clone, Copy, Debug, Eq, PartialEq)]
27pub enum DialogEvent {
28 Opened,
29 Closed(DialogChangeReason),
30}
31
32pub struct DialogState {
39 open: bool,
40 focus: FocusHandle,
41 initial_focus: Option<FocusHandle>,
42 previous_focus: Option<WeakFocusHandle>,
43}
44
45impl DialogState {
46 pub fn new(cx: &mut Context<Self>) -> Self {
47 Self {
48 open: false,
49 focus: cx.focus_handle(),
50 initial_focus: None,
51 previous_focus: None,
52 }
53 }
54
55 pub fn with_initial_focus(mut self, focus: &FocusHandle) -> Self {
57 self.initial_focus = Some(focus.clone());
58 self
59 }
60
61 pub fn is_open(&self) -> bool {
62 self.open
63 }
64
65 pub fn focus_handle(&self) -> &FocusHandle {
66 &self.focus
67 }
68
69 pub fn open(&mut self, window: &mut Window, cx: &mut Context<Self>) {
70 if self.open {
71 return;
72 }
73 self.previous_focus = window.focused(cx).map(|focus| focus.downgrade());
74 self.open = true;
75 self.initial_focus
76 .as_ref()
77 .unwrap_or(&self.focus)
78 .focus(window, cx);
79 cx.emit(DialogEvent::Opened);
80 cx.notify();
81 window.refresh();
82 }
83
84 pub fn close(&mut self, window: &mut Window, cx: &mut Context<Self>) {
85 self.close_with_reason(DialogChangeReason::Imperative, window, cx);
86 }
87
88 fn close_with_reason(
89 &mut self,
90 reason: DialogChangeReason,
91 window: &mut Window,
92 cx: &mut Context<Self>,
93 ) {
94 if !self.open {
95 return;
96 }
97 self.open = false;
98 let owns_focus = self.focus.contains_focused(window, cx)
99 || self.focus.is_focused(window)
100 || self
102 .initial_focus
103 .as_ref()
104 .is_some_and(|focus| focus.is_focused(window));
105 let previous = self.previous_focus.take().and_then(|focus| focus.upgrade());
106 if owns_focus {
107 match previous {
108 Some(focus) => focus.focus(window, cx),
109 None => window.blur(cx),
110 }
111 }
112 cx.emit(DialogEvent::Closed(reason));
113 cx.notify();
114 window.refresh();
115 }
116}
117
118impl EventEmitter<DialogEvent> for DialogState {}
119
120pub(crate) fn init(cx: &mut App) {
121 cx.bind_keys([KeyBinding::new("escape", Cancel, Some(CONTEXT))]);
122}
123
124#[derive(IntoElement)]
130pub struct Dialog {
131 state: Entity<DialogState>,
132 style: StyleRefinement,
133 label: Option<SharedString>,
134 description: Option<SharedString>,
135 role: Role,
136 keyboard: bool,
137 overlay_closable: bool,
138 backdrop: Option<AnyElement>,
139 popup: Option<AnyElement>,
140}
141
142impl Dialog {
143 pub fn new(state: &Entity<DialogState>) -> Self {
144 Self {
145 state: state.clone(),
146 style: StyleRefinement::default(),
147 label: None,
148 description: None,
149 role: Role::Dialog,
150 keyboard: true,
151 overlay_closable: true,
152 backdrop: None,
153 popup: None,
154 }
155 }
156
157 pub fn accessibility_label(mut self, label: impl Into<SharedString>) -> Self {
158 self.label = Some(label.into());
159 self
160 }
161
162 pub fn accessibility_description(mut self, description: impl Into<SharedString>) -> Self {
163 self.description = Some(description.into());
164 self
165 }
166
167 pub(crate) fn role(mut self, role: Role) -> Self {
169 self.role = role;
170 self
171 }
172
173 pub fn backdrop(mut self, element: impl IntoElement) -> Self {
174 self.backdrop = Some(element.into_any_element());
175 self
176 }
177
178 pub fn popup(mut self, element: impl IntoElement) -> Self {
179 self.popup = Some(element.into_any_element());
180 self
181 }
182
183 pub fn close_on_escape(mut self, close: bool) -> Self {
184 self.keyboard = close;
185 self
186 }
187
188 pub fn close_on_backdrop_press(mut self, close: bool) -> Self {
189 self.overlay_closable = close;
190 self
191 }
192}
193
194impl Styled for Dialog {
195 fn style(&mut self) -> &mut StyleRefinement {
196 &mut self.style
197 }
198}
199
200impl RenderOnce for Dialog {
201 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
202 if !self.state.read(cx).is_open() {
203 return div().into_any_element();
204 }
205 let focus = self.state.read(cx).focus_handle().clone();
206 let entity_id = self.state.entity_id();
207 let viewport = window.viewport_size();
208 let escape_state = self.state.clone();
209 let backdrop_state = self.state;
210 let overlay_closable = self.overlay_closable;
211
212 let host = div()
213 .id(("dialog", entity_id))
214 .absolute()
215 .top_0()
216 .left_0()
217 .w(viewport.width)
218 .h(viewport.height)
219 .flex()
220 .items_center()
221 .justify_center()
222 .occlude()
223 .role(self.role)
224 .when_some(self.label, |this, label| this.aria_label(label))
225 .when_some(self.description, |this, description| {
226 this.aria_description(description)
227 })
228 .focus_trap(("dialog", entity_id), &focus)
229 .when(self.keyboard, |this| {
230 this.key_context(CONTEXT)
231 .on_action(move |_: &Cancel, window, cx| {
232 cx.stop_propagation();
233 escape_state.update(cx, |state, cx| {
234 state.close_with_reason(DialogChangeReason::Cancel, window, cx);
235 });
236 })
237 })
238 .when_some(self.backdrop, |this, backdrop| {
239 this.child(
240 div()
241 .absolute()
242 .inset_0()
243 .on_scroll(|_, _, cx| cx.stop_propagation())
244 .on_any_mouse_down(move |event, window, cx| {
245 cx.stop_propagation();
246 if event.button == MouseButton::Left && overlay_closable {
247 backdrop_state.update(cx, |state, cx| {
248 state.close_with_reason(
249 DialogChangeReason::BackdropPress,
250 window,
251 cx,
252 );
253 });
254 }
255 })
256 .child(backdrop),
257 )
258 })
259 .children(self.popup)
260 .refine_style(&self.style);
261 let host = crate::a11y_disabled::A11yDisabled::new(host, false)
262 .with_modal(true)
263 .test_support()
264 .track_focus(&focus);
265
266 deferred(anchored().position(point(px(0.), px(0.))).child(host))
267 .with_priority(10)
268 .into_any_element()
269 }
270}
271
272macro_rules! dialog_part {
273 ($(#[$meta:meta])* $name:ident, $id:literal, $occlude:literal) => {
274 $(#[$meta])*
275 #[derive(IntoElement)]
276 pub struct $name {
277 style: StyleRefinement,
278 children: SmallVec<[AnyElement; 2]>,
279 }
280
281 impl $name {
282 pub fn new() -> Self {
283 Self {
284 style: StyleRefinement::default(),
285 children: SmallVec::new(),
286 }
287 }
288 }
289
290 impl Default for $name {
291 fn default() -> Self {
292 Self::new()
293 }
294 }
295
296 impl Styled for $name {
297 fn style(&mut self) -> &mut StyleRefinement {
298 &mut self.style
299 }
300 }
301
302 impl ParentElement for $name {
303 fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
304 self.children.extend(elements);
305 }
306 }
307
308 impl RenderOnce for $name {
309 fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
310 div()
311 .id($id)
312 .test_support()
313 .when($occlude, |this| this.occlude())
314 .children(self.children)
315 .refine_style(&self.style)
316 }
317 }
318 };
319}
320
321dialog_part!(
322 DialogBackdrop,
324 "dialog-backdrop",
325 false
326);
327dialog_part!(
328 DialogPopup,
330 "dialog-popup",
331 true
332);
333dialog_part!(
334 DialogTitle,
336 "dialog-title",
337 false
338);
339dialog_part!(
340 DialogDescription,
342 "dialog-description",
343 false
344);
345
346#[derive(IntoElement)]
348pub struct DialogClose {
349 state: Entity<DialogState>,
350 trigger: Option<AnyElement>,
351}
352
353impl DialogClose {
354 pub fn new(state: &Entity<DialogState>) -> Self {
355 Self {
356 state: state.clone(),
357 trigger: None,
358 }
359 }
360
361 pub fn trigger<E: IntoElement>(mut self, build: impl FnOnce(crate::Button) -> E) -> Self {
363 let state = self.state.clone();
364 self.trigger = Some(
365 build(
366 crate::Button::new(("dialog-close", state.entity_id()))
367 .accessibility_label("Close")
368 .on_click(move |_, window, cx| {
369 state.update(cx, |state, cx| {
370 state.close_with_reason(DialogChangeReason::CloseButton, window, cx);
371 });
372 }),
373 )
374 .into_any_element(),
375 );
376 self
377 }
378}
379
380impl RenderOnce for DialogClose {
381 fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
382 div().children(self.trigger)
383 }
384}
385
386#[cfg(test)]
387mod tests {
388 use std::{cell::Cell, rc::Rc};
389
390 use gpui::{
391 AppContext as _, Modifiers, Render, ScrollDelta, ScrollEvent, ScrollHandle, TestAppContext,
392 };
393
394 use super::*;
395 use crate::{Button, Root, ScrollArea};
396
397 struct NoBackdropHarness {
398 dialog: Entity<DialogState>,
399 background_activations: Rc<Cell<usize>>,
400 background_scrolls: Rc<Cell<usize>>,
401 popup_activations: Rc<Cell<usize>>,
402 }
403
404 impl Render for NoBackdropHarness {
405 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
406 let background = self.background_activations.clone();
407 let background_scrolls = self.background_scrolls.clone();
408 let popup = self.popup_activations.clone();
409 div()
410 .size_full()
411 .child(
412 Button::new("background-button")
413 .size_full()
414 .on_scroll(move |_, _, _| {
415 background_scrolls.set(background_scrolls.get() + 1)
416 })
417 .on_click(move |_, _, _| background.set(background.get() + 1)),
418 )
419 .child(
420 Dialog::new(&self.dialog)
421 .accessibility_label("Undecorated dialog")
422 .popup(
423 DialogPopup::new().w(px(200.)).h(px(120.)).child(
424 Button::new("popup-button")
425 .size_full()
426 .on_click(move |_, _, _| popup.set(popup.get() + 1)),
427 ),
428 ),
429 )
430 }
431 }
432
433 #[gpui::test]
434 fn modal_without_a_backdrop_blocks_background_pointer_activation(cx: &mut TestAppContext) {
435 cx.update(crate::init);
436 let dialog = cx.new(DialogState::new);
437 let background_activations = Rc::new(Cell::new(0));
438 let background_scrolls = Rc::new(Cell::new(0));
439 let popup_activations = Rc::new(Cell::new(0));
440 let (_, cx) = cx.add_window_view({
441 let dialog = dialog.clone();
442 let background_activations = background_activations.clone();
443 let background_scrolls = background_scrolls.clone();
444 let popup_activations = popup_activations.clone();
445 move |window, cx| {
446 let content = cx.new(|_| NoBackdropHarness {
447 dialog,
448 background_activations,
449 background_scrolls,
450 popup_activations,
451 });
452 Root::new(content, window, cx)
453 }
454 });
455 cx.update(|window, cx| window.draw(cx).clear(cx));
456
457 let background_position = point(px(8.), px(8.));
458 cx.simulate_click(background_position, Modifiers::default());
459 assert_eq!(background_activations.get(), 1);
460 let wheel = || ScrollEvent {
461 position: background_position,
462 delta: ScrollDelta::Pixels(point(px(0.), px(-20.))),
463 ..Default::default()
464 };
465 cx.simulate_event(wheel());
466 assert_eq!(background_scrolls.get(), 1);
467 cx.update(|window, cx| {
468 dialog.update(cx, |state, cx| state.open(window, cx));
469 window.draw(cx).clear(cx);
470 });
471 cx.simulate_click(background_position, Modifiers::default());
472 cx.update(|window, cx| {
473 window.draw(cx).clear(cx);
474 assert!(dialog.read(cx).is_open());
475 });
476 assert_eq!(background_activations.get(), 1);
477 cx.simulate_event(wheel());
478 assert_eq!(
479 background_scrolls.get(),
480 1,
481 "the undecorated modal also blocks background wheel input"
482 );
483
484 let popup_position = cx.update(|window, _| {
485 let viewport = window.viewport_size();
486 point(viewport.width / 2., viewport.height / 2.)
487 });
488 cx.simulate_click(popup_position, Modifiers::default());
489 assert_eq!(popup_activations.get(), 1);
490 #[cfg(feature = "test-support")]
491 cx.update(|window, _| {
492 let node =
493 crate::test_support::find(window, &[], &("dialog", dialog.entity_id()).into())
494 .unwrap();
495 assert_eq!(node.role(), Some(Role::Dialog));
496 assert!(node.modal());
497 });
498 }
499
500 struct ScrollIsolationHarness {
501 dialog: Entity<DialogState>,
502 background: ScrollHandle,
503 body: ScrollHandle,
504 background_presses: Rc<Cell<usize>>,
505 }
506
507 impl Render for ScrollIsolationHarness {
508 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
509 let background_presses = self.background_presses.clone();
510 div()
511 .size_full()
512 .child(
513 ScrollArea::new("background", &self.background)
514 .size_full()
515 .child(div().w_full().h(px(2000.)).flex_shrink_0().on_mouse_down(
516 MouseButton::Left,
517 move |_, _, _| {
518 background_presses.set(background_presses.get() + 1);
519 },
520 )),
521 )
522 .child(
523 Dialog::new(&self.dialog)
524 .accessibility_label("Scroll isolation")
525 .backdrop(DialogBackdrop::new().size_full())
526 .popup(
527 DialogPopup::new().w(px(200.)).h(px(120.)).child(
528 ScrollArea::new("dialog-body", &self.body)
529 .size_full()
530 .child(div().w_full().h(px(400.)).flex_shrink_0()),
531 ),
532 ),
533 )
534 }
535 }
536
537 #[gpui::test]
538 fn modal_wheel_isolation_preserves_body_scrolling_and_backdrop_dismissal(
539 cx: &mut TestAppContext,
540 ) {
541 cx.update(crate::init);
542 let dialog = cx.new(DialogState::new);
543 let background = ScrollHandle::new();
544 let body = ScrollHandle::new();
545 let background_presses = Rc::new(Cell::new(0));
546 let (_, cx) = cx.add_window_view({
547 let dialog = dialog.clone();
548 let background = background.clone();
549 let body = body.clone();
550 let background_presses = background_presses.clone();
551 move |window, cx| {
552 let content = cx.new(|_| ScrollIsolationHarness {
553 dialog,
554 background,
555 body,
556 background_presses,
557 });
558 Root::new(content, window, cx)
559 }
560 });
561 cx.update(|window, cx| window.draw(cx).clear(cx));
562
563 let backdrop_position = point(
564 background.bounds().left() + px(8.),
565 background.bounds().top() + px(8.),
566 );
567 let wheel_down = point(px(0.), px(-40.));
568
569 cx.simulate_event(ScrollEvent {
572 position: backdrop_position,
573 delta: ScrollDelta::Pixels(wheel_down),
574 ..Default::default()
575 });
576 cx.update(|window, cx| window.draw(cx).clear(cx));
577 let background_offset = background.offset();
578 assert_eq!(background_offset, wheel_down);
579
580 cx.update(|window, cx| {
581 dialog.update(cx, |state, cx| state.open(window, cx));
582 window.draw(cx).clear(cx);
583 });
584 assert!(!body.bounds().contains(&backdrop_position));
585
586 cx.simulate_event(ScrollEvent {
587 position: body.bounds().center(),
588 delta: ScrollDelta::Pixels(wheel_down),
589 ..Default::default()
590 });
591 cx.update(|window, cx| window.draw(cx).clear(cx));
592 assert_eq!(body.offset(), wheel_down);
593 assert_eq!(background.offset(), background_offset);
594
595 let body_end = point(px(0.), -body.max_offset().y);
597 body.set_offset(body_end);
598 cx.update(|window, cx| window.draw(cx).clear(cx));
599 cx.simulate_event(ScrollEvent {
600 position: body.bounds().center(),
601 delta: ScrollDelta::Pixels(wheel_down),
602 ..Default::default()
603 });
604 cx.update(|window, cx| window.draw(cx).clear(cx));
605 assert_eq!(body.offset(), body_end);
606 assert_eq!(background.offset(), background_offset);
607
608 cx.simulate_event(ScrollEvent {
609 position: backdrop_position,
610 delta: ScrollDelta::Pixels(wheel_down),
611 ..Default::default()
612 });
613 cx.update(|window, cx| window.draw(cx).clear(cx));
614 let background_after_backdrop_wheel = background.offset();
615 assert_eq!(body.offset(), body_end);
616
617 cx.simulate_click(backdrop_position, Modifiers::default());
620 cx.update(|window, cx| {
621 window.draw(cx).clear(cx);
622 assert!(!dialog.read(cx).is_open());
623 });
624 assert_eq!(background_presses.get(), 0);
625 assert_eq!(
626 background_after_backdrop_wheel, background_offset,
627 "a wheel over the modal backdrop must not move the background"
628 );
629 }
630}