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
49impl Element for EntranceSurface {
50    type RequestLayoutState = ();
51    type PrepaintState = ();
52
53    fn id(&self) -> Option<ElementId> {
54        None
55    }
56
57    fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
58        None
59    }
60
61    fn request_layout(
62        &mut self,
63        _: Option<&GlobalElementId>,
64        _: Option<&InspectorElementId>,
65        window: &mut Window,
66        cx: &mut App,
67    ) -> (LayoutId, ()) {
68        (self.child.request_layout(window, cx), ())
69    }
70
71    fn prepaint(
72        &mut self,
73        _: Option<&GlobalElementId>,
74        _: Option<&InspectorElementId>,
75        bounds: Bounds<Pixels>,
76        _: &mut (),
77        window: &mut Window,
78        cx: &mut App,
79    ) {
80        let available = (bounds.top() - self.top_limit).max(px(0.));
81        let travel = self.travel.max(px(0.)).min(available);
82        let offset = point(px(0.), -travel * (1. - self.progress.clamp(0., 1.)));
83        window.with_element_offset(offset, |window| self.child.prepaint(window, cx));
84    }
85
86    fn paint(
87        &mut self,
88        _: Option<&GlobalElementId>,
89        _: Option<&InspectorElementId>,
90        _: Bounds<Pixels>,
91        _: &mut (),
92        _: &mut (),
93        window: &mut Window,
94        cx: &mut App,
95    ) {
96        self.child.paint(window, cx);
97    }
98}
99
100#[cfg(test)]
101mod tests {
102    use super::*;
103    use gpui::IntoElement as _;
104    use gpui::{
105        Anchor, Context, InteractiveElement as _, ParentElement as _, Render,
106        StatefulInteractiveElement as _, Styled as _, TestAppContext, div, size,
107    };
108
109    struct SurfaceProbe {
110        progress: f32,
111        requested_y: Pixels,
112        clicks: usize,
113    }
114
115    impl Render for SurfaceProbe {
116        fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl gpui::IntoElement {
117            let mut surface = EntranceSurface::new(
118                div()
119                    .id("surface")
120                    .w(px(200.))
121                    .h(px(300.))
122                    .debug_selector(|| "entrance-surface".into())
123                    .on_click(cx.listener(|probe, _, _, _| probe.clicks += 1))
124                    .into_any_element(),
125                px(8.),
126                px(16.),
127            );
128            surface.progress = self.progress;
129            div().size_full().child(
130                gpui_base::Positioner::corner(Anchor::TopLeft, point(px(100.), self.requested_y))
131                    .margin(px(16.))
132                    .child(surface),
133            )
134        }
135    }
136
137    #[gpui::test]
138    fn fade_slide_uses_resolved_bounds_and_keeps_the_surface_inside_the_window(
139        cx: &mut TestAppContext,
140    ) {
141        let (view, cx) = cx.add_window_view(|_, _| SurfaceProbe {
142            progress: 0.,
143            requested_y: px(200.),
144            clicks: 0,
145        });
146        cx.simulate_resize(size(px(400.), px(400.)));
147        // Requested y=200 resolves to y=84 because the surface is 300px tall.
148        for (requested_y, positions) in [
149            (px(200.), [px(76.), px(80.), px(84.)]),
150            (px(20.), [px(16.), px(18.), px(20.)]),
151            (px(0.), [px(16.), px(16.), px(16.)]),
152        ] {
153            for (progress, expected_y) in [0., 0.5, 1.].into_iter().zip(positions) {
154                cx.update(|window, cx| {
155                    view.update(cx, |probe, cx| {
156                        probe.progress = progress;
157                        probe.requested_y = requested_y;
158                        cx.notify();
159                    });
160                    window.draw(cx).clear(cx);
161                });
162                let bounds = cx.debug_bounds("entrance-surface").unwrap();
163                assert_eq!(bounds.top(), expected_y);
164                assert!(bounds.top() >= px(16.) && bounds.bottom() <= px(384.));
165                // At the beginning of the clamped entrance this point is
166                // above the resting surface, so the hitbox must travel too.
167                cx.simulate_click(bounds.origin + point(px(10.), px(2.)), Default::default());
168            }
169        }
170        cx.update(|_, cx| assert_eq!(view.read(cx).clicks, 9));
171    }
172}