modal_layer.rs

  1use gpui::{
  2    AnyView, DismissEvent, Entity, EventEmitter, FocusHandle, Focusable as _, ManagedView,
  3    MouseButton, Subscription,
  4};
  5use ui::prelude::*;
  6
  7#[derive(Debug)]
  8pub enum DismissDecision {
  9    Dismiss(bool),
 10    Pending,
 11}
 12
 13pub trait ModalView: ManagedView {
 14    fn on_before_dismiss(
 15        &mut self,
 16        _window: &mut Window,
 17        _: &mut Context<Self>,
 18    ) -> DismissDecision {
 19        DismissDecision::Dismiss(true)
 20    }
 21
 22    fn fade_out_background(&self) -> bool {
 23        false
 24    }
 25
 26    fn render_bare(&self) -> bool {
 27        false
 28    }
 29}
 30
 31trait ModalViewHandle {
 32    fn on_before_dismiss(&mut self, window: &mut Window, cx: &mut App) -> DismissDecision;
 33    fn view(&self) -> AnyView;
 34    fn fade_out_background(&self, cx: &mut App) -> bool;
 35    fn render_bare(&self, cx: &mut App) -> bool;
 36}
 37
 38impl<V: ModalView> ModalViewHandle for Entity<V> {
 39    fn on_before_dismiss(&mut self, window: &mut Window, cx: &mut App) -> DismissDecision {
 40        self.update(cx, |this, cx| this.on_before_dismiss(window, cx))
 41    }
 42
 43    fn view(&self) -> AnyView {
 44        self.clone().into()
 45    }
 46
 47    fn fade_out_background(&self, cx: &mut App) -> bool {
 48        self.read(cx).fade_out_background()
 49    }
 50
 51    fn render_bare(&self, cx: &mut App) -> bool {
 52        self.read(cx).render_bare()
 53    }
 54}
 55
 56pub struct ActiveModal {
 57    modal: Box<dyn ModalViewHandle>,
 58    _subscriptions: [Subscription; 2],
 59    previous_focus_handle: Option<FocusHandle>,
 60    focus_handle: FocusHandle,
 61}
 62
 63pub struct ModalLayer {
 64    active_modal: Option<ActiveModal>,
 65    dismiss_on_focus_lost: bool,
 66}
 67
 68pub(crate) struct ModalOpenedEvent;
 69
 70impl EventEmitter<ModalOpenedEvent> for ModalLayer {}
 71
 72impl Default for ModalLayer {
 73    fn default() -> Self {
 74        Self::new()
 75    }
 76}
 77
 78impl ModalLayer {
 79    pub fn new() -> Self {
 80        Self {
 81            active_modal: None,
 82            dismiss_on_focus_lost: false,
 83        }
 84    }
 85
 86    pub fn toggle_modal<V, B>(&mut self, window: &mut Window, cx: &mut Context<Self>, build_view: B)
 87    where
 88        V: ModalView,
 89        B: FnOnce(&mut Window, &mut Context<V>) -> V,
 90    {
 91        if let Some(active_modal) = &self.active_modal {
 92            let is_close = active_modal.modal.view().downcast::<V>().is_ok();
 93            let did_close = self.hide_modal(window, cx);
 94            if is_close || !did_close {
 95                return;
 96            }
 97        }
 98        let new_modal = cx.new(|cx| build_view(window, cx));
 99        self.show_modal(new_modal, window, cx);
100        cx.emit(ModalOpenedEvent);
101    }
102
103    fn show_modal<V>(&mut self, new_modal: Entity<V>, window: &mut Window, cx: &mut Context<Self>)
104    where
105        V: ModalView,
106    {
107        let focus_handle = cx.focus_handle();
108        self.active_modal = Some(ActiveModal {
109            modal: Box::new(new_modal.clone()),
110            _subscriptions: [
111                cx.subscribe_in(
112                    &new_modal,
113                    window,
114                    |this, _, _: &DismissEvent, window, cx| {
115                        this.hide_modal(window, cx);
116                    },
117                ),
118                cx.on_focus_out(&focus_handle, window, |this, _event, window, cx| {
119                    if this.dismiss_on_focus_lost {
120                        this.hide_modal(window, cx);
121                    }
122                }),
123            ],
124            previous_focus_handle: window.focused(cx),
125            focus_handle,
126        });
127        cx.defer_in(window, move |_, window, cx| {
128            window.focus(&new_modal.focus_handle(cx), cx);
129        });
130        cx.notify();
131    }
132
133    pub fn hide_modal(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
134        let Some(active_modal) = self.active_modal.as_mut() else {
135            self.dismiss_on_focus_lost = false;
136            return false;
137        };
138
139        match active_modal.modal.on_before_dismiss(window, cx) {
140            DismissDecision::Dismiss(dismiss) => {
141                self.dismiss_on_focus_lost = !dismiss;
142                if !dismiss {
143                    return false;
144                }
145            }
146            DismissDecision::Pending => {
147                self.dismiss_on_focus_lost = false;
148                return false;
149            }
150        }
151
152        if let Some(active_modal) = self.active_modal.take() {
153            if let Some(previous_focus) = active_modal.previous_focus_handle
154                && active_modal.focus_handle.contains_focused(window, cx)
155            {
156                previous_focus.focus(window, cx);
157            }
158            cx.notify();
159        }
160        true
161    }
162
163    pub fn active_modal<V>(&self) -> Option<Entity<V>>
164    where
165        V: 'static,
166    {
167        let active_modal = self.active_modal.as_ref()?;
168        active_modal.modal.view().downcast::<V>().ok()
169    }
170
171    pub fn has_active_modal(&self) -> bool {
172        self.active_modal.is_some()
173    }
174}
175
176impl Render for ModalLayer {
177    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
178        let Some(active_modal) = &self.active_modal else {
179            return div().into_any_element();
180        };
181
182        if active_modal.modal.render_bare(cx) {
183            return active_modal.modal.view().into_any_element();
184        }
185
186        div()
187            .absolute()
188            .size_full()
189            .inset_0()
190            .occlude()
191            .when(active_modal.modal.fade_out_background(cx), |this| {
192                let mut background = cx.theme().colors().elevated_surface_background;
193                background.fade_out(0.2);
194                this.bg(background)
195            })
196            .child(
197                v_flex()
198                    .h(px(0.0))
199                    .top_20()
200                    .items_center()
201                    .track_focus(&active_modal.focus_handle)
202                    .child(
203                        h_flex()
204                            .occlude()
205                            .child(active_modal.modal.view())
206                            .on_mouse_down(MouseButton::Left, |_, _, cx| {
207                                cx.stop_propagation();
208                            }),
209                    ),
210            )
211            .into_any_element()
212    }
213}