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