Skip to main content

gpui_material_extras/carousel/
mod.rs

1//! Material 3 carousel strategies and desktop navigation.
2
3mod geometry;
4mod parallax;
5mod state;
6
7use std::{cell::RefCell, rc::Rc, time::Duration};
8
9use gpui::{
10    AccessibleAction, AnyElement, App, Bounds, ContentMask, Element, ElementId, Entity,
11    GlobalElementId, ImageSource, InspectorElementId, InteractiveElement, IntoElement, LayoutId,
12    ObjectFit, ParentElement, Pixels, RenderOnce, Role, ScrollEvent, SharedString,
13    StatefulInteractiveElement, Style, Styled, StyledImage, TouchPhase, Window, div, img, point,
14    prelude::FluentBuilder, px, relative, size,
15};
16use gpui_base::{Button, TestSupportExt};
17use gpui_material_foundation::{animate, color, current_material_theme};
18use gpui_material_theme::{ColorRole, CornerRole, Direction, MotionKind, MotionSpec, MotionSpeed};
19
20use geometry::{Layout, LayoutOptions};
21use state::ItemFocus;
22
23pub use parallax::{CarouselBorder, CarouselParallax};
24pub use state::CarouselState;
25
26const SCROLL_SETTLE: Duration = Duration::from_millis(120);
27const WIDTH_TO_HEIGHT_MIN: f32 = 9. / 16.;
28const WIDTH_TO_HEIGHT_MAX: f32 = 16. / 9.;
29
30/// Material carousel layouts. Full-screen pages scroll vertically.
31#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
32pub enum CarouselVariant {
33    /// Displays multiple sized items (large, medium, and small) across the viewport.
34    #[default]
35    MultiBrowse,
36    /// Scrolls uniform-width items freely without contained keyline shrinking.
37    Uncontained,
38    /// Scrolls items freely with per-item aspect ratios clamped to Material bounds.
39    UncontainedMultiAspectRatio,
40    /// Features one large hero item alongside smaller peeking items.
41    Hero,
42    /// Centers the large hero item between smaller peeking items on both sides.
43    CenteredHero,
44    /// Displays one full-bleed page at a time along the vertical axis.
45    FullScreen,
46}
47
48impl CarouselVariant {
49    fn is_vertical(self) -> bool {
50        self == Self::FullScreen
51    }
52
53    fn is_uncontained(self) -> bool {
54        matches!(self, Self::Uncontained | Self::UncontainedMultiAspectRatio)
55    }
56}
57
58/// Resting alignment for Multi-browse, Hero, and Centered Hero keylines.
59#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
60pub enum CarouselAlignment {
61    /// Aligns the focal keyline toward the leading edge of the carousel.
62    #[default]
63    Start,
64    /// Centers the focal keyline within the carousel viewport.
65    Center,
66}
67
68/// Padding in logical pixels. Start and end follow the window direction.
69#[derive(Clone, Copy, Debug, Default, PartialEq)]
70pub struct CarouselPadding {
71    /// Leading-edge padding along the horizontal axis (respects RTL).
72    pub start: Pixels,
73    /// Trailing-edge padding along the horizontal axis (respects RTL).
74    pub end: Pixels,
75    /// Top-edge padding.
76    pub top: Pixels,
77    /// Bottom-edge padding.
78    pub bottom: Pixels,
79}
80
81/// Positions before and after a precise scroll gesture, in fractional item units.
82#[derive(Clone, Copy, Debug, PartialEq)]
83pub struct CarouselFlingContext {
84    /// Fractional item position when the scroll gesture began.
85    pub start: f32,
86    /// Fractional item position when the scroll gesture ended.
87    pub position: f32,
88    /// Total number of items currently in the carousel.
89    pub item_count: usize,
90}
91
92/// Chooses the resting position when a precise scroll gesture ends.
93#[derive(Clone, Default)]
94pub enum CarouselFling {
95    /// Snap on contained layouts and Full-screen. Scroll freely on uncontained layouts.
96    #[default]
97    Default,
98    /// Leaves the fractional position at the end of the gesture.
99    Free,
100    /// Snaps to the nearest item after any number of items have been scrolled.
101    Snap,
102    /// Snaps to the nearest item at most one index away from the gesture's start.
103    SingleAdvance,
104    /// Returns the resting item index, or None to leave the position where the gesture ended.
105    Custom(Rc<dyn Fn(CarouselFlingContext) -> Option<usize>>),
106}
107
108impl CarouselFling {
109    /// Creates a [`CarouselFling::Custom`] strategy from a callback that chooses the target item index.
110    pub fn custom(target: impl Fn(CarouselFlingContext) -> Option<usize> + 'static) -> Self {
111        Self::Custom(Rc::new(target))
112    }
113}
114
115fn nonnegative(value: Pixels) -> f32 {
116    let value = f32::from(value);
117    if value.is_finite() { value.max(0.) } else { 0. }
118}
119
120type Activate = Rc<dyn Fn(&SharedString, &mut Window, &mut App)>;
121
122enum Content {
123    Element(AnyElement),
124    Image(ImageSource),
125}
126
127/// One slide, with a stable unique identifier and a localized accessible name.
128pub struct CarouselItem {
129    id: SharedString,
130    label: SharedString,
131    aspect: f32,
132    disabled: bool,
133    content: Content,
134}
135
136impl CarouselItem {
137    /// Creates a carousel item with a stable `id`, accessible `label`, and custom element `content`.
138    pub fn new(
139        id: impl Into<SharedString>,
140        label: impl Into<SharedString>,
141        content: impl IntoElement,
142    ) -> Self {
143        Self {
144            id: id.into(),
145            label: label.into(),
146            aspect: 1.,
147            disabled: false,
148            content: Content::Element(content.into_any_element()),
149        }
150    }
151
152    /// A full-bleed image cropped to the changing item mask.
153    pub fn image(
154        id: impl Into<SharedString>,
155        label: impl Into<SharedString>,
156        source: impl Into<ImageSource>,
157    ) -> Self {
158        Self {
159            id: id.into(),
160            label: label.into(),
161            aspect: 1.,
162            disabled: false,
163            content: Content::Image(source.into()),
164        }
165    }
166
167    /// Width divided by height, used by the multi-aspect ratio layout.
168    /// Values outside the Material 9:16–16:9 range are clamped.
169    pub fn aspect_ratio(mut self, width_over_height: f32) -> Self {
170        if width_over_height.is_finite() && width_over_height > 0. {
171            self.aspect = width_over_height.clamp(WIDTH_TO_HEIGHT_MIN, WIDTH_TO_HEIGHT_MAX);
172        }
173        self
174    }
175
176    /// Disables activation and state-layer feedback on this item when `true`.
177    pub fn disabled(mut self, disabled: bool) -> Self {
178        self.disabled = disabled;
179        self
180    }
181}
182
183/// A viewport-sized collection of Material carousel items.
184///
185/// The component retains the visible item by ID across frames. The caller
186/// owns the item data and activation outcome. Tab enters the carousel at its
187/// current item. Arrow keys move within it and Enter or Space activates.
188/// Wheel and trackpad input follow the scrolling axis. Uncontained variants
189/// scroll freely by default. The contained layouts settle on a keyline.
190/// Supply descriptive item labels and noninteractive item content.
191#[derive(IntoElement)]
192pub struct Carousel {
193    id: ElementId,
194    label: SharedString,
195    items: Vec<CarouselItem>,
196    variant: CarouselVariant,
197    height: Pixels,
198    preferred_width: Pixels,
199    layout_options: LayoutOptions,
200    snap: Option<bool>,
201    fling: CarouselFling,
202    user_scroll_enabled: bool,
203    state: Option<Entity<CarouselState>>,
204    on_activate: Option<Activate>,
205}
206
207impl Carousel {
208    /// Creates a carousel with an element `id`, accessible region `label`, and initial `items`.
209    ///
210    /// Defaults to [`CarouselVariant::MultiBrowse`], a `220px` height, `192px` preferred item
211    /// width, and user scrolling enabled.
212    pub fn new(
213        id: impl Into<ElementId>,
214        label: impl Into<SharedString>,
215        items: impl IntoIterator<Item = CarouselItem>,
216    ) -> Self {
217        Self {
218            id: id.into(),
219            label: label.into(),
220            items: items.into_iter().collect(),
221            variant: CarouselVariant::default(),
222            height: px(220.),
223            preferred_width: px(192.),
224            layout_options: LayoutOptions::default(),
225            snap: None,
226            fling: CarouselFling::Default,
227            user_scroll_enabled: true,
228            state: None,
229            on_activate: None,
230        }
231    }
232
233    /// Sets the Material carousel layout strategy.
234    pub fn variant(mut self, variant: CarouselVariant) -> Self {
235        self.variant = variant;
236        self
237    }
238
239    /// Carousel viewport height. Full-screen pages span this height and the
240    /// available width. A host can supply the window's content height.
241    pub fn height(mut self, height: Pixels) -> Self {
242        if f32::from(height).is_finite() && height > px(0.) {
243            self.height = height;
244        }
245        self
246    }
247
248    /// Preferred large item width for multi-browse and regular uncontained.
249    pub fn preferred_item_width(mut self, width: Pixels) -> Self {
250        if f32::from(width).is_finite() && width > px(0.) {
251            self.preferred_width = width;
252        }
253        self
254    }
255
256    /// Sets default snapping for uncontained layouts.
257    pub fn snap_scrolling(mut self, snap: bool) -> Self {
258        self.snap = Some(snap);
259        self
260    }
261
262    /// Overrides the resting keyline alignment for contained variants.
263    pub fn alignment(mut self, alignment: CarouselAlignment) -> Self {
264        self.layout_options.alignment = Some(alignment);
265        self
266    }
267
268    /// Sets the distance between items in logical pixels.
269    pub fn item_spacing(mut self, gap: Pixels) -> Self {
270        self.layout_options.spacing = Some(nonnegative(gap));
271        self
272    }
273
274    /// Sets the content padding around the carousel viewport, clamping negative values to `0`.
275    pub fn content_padding(mut self, padding: CarouselPadding) -> Self {
276        self.layout_options.padding = Some(CarouselPadding {
277            start: px(nonnegative(padding.start)),
278            end: px(nonnegative(padding.end)),
279            top: px(nonnegative(padding.top)),
280            bottom: px(nonnegative(padding.bottom)),
281        });
282        self
283    }
284
285    /// Overrides the ordered positive width bounds for small contained keylines.
286    pub fn small_item_widths(mut self, min: Pixels, max: Pixels) -> Self {
287        let (min, max) = (nonnegative(min), nonnegative(max));
288        if min > 0. && max >= min {
289            self.layout_options.small = (min, max);
290        }
291        self
292    }
293
294    /// Overrides the variant's default precise-scroll settling behavior.
295    pub fn fling_behavior(mut self, fling: CarouselFling) -> Self {
296        self.fling = fling;
297        self
298    }
299
300    /// Enables wheel, trackpad, keyboard navigation, and accessibility scrolling.
301    pub fn user_scroll_enabled(mut self, enabled: bool) -> Self {
302        self.user_scroll_enabled = enabled;
303        self
304    }
305
306    /// Uses a caller-retained entity for this carousel's position.
307    pub fn state(mut self, state: &Entity<CarouselState>) -> Self {
308        self.state = Some(state.clone());
309        self
310    }
311
312    /// Registers a callback invoked with the activated item's ID on click or accessibility click.
313    pub fn on_activate(
314        mut self,
315        callback: impl Fn(&SharedString, &mut Window, &mut App) + 'static,
316    ) -> Self {
317        self.on_activate = Some(Rc::new(callback));
318        self
319    }
320}
321
322impl RenderOnce for Carousel {
323    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
324        let state = self.state.unwrap_or_else(|| {
325            window.use_keyed_state((self.id.clone(), "carousel-state"), cx, |_, _| {
326                CarouselState::new(0)
327            })
328        });
329        let (target, direct, focus) = state.update(cx, |state, cx| {
330            state.sync(&self.items, cx);
331            if !self.user_scroll_enabled {
332                state.cancel_input(cx);
333            }
334            (state.requested, state.direct, state.items.clone())
335        });
336        let theme = current_material_theme(window, cx);
337        let direction = theme.layout.direction;
338        let ring = color(theme.colors.color(ColorRole::Secondary));
339        let hover = color(theme.colors.color(ColorRole::OnSurface));
340        let surface = color(theme.colors.color(ColorRole::SurfaceContainer));
341        let reduced = cx.reduce_motion();
342        let motion = theme
343            .motion
344            .spec(MotionKind::Spatial, MotionSpeed::Fast, reduced);
345        let sample = animate(
346            (self.id.clone(), "carousel-position"),
347            target,
348            if direct { MotionSpec::Instant } else { motion },
349            window,
350            cx,
351        );
352        state.update(cx, |state, cx| state.sample(sample, cx));
353        let sample = state.read(cx).sampled;
354        let vertical = self.variant.is_vertical();
355        let shared_layout = Rc::new(RefCell::new(None));
356        let fling = match self.fling {
357            CarouselFling::Default if !self.variant.is_uncontained() || self.snap == Some(true) => {
358                CarouselFling::Snap
359            }
360            CarouselFling::Default => CarouselFling::Free,
361            explicit => explicit,
362        };
363        let wheel = Interaction {
364            layout: shared_layout.clone(),
365            focus: focus.clone(),
366            state: state.clone(),
367            vertical,
368            direction,
369            fling,
370        };
371        let keys = wheel.clone();
372        let previous = wheel.clone();
373        let next = wheel.clone();
374        let (backward, forward) = match (vertical, direction) {
375            (true, _) => (AccessibleAction::ScrollUp, AccessibleAction::ScrollDown),
376            (false, Direction::Ltr) => {
377                (AccessibleAction::ScrollLeft, AccessibleAction::ScrollRight)
378            }
379            (false, Direction::Rtl) => {
380                (AccessibleAction::ScrollRight, AccessibleAction::ScrollLeft)
381            }
382        };
383        let focused = focus.iter().position(|item| item.focus.is_focused(window));
384        let tab_stop = focus_at_position(&focus, target);
385
386        div()
387            .id(self.id.clone())
388            .test_support()
389            .role(Role::Region)
390            .aria_label(self.label)
391            .w_full()
392            .min_w_0()
393            .relative()
394            .overflow_hidden()
395            .when(self.user_scroll_enabled, move |region| {
396                region
397                    .on_key_down(move |event, window, cx| {
398                        if event.keystroke.modifiers.modified() {
399                            return;
400                        }
401                        let current = keys.state.read(cx).requested;
402                        if let Some(index) = navigation_index(
403                            &keys.focus,
404                            current,
405                            &event.keystroke.key,
406                            keys.vertical,
407                            keys.direction,
408                        ) {
409                            keys.state
410                                .update(cx, |state, cx| state.animate_scroll_to_item(index, cx));
411                            keys.focus[index].focus.focus(window, cx);
412                            window.refresh();
413                            cx.stop_propagation();
414                        }
415                    })
416                    .on_a11y_action(backward, move |_, window, cx| previous.page(-1, window, cx))
417                    .on_a11y_action(forward, move |_, window, cx| next.page(1, window, cx))
418                    .on_scroll(move |event, window, cx| wheel.on_scroll(event, window, cx))
419            })
420            .child(Viewport {
421                id: self.id,
422                variant: self.variant,
423                height: self.height,
424                preferred_width: self.preferred_width,
425                layout_options: self.layout_options,
426                user_scroll_enabled: self.user_scroll_enabled,
427                items: self.items.into_iter().map(Some).collect(),
428                focus,
429                focused,
430                tab_stop,
431                state,
432                sample,
433                direction,
434                ring,
435                hover,
436                surface,
437                activate: self.on_activate,
438                layout: shared_layout,
439            })
440    }
441}
442
443struct Viewport {
444    id: ElementId,
445    variant: CarouselVariant,
446    height: Pixels,
447    preferred_width: Pixels,
448    layout_options: LayoutOptions,
449    user_scroll_enabled: bool,
450    items: Vec<Option<CarouselItem>>,
451    focus: Rc<[ItemFocus]>,
452    focused: Option<usize>,
453    tab_stop: Option<usize>,
454    state: Entity<CarouselState>,
455    sample: f32,
456    direction: Direction,
457    ring: gpui::Hsla,
458    hover: gpui::Hsla,
459    surface: gpui::Hsla,
460    activate: Option<Activate>,
461    layout: Rc<RefCell<Option<Layout>>>,
462}
463
464struct Prepaint {
465    children: Vec<AnyElement>,
466    mask: Bounds<Pixels>,
467}
468
469impl IntoElement for Viewport {
470    type Element = Self;
471    fn into_element(self) -> Self {
472        self
473    }
474}
475
476impl Element for Viewport {
477    type RequestLayoutState = ();
478    type PrepaintState = Prepaint;
479
480    fn id(&self) -> Option<ElementId> {
481        Some((self.id.clone(), "viewport").into())
482    }
483
484    fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
485        None
486    }
487
488    fn request_layout(
489        &mut self,
490        _: Option<&GlobalElementId>,
491        _: Option<&InspectorElementId>,
492        window: &mut Window,
493        cx: &mut App,
494    ) -> (LayoutId, ()) {
495        let style = Style {
496            size: size(relative(1.).into(), self.height.into()),
497            ..Style::default()
498        };
499        (window.request_layout(style, [], cx), ())
500    }
501
502    fn prepaint(
503        &mut self,
504        _: Option<&GlobalElementId>,
505        _: Option<&InspectorElementId>,
506        bounds: Bounds<Pixels>,
507        _: &mut (),
508        window: &mut Window,
509        cx: &mut App,
510    ) -> Self::PrepaintState {
511        let vertical = self.variant.is_vertical();
512        let layout = layout(
513            self.variant,
514            bounds.size.width,
515            bounds.size.height,
516            self.preferred_width,
517            self.layout_options,
518            self.items.iter().flatten(),
519        );
520        let (inset, cross) = layout.cross_bounds(self.direction);
521        let (inset, cross) = (px(inset), px(cross));
522        let mut visible = layout.visible(self.sample, self.direction);
523        // When keyboard or UI Automation focuses an item outside the current
524        // mask, reveal it in this frame rather than leaving an invisible focus
525        // target during a long animation.
526        if let Some(focused) = self.focused
527            && !self.state.read(cx).direct
528            && self.state.read(cx).requested.round() as usize == focused
529            && !visible.iter().any(|(index, item)| {
530                *index == focused
531                    && item.size >= 40.
532                    && item.start >= -0.5
533                    && item.start + item.size
534                        <= f32::from(if vertical {
535                            bounds.size.height
536                        } else {
537                            bounds.size.width
538                        }) + 0.5
539            })
540        {
541            visible = layout.visible(focused as f32, self.direction);
542        }
543        let (start, end) = layout.clip_range(self.direction);
544        *self.layout.borrow_mut() = Some(layout);
545        let mask = if vertical {
546            Bounds::new(
547                bounds.origin + point(inset, px(start)),
548                size(cross, px(end - start)),
549            )
550        } else {
551            Bounds::new(
552                bounds.origin + point(px(start), inset),
553                size(px(end - start), cross),
554            )
555        };
556        let mut children = Vec::with_capacity(visible.len());
557        let count = self.items.len();
558        window.with_content_mask(Some(ContentMask { bounds: mask }), |window| {
559            for (index, geometry) in visible {
560                let Some(item) = self.items[index].take() else {
561                    continue;
562                };
563                let (size, offset) = if vertical {
564                    (
565                        size(cross, px(geometry.size)),
566                        point(inset, px(geometry.start)),
567                    )
568                } else {
569                    (
570                        size(px(geometry.size), cross),
571                        point(px(geometry.start), inset),
572                    )
573                };
574                let radius = if vertical {
575                    0.
576                } else {
577                    CornerRole::ExtraLarge.shape().radii(
578                        f32::from(size.width),
579                        f32::from(size.height),
580                        self.direction,
581                    )[0]
582                };
583                let id = item.id;
584                let activate_id = id.clone();
585                let accessible_id = id.clone();
586                let activate = self.activate.clone();
587                let activate_accessible = activate.clone();
588                let state = self.state.clone();
589                let accessible_state = state.clone();
590                let accessible_focus = self.focus[index].focus.clone();
591                let user_scroll_enabled = self.user_scroll_enabled;
592                let content = match item.content {
593                    Content::Element(content) => content,
594                    Content::Image(source) => img(source)
595                        .size_full()
596                        .object_fit(ObjectFit::Cover)
597                        .rounded(px(radius))
598                        .into_any_element(),
599                };
600                let focused = self.focused == Some(index) && window.last_input_was_keyboard();
601                let mut child = Button::new((self.id.clone(), id))
602                    .accessibility_label(item.label)
603                    .aria_position_in_set(index + 1)
604                    .aria_size_of_set(count)
605                    .track_focus(&self.focus[index].focus)
606                    .tab_stop(self.tab_stop == Some(index))
607                    .disabled(item.disabled)
608                    .w(size.width)
609                    .h(size.height)
610                    .bg(self.surface)
611                    .rounded(px(radius))
612                    .overflow_hidden()
613                    .relative()
614                    .group("carousel-item")
615                    .when(!item.disabled, |button| {
616                        button
617                            .on_click(move |_, window, cx| {
618                                if user_scroll_enabled {
619                                    state.update(cx, |state, cx| {
620                                        state.animate_scroll_to_item(index, cx)
621                                    });
622                                }
623                                window.refresh();
624                                if let Some(activate) = &activate {
625                                    activate(&activate_id, window, cx);
626                                }
627                            })
628                            .on_a11y_action(AccessibleAction::Click, move |_, window, cx| {
629                                if user_scroll_enabled {
630                                    accessible_state.update(cx, |state, cx| {
631                                        state.animate_scroll_to_item(index, cx)
632                                    });
633                                }
634                                accessible_focus.focus(window, cx);
635                                window.refresh();
636                                if let Some(activate) = &activate_accessible {
637                                    activate(&accessible_id, window, cx);
638                                }
639                            })
640                    })
641                    .child(content)
642                    .child(
643                        div()
644                            .id("state-layer")
645                            .absolute()
646                            .inset_0()
647                            .rounded(px(radius))
648                            .when(!item.disabled, |state| {
649                                state
650                                    .group_hover("carousel-item", |style| {
651                                        style.bg(self.hover.opacity(0.08))
652                                    })
653                                    .group_active("carousel-item", |style| {
654                                        style.bg(self.hover.opacity(0.1))
655                                    })
656                                    .when(focused, |state| state.border_2().border_color(self.ring))
657                            }),
658                    )
659                    .into_any_element();
660                child.prepaint_as_root(bounds.origin + offset, size.map(Into::into), window, cx);
661                children.push(child);
662            }
663        });
664        Prepaint { children, mask }
665    }
666
667    fn paint(
668        &mut self,
669        _: Option<&GlobalElementId>,
670        _: Option<&InspectorElementId>,
671        _: Bounds<Pixels>,
672        _: &mut (),
673        state: &mut Self::PrepaintState,
674        window: &mut Window,
675        cx: &mut App,
676    ) {
677        window.with_content_mask(Some(ContentMask { bounds: state.mask }), |window| {
678            for child in &mut state.children {
679                child.paint(window, cx);
680            }
681        });
682    }
683}
684
685fn layout<'a>(
686    variant: CarouselVariant,
687    width: Pixels,
688    height: Pixels,
689    preferred_width: Pixels,
690    options: LayoutOptions,
691    items: impl IntoIterator<Item = &'a CarouselItem>,
692) -> Layout {
693    let (main, cross) = if variant.is_vertical() {
694        (height, width)
695    } else {
696        (width, height)
697    };
698    Layout::new(
699        variant,
700        main.into(),
701        cross.into(),
702        preferred_width.into(),
703        options,
704        items.into_iter().map(|item| item.aspect),
705    )
706}
707
708#[derive(Clone)]
709struct Interaction {
710    layout: Rc<RefCell<Option<Layout>>>,
711    focus: Rc<[ItemFocus]>,
712    state: Entity<CarouselState>,
713    vertical: bool,
714    direction: Direction,
715    fling: CarouselFling,
716}
717
718impl Interaction {
719    fn page(&self, delta: isize, window: &mut Window, cx: &mut App) {
720        let state = self.state.read(cx);
721        let index = (state.requested.round() as usize).saturating_add_signed(delta);
722        if index < self.focus.len() {
723            self.state
724                .update(cx, |state, cx| state.animate_scroll_to_item(index, cx));
725            window.refresh();
726        }
727    }
728
729    fn on_scroll(&self, event: &ScrollEvent, window: &mut Window, cx: &mut App) {
730        let delta = event.delta.pixel_delta(px(32.));
731        let x = f32::from(delta.x);
732        let y = f32::from(delta.y);
733        let horizontal_input = if event.modifiers.shift && x.abs() < y.abs() {
734            y
735        } else {
736            x
737        };
738        let main = if self.vertical {
739            if x.abs() > y.abs() {
740                return;
741            }
742            y
743        } else {
744            if !event.modifiers.shift && y.abs() > x.abs() {
745                return;
746            }
747            if self.direction == Direction::Rtl {
748                -horizontal_input
749            } else {
750                horizontal_input
751            }
752        };
753        if self.focus.len() < 2 || !main.is_finite() {
754            return;
755        }
756
757        let moved = self.state.update(cx, |state, cx| {
758            if event.touch_phase == TouchPhase::Cancelled {
759                return finish_gesture(state, &self.fling, true, cx);
760            }
761
762            let previous = state.requested;
763            let limit = (self.focus.len() - 1) as f32;
764            if !event.delta.precise() {
765                let sign = if main == 0. { 0. } else { main.signum() };
766                let target = (previous - sign).clamp(0., limit);
767                if target == previous {
768                    return false;
769                }
770                state.animate_scroll_to_item(target.round() as usize, cx);
771                return true;
772            }
773
774            let delta = {
775                let layout = self.layout.borrow();
776                let Some(layout) = layout.as_ref() else {
777                    return false;
778                };
779                layout.scroll_delta(previous, -main)
780            };
781            let target = (previous + delta).clamp(0., limit);
782            if target != previous {
783                state.gesture_start.get_or_insert(previous);
784                state.set_requested(target, true, cx);
785            }
786
787            if event.touch_phase == TouchPhase::Ended {
788                return finish_gesture(state, &self.fling, false, cx);
789            }
790            if target == previous {
791                return false;
792            }
793
794            // Some desktop drivers omit the terminal phase of a precise gesture.
795            let timer = cx.background_executor().timer(SCROLL_SETTLE);
796            let weak_state = cx.weak_entity();
797            let fling = self.fling.clone();
798            state.settle = Some(window.spawn(cx, async move |cx| {
799                timer.await;
800                let _ = cx.update(|window, cx| {
801                    if weak_state
802                        .update(cx, |state, cx| finish_gesture(state, &fling, false, cx))
803                        .unwrap_or(false)
804                    {
805                        window.refresh();
806                    }
807                });
808            }));
809            true
810        });
811        if !moved {
812            return;
813        }
814
815        // A pointer scroll can move already-contained focus to a visible item.
816        let target = self.state.read(cx).requested;
817        let viewport = {
818            let layout = self.layout.borrow();
819            layout
820                .as_ref()
821                .map(|layout| layout.visible(target, self.direction))
822                .unwrap_or_default()
823        };
824        let current_focus = self
825            .focus
826            .iter()
827            .position(|item| item.focus.is_focused(window));
828        if current_focus.is_some_and(|index| !viewport.iter().any(|(visible, _)| *visible == index))
829            && let Some((index, _)) = viewport
830                .iter()
831                .filter(|(index, _)| self.focus[*index].enabled)
832                .max_by(|(_, a), (_, b)| a.size.total_cmp(&b.size))
833        {
834            self.focus[*index].focus.focus(window, cx);
835        }
836        window.refresh();
837        cx.stop_propagation();
838    }
839}
840
841fn finish_gesture(
842    state: &mut CarouselState,
843    fling: &CarouselFling,
844    cancelled: bool,
845    cx: &mut gpui::Context<CarouselState>,
846) -> bool {
847    let Some(start) = state.gesture_start.take() else {
848        return false;
849    };
850    state.settle = None;
851    let position = state.requested;
852    let resting_item = if cancelled {
853        if matches!(fling, CarouselFling::Free) {
854            state.set_requested(start, true, cx);
855            None
856        } else {
857            Some(start.round() as usize)
858        }
859    } else {
860        let item = position.round() as usize;
861        let initial = start.round() as usize;
862        match fling {
863            CarouselFling::Free => None,
864            CarouselFling::Default | CarouselFling::Snap => Some(item),
865            CarouselFling::SingleAdvance => {
866                Some(item.clamp(initial.saturating_sub(1), initial + 1))
867            }
868            CarouselFling::Custom(target) => target(CarouselFlingContext {
869                start,
870                position,
871                item_count: state.items.len(),
872            }),
873        }
874    };
875    if let Some(item) = resting_item {
876        state.animate_scroll_to_item(item, cx);
877    }
878    true
879}
880
881fn focus_at_position(items: &[ItemFocus], position: f32) -> Option<usize> {
882    let index = (position.round() as usize).min(items.len().saturating_sub(1));
883    (index..items.len())
884        .chain((0..index).rev())
885        .find(|index| items[*index].enabled)
886}
887
888fn navigation_index(
889    items: &[ItemFocus],
890    position: f32,
891    key: &str,
892    vertical: bool,
893    direction: Direction,
894) -> Option<usize> {
895    if items.is_empty() {
896        return None;
897    }
898    let current = (position.round() as usize).min(items.len() - 1);
899    let forward = match key {
900        "home" => return items.iter().position(|item| item.enabled),
901        "end" => return items.iter().rposition(|item| item.enabled),
902        "up" if vertical => false,
903        "down" if vertical => true,
904        "left" if !vertical => direction == Direction::Rtl,
905        "right" if !vertical => direction == Direction::Ltr,
906        _ => return None,
907    };
908    if forward {
909        (current + 1..items.len()).find(|index| items[*index].enabled)
910    } else {
911        (0..current).rev().find(|index| items[*index].enabled)
912    }
913}