Skip to main content

gpui_component/dialog/
entrance.rs

1use gpui::{
2    AnyElement, App, Bounds, Element, ElementId, GlobalElementId, InspectorElementId, LayoutId,
3    Pixels, Window, point, px,
4};
5use serde::{Deserialize, Serialize};
6
7/// The entrance presentation shared by Dialog and AlertDialog.
8///
9/// Closing animates the surface and backdrop back out. Reduced motion displays
10/// the final state for every option, and [`DialogEntrance::None`] opens and
11/// closes in a single frame.
12#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
13#[non_exhaustive]
14pub enum DialogEntrance {
15    /// Slide down from the window top while fading in, preserving the legacy entrance.
16    #[default]
17    SlideDown,
18    /// Fade in at the final position without movement.
19    Fade,
20    /// Fade in while settling from just above the final position.
21    ///
22    /// Travel comes from the theme's short motion distance and is limited by
23    /// the space above the resolved surface inside the window.
24    FadeSlide,
25    /// Show the surface and backdrop immediately without entrance animation.
26    None,
27}
28
29/// Applies presentation travel after Positioner has resolved the resting bounds.
30/// Paint, hit testing, and accessibility follow the same offset.
31pub(super) struct EntranceSurface {
32    child: AnyElement,
33    travel: Pixels,
34    top_limit: Pixels,
35    pub(super) progress: f32,
36}
37
38impl EntranceSurface {
39    pub(super) fn new(child: AnyElement, travel: Pixels, top_limit: Pixels) -> Self {
40        Self {
41            child,
42            travel,
43            top_limit,
44            progress: 0.,
45        }
46    }
47}
48
49#[cfg(not(feature = "gpui-fast"))]
50impl gpui::IntoElement for EntranceSurface {
51    type Element = Self;
52
53    fn into_element(self) -> Self::Element {
54        self
55    }
56}
57
58impl Element for EntranceSurface {
59    type RequestLayoutState = ();
60    type PrepaintState = ();
61
62    fn id(&self) -> Option<ElementId> {
63        None
64    }
65
66    fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
67        None
68    }
69
70    fn request_layout(
71        &mut self,
72        _: Option<&GlobalElementId>,
73        _: Option<&InspectorElementId>,
74        window: &mut Window,
75        cx: &mut App,
76    ) -> (LayoutId, ()) {
77        (self.child.request_layout(window, cx), ())
78    }
79
80    fn prepaint(
81        &mut self,
82        _: Option<&GlobalElementId>,
83        _: Option<&InspectorElementId>,
84        bounds: Bounds<Pixels>,
85        _: &mut (),
86        window: &mut Window,
87        cx: &mut App,
88    ) {
89        let available = (bounds.top() - self.top_limit).max(px(0.));
90        let travel = self.travel.max(px(0.)).min(available);
91        let offset = point(px(0.), -travel * (1. - self.progress.clamp(0., 1.)));
92        window.with_element_offset(offset, |window| self.child.prepaint(window, cx));
93    }
94
95    fn paint(
96        &mut self,
97        _: Option<&GlobalElementId>,
98        _: Option<&InspectorElementId>,
99        _: Bounds<Pixels>,
100        _: &mut (),
101        _: &mut (),
102        window: &mut Window,
103        cx: &mut App,
104    ) {
105        self.child.paint(window, cx);
106    }
107}
108
109#[cfg(test)]
110mod tests {
111    use super::*;
112    use gpui::IntoElement as _;
113    use gpui::{
114        Anchor, Context, InteractiveElement as _, ParentElement as _, Render,
115        StatefulInteractiveElement as _, Styled as _, TestAppContext, div, size,
116    };
117
118    struct SurfaceProbe {
119        progress: f32,
120        requested_y: Pixels,
121        clicks: usize,
122    }
123
124    impl Render for SurfaceProbe {
125        fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl gpui::IntoElement {
126            let mut surface = EntranceSurface::new(
127                div()
128                    .id("surface")
129                    .w(px(200.))
130                    .h(px(300.))
131                    .debug_selector(|| "entrance-surface".into())
132                    .on_click(cx.listener(|probe, _, _, _| probe.clicks += 1))
133                    .into_any_element(),
134                px(8.),
135                px(16.),
136            );
137            surface.progress = self.progress;
138            div().size_full().child(
139                gpui_base::Positioner::corner(Anchor::TopLeft, point(px(100.), self.requested_y))
140                    .margin(px(16.))
141                    .child(surface),
142            )
143        }
144    }
145
146    #[gpui::test]
147    fn fade_slide_uses_resolved_bounds_and_keeps_the_surface_inside_the_window(
148        cx: &mut TestAppContext,
149    ) {
150        let (view, cx) = cx.add_window_view(|_, _| SurfaceProbe {
151            progress: 0.,
152            requested_y: px(200.),
153            clicks: 0,
154        });
155        cx.simulate_resize(size(px(400.), px(400.)));
156        // Requested y=200 resolves to y=84 because the surface is 300px tall.
157        for (requested_y, positions) in [
158            (px(200.), [px(76.), px(80.), px(84.)]),
159            (px(20.), [px(16.), px(18.), px(20.)]),
160            (px(0.), [px(16.), px(16.), px(16.)]),
161        ] {
162            for (progress, expected_y) in [0., 0.5, 1.].into_iter().zip(positions) {
163                cx.update(|window, cx| {
164                    view.update(cx, |probe, cx| {
165                        probe.progress = progress;
166                        probe.requested_y = requested_y;
167                        cx.notify();
168                    });
169                    window.draw(cx).clear(cx);
170                });
171                let bounds = cx.debug_bounds("entrance-surface").unwrap();
172                assert_eq!(bounds.top(), expected_y);
173                assert!(bounds.top() >= px(16.) && bounds.bottom() <= px(384.));
174                // At the beginning of the clamped entrance this point is
175                // above the resting surface, so the hitbox must travel too.
176                cx.simulate_click(bounds.origin + point(px(10.), px(2.)), Default::default());
177            }
178        }
179        cx.update(|_, cx| assert_eq!(view.read(cx).clicks, 9));
180    }
181}