Skip to main content

gpui_material_extras/carousel/
parallax.rs

1use gpui::{
2    AnyElement, App, Axis, BorderStyle, Bounds, ContentMask, Corners, Element, ElementId,
3    GlobalElementId, Hsla, InspectorElementId, IntoElement, LayoutId, PathBuilder, Pixels, Point,
4    Window, point, px, quad, size,
5};
6use gpui_material_foundation::{SurfaceBorder, color, current_material_theme};
7use gpui_material_theme::{ColorRole, CornerRole, CornerShape};
8
9/// Clips and translates arbitrary scrollable content at the viewport edges.
10///
11/// The element keeps its original layout size and clips to the current GPUI
12/// content mask or an explicit viewport. Rounded corners use an opaque
13/// backdrop because GPUI's content masks are rectangular.
14pub struct CarouselParallax {
15    child: AnyElement,
16    axis: Axis,
17    viewport: Option<Bounds<Pixels>>,
18    shape: CornerShape,
19    border: Option<SurfaceBorder>,
20    backdrop: Option<Hsla>,
21}
22
23impl CarouselParallax {
24    /// Wraps `content` in a horizontal parallax mask using [`CornerRole::ExtraLarge`] corners.
25    pub fn new(content: impl IntoElement) -> Self {
26        Self {
27            child: content.into_any_element(),
28            axis: Axis::Horizontal,
29            viewport: None,
30            shape: CornerRole::ExtraLarge.shape(),
31            border: None,
32            backdrop: None,
33        }
34    }
35
36    /// Sets the scroll axis along which edge cropping and parallax translation apply.
37    pub fn axis(mut self, axis: Axis) -> Self {
38        self.axis = axis;
39        self
40    }
41
42    /// Overrides the effect viewport with bounds in window coordinates.
43    pub fn viewport(mut self, viewport: Bounds<Pixels>) -> Self {
44        self.viewport = Some(viewport);
45        self
46    }
47
48    /// Sets the corner shape used to mask the cropped content.
49    pub fn shape(mut self, shape: CornerShape) -> Self {
50        self.shape = shape;
51        self
52    }
53
54    /// Draws an inner border stroke around the masked region.
55    pub fn border(mut self, border: SurfaceBorder) -> Self {
56        self.border = Some(border);
57        self
58    }
59
60    /// Matches the opaque color of the scroll viewport behind rounded corners.
61    /// The window theme's Surface color is used by default.
62    pub fn backdrop(mut self, backdrop: Hsla) -> Self {
63        self.backdrop = Some(Hsla { a: 1., ..backdrop });
64        self
65    }
66}
67
68struct Mask {
69    bounds: Bounds<Pixels>,
70    offset: Point<Pixels>,
71}
72
73impl Mask {
74    fn new(
75        item: Bounds<Pixels>,
76        viewport: Bounds<Pixels>,
77        axis: Axis,
78        reduce_motion: bool,
79    ) -> Self {
80        let (start, end, clip_start, clip_end, cross) = match axis {
81            Axis::Horizontal => (
82                item.left(),
83                item.right(),
84                viewport.left(),
85                viewport.right(),
86                item.size.height,
87            ),
88            Axis::Vertical => (
89                item.top(),
90                item.bottom(),
91                viewport.top(),
92                viewport.bottom(),
93                item.size.width,
94            ),
95        };
96        let extent = end - start;
97        let mut crop_start = px(0.);
98        let mut crop_end = px(0.);
99        let mut translate = px(0.);
100        if !reduce_motion && extent > px(0.) && cross > px(0.) {
101            let ratio = f32::from(extent) / f32::from(cross);
102            let lerp = |a: f32, b: f32, lo, hi| {
103                let progress: f32 = (ratio - lo) / (hi - lo);
104                a + (b - a) * progress.clamp(0., 1.)
105            };
106            let intensity = if ratio < 1. {
107                lerp(0.25, 1. / 3., 9. / 16., 1.)
108            } else {
109                lerp(1. / 3., 0.5, 1., 16. / 9.)
110            };
111            // Recenter part of the content as either viewport edge crops it.
112            // Evaluate both edges independently so items wider than the viewport
113            // clip on both sides rather than leaving the trailing edge unclipped.
114            if start < clip_start {
115                let distance = (clip_start - start).min(extent);
116                crop_start = distance * (1. - intensity);
117                translate += distance * intensity;
118            }
119            if end > clip_end {
120                let distance = (end - clip_end).min(extent);
121                crop_end = distance * (1. - intensity);
122                translate -= distance * intensity;
123            }
124        }
125        let cropped_extent = (extent - crop_start - crop_end).max(px(0.));
126        let (crop, cropped_size, offset) = match axis {
127            Axis::Horizontal => (
128                point(crop_start, px(0.)),
129                size(cropped_extent, item.size.height),
130                point(translate, px(0.)),
131            ),
132            Axis::Vertical => (
133                point(px(0.), crop_start),
134                size(item.size.width, cropped_extent),
135                point(px(0.), translate),
136            ),
137        };
138        Self {
139            bounds: Bounds::new(item.origin + crop, cropped_size),
140            offset,
141        }
142    }
143}
144
145/// Layout and clip resolved against the scroll viewport for one draw.
146#[doc(hidden)]
147pub struct CarouselParallaxPaint {
148    mask: Bounds<Pixels>,
149    clip: Bounds<Pixels>,
150}
151
152impl Element for CarouselParallax {
153    type RequestLayoutState = ();
154    type PrepaintState = Option<CarouselParallaxPaint>;
155
156    fn id(&self) -> Option<ElementId> {
157        None
158    }
159
160    fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
161        None
162    }
163
164    fn request_layout(
165        &mut self,
166        _: Option<&GlobalElementId>,
167        _: Option<&InspectorElementId>,
168        window: &mut Window,
169        cx: &mut App,
170    ) -> (LayoutId, ()) {
171        (self.child.request_layout(window, cx), ())
172    }
173
174    fn prepaint(
175        &mut self,
176        _: Option<&GlobalElementId>,
177        _: Option<&InspectorElementId>,
178        bounds: Bounds<Pixels>,
179        _: &mut (),
180        window: &mut Window,
181        cx: &mut App,
182    ) -> Self::PrepaintState {
183        let parent_clip = window.content_mask().bounds;
184        let viewport = self.viewport.unwrap_or(parent_clip);
185        let mask = Mask::new(bounds, viewport, self.axis, cx.reduce_motion());
186        let clip = mask.bounds.intersect(&viewport).intersect(&parent_clip);
187        if clip.is_empty() {
188            return None;
189        }
190        window.with_content_mask(Some(ContentMask { bounds: clip }), |window| {
191            window.with_element_offset(mask.offset, |window| {
192                self.child.prepaint(window, cx);
193            });
194        });
195        Some(CarouselParallaxPaint {
196            mask: mask.bounds,
197            clip,
198        })
199    }
200
201    fn paint(
202        &mut self,
203        _: Option<&GlobalElementId>,
204        _: Option<&InspectorElementId>,
205        _: Bounds<Pixels>,
206        _: &mut (),
207        paint: &mut Self::PrepaintState,
208        window: &mut Window,
209        cx: &mut App,
210    ) {
211        let Some(paint) = paint else { return };
212        let theme = current_material_theme(window, cx);
213        let backdrop = self
214            .backdrop
215            .unwrap_or_else(|| color(theme.colors.color(ColorRole::Surface)));
216        let radii = self
217            .shape
218            .radii(
219                paint.mask.size.width.into(),
220                paint.mask.size.height.into(),
221                theme.layout.direction,
222            )
223            .map(px);
224        window.with_content_mask(Some(ContentMask { bounds: paint.clip }), |window| {
225            self.child.paint(window, cx);
226            paint_corners(paint.mask, radii, backdrop, window);
227            if let Some(border) = self.border {
228                let width = px(super::nonnegative(border.width))
229                    .min(paint.mask.size.width.min(paint.mask.size.height) / 2.);
230                if width > px(0.) {
231                    let [top_left, top_right, bottom_right, bottom_left] = radii;
232                    window.paint_quad(quad(
233                        paint.mask,
234                        Corners {
235                            top_left,
236                            top_right,
237                            bottom_right,
238                            bottom_left,
239                        },
240                        gpui::transparent_black(),
241                        width,
242                        border.color,
243                        BorderStyle::Solid,
244                    ));
245                }
246            }
247        });
248    }
249}
250
251fn paint_corners(bounds: Bounds<Pixels>, radii: [Pixels; 4], backdrop: Hsla, window: &mut Window) {
252    if radii.iter().all(|&r| r <= px(0.)) {
253        return;
254    }
255    let mut cutouts = PathBuilder::fill();
256    let corners = [
257        (point(bounds.left(), bounds.top()), 1., 1.),
258        (point(bounds.right(), bounds.top()), -1., 1.),
259        (point(bounds.right(), bounds.bottom()), -1., -1.),
260        (point(bounds.left(), bounds.bottom()), 1., -1.),
261    ];
262    for ((corner, x, y), radius) in corners.into_iter().zip(radii) {
263        if radius <= px(0.) {
264            continue;
265        }
266        // The two control points approximate the circular arc of a GPUI quad.
267        let control = radius * (1. - 0.552_284_8);
268        cutouts.move_to(corner);
269        cutouts.line_to(corner + point(radius * x, px(0.)));
270        cutouts.cubic_bezier_to(
271            corner + point(px(0.), radius * y),
272            corner + point(control * x, px(0.)),
273            corner + point(px(0.), control * y),
274        );
275        cutouts.close();
276    }
277    if let Ok(path) = cutouts.build() {
278        window.paint_path(path, backdrop);
279    }
280}
281
282#[cfg(test)]
283mod tests {
284    use super::*;
285
286    #[test]
287    fn wide_item_clips_both_edges_on_horizontal_and_vertical_axes() {
288        let viewport = Bounds::new(point(px(50.), px(40.)), size(px(200.), px(120.)));
289
290        // Horizontally wider than the viewport: overflows both left and right edges.
291        let wide_h = Bounds::new(point(px(0.), px(40.)), size(px(400.), px(100.)));
292        let mask_h = Mask::new(wide_h, viewport, Axis::Horizontal, false);
293        assert!(
294            mask_h.bounds.left() > wide_h.left(),
295            "left edge should be cropped, got {:?}",
296            mask_h.bounds
297        );
298        assert!(
299            mask_h.bounds.right() < wide_h.right(),
300            "right edge should be cropped, got {:?}",
301            mask_h.bounds
302        );
303        assert!(mask_h.bounds.size.width > px(0.));
304
305        // Vertically taller than the viewport: overflows both top and bottom edges.
306        let tall_v = Bounds::new(point(px(50.), px(0.)), size(px(100.), px(300.)));
307        let mask_v = Mask::new(tall_v, viewport, Axis::Vertical, false);
308        assert!(
309            mask_v.bounds.top() > tall_v.top(),
310            "top edge should be cropped, got {:?}",
311            mask_v.bounds
312        );
313        assert!(
314            mask_v.bounds.bottom() < tall_v.bottom(),
315            "bottom edge should be cropped, got {:?}",
316            mask_v.bounds
317        );
318        assert!(mask_v.bounds.size.height > px(0.));
319    }
320}