Skip to main content

gpui_material_extras/
carousel.rs

1//! Material 3 carousel strategies and desktop navigation.
2
3mod geometry;
4mod interaction;
5mod parallax;
6mod state;
7mod viewport;
8
9use std::{cell::RefCell, rc::Rc};
10
11use gpui::{
12    AccessibleAction, AnyElement, App, ElementId, Entity, ImageSource, InteractiveElement,
13    IntoElement, ParentElement, Pixels, RenderOnce, Role, SharedString, StatefulInteractiveElement,
14    Styled, Window, div, prelude::FluentBuilder, px,
15};
16use gpui_base::TestSupportExt;
17use gpui_material_foundation::{animate, color, current_material_theme};
18use gpui_material_theme::{
19    ColorRole, Direction, LogicalEdges, MotionKind, MotionSpec, MotionSpeed,
20};
21
22use geometry::LayoutOptions;
23use interaction::{Interaction, focus_at_position, navigation_index};
24use viewport::Viewport;
25
26pub use parallax::CarouselParallax;
27pub use state::CarouselState;
28
29const WIDTH_TO_HEIGHT_MIN: f32 = 9. / 16.;
30const WIDTH_TO_HEIGHT_MAX: f32 = 16. / 9.;
31
32/// Material carousel layouts. Full-screen pages scroll vertically.
33#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
34pub enum CarouselVariant {
35    /// Displays multiple sized items (large, medium, and small) across the viewport.
36    #[default]
37    MultiBrowse,
38    /// Scrolls uniform-width items freely without contained keyline shrinking.
39    Uncontained,
40    /// Scrolls items freely with per-item aspect ratios clamped to Material bounds.
41    UncontainedMultiAspectRatio,
42    /// Features one large hero item alongside smaller peeking items.
43    Hero,
44    /// Centers the large hero item between smaller peeking items on both sides.
45    CenteredHero,
46    /// Displays one full-bleed page at a time along the vertical axis.
47    FullScreen,
48}
49
50impl CarouselVariant {
51    pub(crate) fn is_vertical(self) -> bool {
52        self == Self::FullScreen
53    }
54
55    pub(crate) fn is_uncontained(self) -> bool {
56        matches!(self, Self::Uncontained | Self::UncontainedMultiAspectRatio)
57    }
58}
59
60/// Resting alignment for Multi-browse, Hero, and Centered Hero keylines.
61#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
62pub enum CarouselAlignment {
63    /// Aligns the focal keyline toward the leading edge of the carousel.
64    #[default]
65    Start,
66    /// Centers the focal keyline within the carousel viewport.
67    Center,
68}
69
70/// Positions before and after a precise scroll gesture, in fractional item units.
71#[derive(Clone, Copy, Debug, PartialEq)]
72pub struct CarouselFlingContext {
73    /// Fractional item position when the scroll gesture began.
74    pub start: f32,
75    /// Fractional item position when the scroll gesture ended.
76    pub position: f32,
77    /// Total number of items currently in the carousel.
78    pub item_count: usize,
79}
80
81/// Chooses the resting position when a precise scroll gesture ends.
82#[derive(Clone, Default)]
83pub enum CarouselFling {
84    /// Snap on contained layouts and Full-screen. Scroll freely on uncontained layouts.
85    #[default]
86    Default,
87    /// Leaves the fractional position at the end of the gesture.
88    Free,
89    /// Snaps to the nearest item after any number of items have been scrolled.
90    Snap,
91    /// Snaps to the nearest item at most one index away from the gesture's start.
92    SingleAdvance,
93    /// Returns the resting item index, or None to leave the position where the gesture ended.
94    Custom(Rc<dyn Fn(CarouselFlingContext) -> Option<usize>>),
95}
96
97impl CarouselFling {
98    /// Creates a [`CarouselFling::Custom`] strategy from a callback that chooses the target item index.
99    pub fn custom(target: impl Fn(CarouselFlingContext) -> Option<usize> + 'static) -> Self {
100        Self::Custom(Rc::new(target))
101    }
102}
103
104fn nonnegative(value: Pixels) -> f32 {
105    nonnegative_f32(f32::from(value))
106}
107
108fn nonnegative_f32(value: f32) -> f32 {
109    if value.is_finite() { value.max(0.) } else { 0. }
110}
111
112type Activate = Rc<dyn Fn(&SharedString, &mut Window, &mut App)>;
113
114enum Content {
115    Element(AnyElement),
116    Image(ImageSource),
117}
118
119/// One slide, with a stable unique identifier and a localized accessible name.
120pub struct CarouselItem {
121    id: SharedString,
122    label: SharedString,
123    aspect: f32,
124    disabled: bool,
125    content: Content,
126}
127
128impl CarouselItem {
129    /// Creates a carousel item with a stable `id`, accessible `label`, and custom element `content`.
130    pub fn new(
131        id: impl Into<SharedString>,
132        label: impl Into<SharedString>,
133        content: impl IntoElement,
134    ) -> Self {
135        Self {
136            id: id.into(),
137            label: label.into(),
138            aspect: 1.,
139            disabled: false,
140            content: Content::Element(content.into_any_element()),
141        }
142    }
143
144    /// A full-bleed image cropped to the changing item mask.
145    pub fn image(
146        id: impl Into<SharedString>,
147        label: impl Into<SharedString>,
148        source: impl Into<ImageSource>,
149    ) -> Self {
150        Self {
151            id: id.into(),
152            label: label.into(),
153            aspect: 1.,
154            disabled: false,
155            content: Content::Image(source.into()),
156        }
157    }
158
159    /// Width divided by height, used by the multi-aspect ratio layout.
160    /// Values outside the Material 9:16–16:9 range are clamped.
161    pub fn aspect_ratio(mut self, width_over_height: f32) -> Self {
162        if width_over_height.is_finite() && width_over_height > 0. {
163            self.aspect = width_over_height.clamp(WIDTH_TO_HEIGHT_MIN, WIDTH_TO_HEIGHT_MAX);
164        }
165        self
166    }
167
168    /// Disables activation and state-layer feedback on this item when `true`.
169    pub fn disabled(mut self, disabled: bool) -> Self {
170        self.disabled = disabled;
171        self
172    }
173}
174
175/// A viewport-sized collection of Material carousel items.
176///
177/// The component retains the visible item by ID across frames. The caller
178/// owns the item data and activation outcome. Tab enters the carousel at its
179/// current item. Arrow keys move within it and Enter or Space activates.
180/// Wheel and trackpad input follow the scrolling axis. Uncontained variants
181/// scroll freely by default. The contained layouts settle on a keyline.
182/// Supply descriptive item labels and noninteractive item content.
183#[derive(IntoElement)]
184pub struct Carousel {
185    id: ElementId,
186    label: SharedString,
187    items: Vec<CarouselItem>,
188    variant: CarouselVariant,
189    height: Pixels,
190    preferred_width: Pixels,
191    layout_options: LayoutOptions,
192    snap: Option<bool>,
193    fling: CarouselFling,
194    user_scroll_enabled: bool,
195    state: Option<Entity<CarouselState>>,
196    on_activate: Option<Activate>,
197}
198
199impl Carousel {
200    /// Creates a carousel with an element `id`, accessible region `label`, and initial `items`.
201    ///
202    /// Defaults to [`CarouselVariant::MultiBrowse`], a `220px` height, `192px` preferred item
203    /// width, and user scrolling enabled.
204    pub fn new(
205        id: impl Into<ElementId>,
206        label: impl Into<SharedString>,
207        items: impl IntoIterator<Item = CarouselItem>,
208    ) -> Self {
209        Self {
210            id: id.into(),
211            label: label.into(),
212            items: items.into_iter().collect(),
213            variant: CarouselVariant::default(),
214            height: px(220.),
215            preferred_width: px(192.),
216            layout_options: LayoutOptions::default(),
217            snap: None,
218            fling: CarouselFling::Default,
219            user_scroll_enabled: true,
220            state: None,
221            on_activate: None,
222        }
223    }
224
225    /// Sets the Material carousel layout strategy.
226    pub fn variant(mut self, variant: CarouselVariant) -> Self {
227        self.variant = variant;
228        self
229    }
230
231    /// Carousel viewport height. Full-screen pages span this height and the
232    /// available width. A host can supply the window's content height.
233    pub fn height(mut self, height: Pixels) -> Self {
234        if f32::from(height).is_finite() && height > px(0.) {
235            self.height = height;
236        }
237        self
238    }
239
240    /// Preferred large item width for multi-browse and regular uncontained.
241    pub fn preferred_item_width(mut self, width: Pixels) -> Self {
242        if f32::from(width).is_finite() && width > px(0.) {
243            self.preferred_width = width;
244        }
245        self
246    }
247
248    /// Sets default snapping for uncontained layouts.
249    pub fn snap_scrolling(mut self, snap: bool) -> Self {
250        self.snap = Some(snap);
251        self
252    }
253
254    /// Overrides the resting keyline alignment for contained variants.
255    pub fn alignment(mut self, alignment: CarouselAlignment) -> Self {
256        self.layout_options.alignment = Some(alignment);
257        self
258    }
259
260    /// Sets the distance between items in logical pixels.
261    pub fn item_spacing(mut self, gap: Pixels) -> Self {
262        self.layout_options.spacing = Some(nonnegative(gap));
263        self
264    }
265
266    /// Sets the content padding around the carousel viewport, clamping negative values to `0`.
267    pub fn content_padding(mut self, padding: LogicalEdges) -> Self {
268        self.layout_options.padding = Some(LogicalEdges {
269            start: nonnegative_f32(padding.start),
270            end: nonnegative_f32(padding.end),
271            top: nonnegative_f32(padding.top),
272            bottom: nonnegative_f32(padding.bottom),
273        });
274        self
275    }
276
277    /// Overrides the ordered positive width bounds for small contained keylines.
278    pub fn small_item_widths(mut self, min: Pixels, max: Pixels) -> Self {
279        let (min, max) = (nonnegative(min), nonnegative(max));
280        if min > 0. && max >= min {
281            self.layout_options.small = (min, max);
282        }
283        self
284    }
285
286    /// Overrides the variant's default precise-scroll settling behavior.
287    pub fn fling_behavior(mut self, fling: CarouselFling) -> Self {
288        self.fling = fling;
289        self
290    }
291
292    /// Enables wheel, trackpad, keyboard navigation, and accessibility scrolling.
293    pub fn user_scroll_enabled(mut self, enabled: bool) -> Self {
294        self.user_scroll_enabled = enabled;
295        self
296    }
297
298    /// Uses a caller-retained entity for this carousel's position.
299    pub fn state(mut self, state: &Entity<CarouselState>) -> Self {
300        self.state = Some(state.clone());
301        self
302    }
303
304    /// Registers a callback invoked with the activated item's ID on click or accessibility click.
305    pub fn on_activate(
306        mut self,
307        callback: impl Fn(&SharedString, &mut Window, &mut App) + 'static,
308    ) -> Self {
309        self.on_activate = Some(Rc::new(callback));
310        self
311    }
312}
313
314impl RenderOnce for Carousel {
315    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
316        let state = self.state.unwrap_or_else(|| {
317            window.use_keyed_state((self.id.clone(), "carousel-state"), cx, |_, _| {
318                CarouselState::new(0)
319            })
320        });
321        let (target, direct, focus) = state.update(cx, |state, cx| {
322            state.sync(&self.items, cx);
323            if !self.user_scroll_enabled {
324                state.cancel_input(cx);
325            }
326            (state.requested, state.direct, state.items.clone())
327        });
328        let theme = current_material_theme(window, cx);
329        let direction = theme.layout.direction;
330        let ring = color(theme.colors.color(ColorRole::Secondary));
331        let hover = color(theme.colors.color(ColorRole::OnSurface));
332        let surface = color(theme.colors.color(ColorRole::SurfaceContainer));
333        let reduced = cx.reduce_motion();
334        let motion = theme
335            .motion
336            .spec(MotionKind::Spatial, MotionSpeed::Fast, reduced);
337        let sample = animate(
338            (self.id.clone(), "carousel-position"),
339            target,
340            if direct { MotionSpec::Instant } else { motion },
341            window,
342            cx,
343        );
344        state.update(cx, |state, cx| state.sample(sample, cx));
345        let sample = state.read(cx).sampled;
346        let vertical = self.variant.is_vertical();
347        let shared_layout = Rc::new(RefCell::new(None));
348        let fling = match self.fling {
349            CarouselFling::Default if !self.variant.is_uncontained() || self.snap == Some(true) => {
350                CarouselFling::Snap
351            }
352            CarouselFling::Default => CarouselFling::Free,
353            explicit => explicit,
354        };
355        let wheel = Interaction {
356            layout: shared_layout.clone(),
357            focus: focus.clone(),
358            state: state.clone(),
359            vertical,
360            direction,
361            fling,
362        };
363        let keys = wheel.clone();
364        let previous = wheel.clone();
365        let next = wheel.clone();
366        let (backward, forward) = match (vertical, direction) {
367            (true, _) => (AccessibleAction::ScrollUp, AccessibleAction::ScrollDown),
368            (false, Direction::Ltr) => {
369                (AccessibleAction::ScrollLeft, AccessibleAction::ScrollRight)
370            }
371            (false, Direction::Rtl) => {
372                (AccessibleAction::ScrollRight, AccessibleAction::ScrollLeft)
373            }
374        };
375        let focused = focus.iter().position(|item| item.focus.is_focused(window));
376        let tab_stop = focus_at_position(&focus, target);
377
378        div()
379            .id(self.id.clone())
380            .test_support()
381            .role(Role::Region)
382            .aria_label(self.label)
383            .w_full()
384            .min_w_0()
385            .relative()
386            .overflow_hidden()
387            .when(self.user_scroll_enabled, move |region| {
388                region
389                    .on_key_down(move |event, window, cx| {
390                        if event.keystroke.modifiers.modified() {
391                            return;
392                        }
393                        let current = keys.state.read(cx).requested;
394                        if let Some(index) = navigation_index(
395                            &keys.focus,
396                            current,
397                            &event.keystroke.key,
398                            keys.vertical,
399                            keys.direction,
400                        ) {
401                            keys.state
402                                .update(cx, |state, cx| state.animate_scroll_to_item(index, cx));
403                            keys.focus[index].focus.focus(window, cx);
404                            window.refresh();
405                            cx.stop_propagation();
406                        }
407                    })
408                    .on_a11y_action(backward, move |_, window, cx| previous.page(-1, window, cx))
409                    .on_a11y_action(forward, move |_, window, cx| next.page(1, window, cx))
410                    .on_scroll(move |event, window, cx| wheel.on_scroll(event, window, cx))
411            })
412            .child(Viewport {
413                id: self.id,
414                variant: self.variant,
415                height: self.height,
416                preferred_width: self.preferred_width,
417                layout_options: self.layout_options,
418                user_scroll_enabled: self.user_scroll_enabled,
419                items: self.items.into_iter().map(Some).collect(),
420                focus,
421                focused,
422                tab_stop,
423                state,
424                sample,
425                direction,
426                ring,
427                hover,
428                surface,
429                activate: self.on_activate,
430                layout: shared_layout,
431            })
432    }
433}