modal_layer.rs

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