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 Element for Viewport {
470    type RequestLayoutState = ();
471    type PrepaintState = Prepaint;
472
473    fn id(&self) -> Option<ElementId> {
474        Some((self.id.clone(), "viewport").into())
475    }
476
477    fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
478        None
479    }
480
481    fn request_layout(
482        &mut self,
483        _: Option<&GlobalElementId>,
484        _: Option<&InspectorElementId>,
485        window: &mut Window,
486        cx: &mut App,
487    ) -> (LayoutId, ()) {
488        let style = Style {
489            size: size(relative(1.).into(), self.height.into()),
490            ..Style::default()
491        };
492        (window.request_layout(style, [], cx), ())
493    }
494
495    fn prepaint(
496        &mut self,
497        _: Option<&GlobalElementId>,
498        _: Option<&InspectorElementId>,
499        bounds: Bounds<Pixels>,
500        _: &mut (),
501        window: &mut Window,
502        cx: &mut App,
503    ) -> Self::PrepaintState {
504        let vertical = self.variant.is_vertical();
505        let layout = layout(
506            self.variant,
507            bounds.size.width,
508            bounds.size.height,
509            self.preferred_width,
510            self.layout_options,
511            self.items.iter().flatten(),
512        );
513        let (inset, cross) = layout.cross_bounds(self.direction);
514        let (inset, cross) = (px(inset), px(cross));
515        let mut visible = layout.visible(self.sample, self.direction);
516        // When keyboard or UI Automation focuses an item outside the current
517        // mask, reveal it in this frame rather than leaving an invisible focus
518        // target during a long animation.
519        if let Some(focused) = self.focused
520            && !self.state.read(cx).direct
521            && self.state.read(cx).requested.round() as usize == focused
522            && !visible.iter().any(|(index, item)| {
523                *index == focused
524                    && item.size >= 40.
525                    && item.start >= -0.5
526                    && item.start + item.size
527                        <= f32::from(if vertical {
528                            bounds.size.height
529                        } else {
530                            bounds.size.width
531                        }) + 0.5
532            })
533        {
534            visible = layout.visible(focused as f32, self.direction);
535        }
536        let (start, end) = layout.clip_range(self.direction);
537        *self.layout.borrow_mut() = Some(layout);
538        let mask = if vertical {
539            Bounds::new(
540                bounds.origin + point(inset, px(start)),
541                size(cross, px(end - start)),
542            )
543        } else {
544            Bounds::new(
545                bounds.origin + point(px(start), inset),
546                size(px(end - start), cross),
547            )
548        };
549        let mut children = Vec::with_capacity(visible.len());
550        let count = self.items.len();
551        window.with_content_mask(Some(ContentMask { bounds: mask }), |window| {
552            for (index, geometry) in visible {
553                let Some(item) = self.items[index].take() else {
554                    continue;
555                };
556                let (size, offset) = if vertical {
557                    (
558                        size(cross, px(geometry.size)),
559                        point(inset, px(geometry.start)),
560                    )
561                } else {
562                    (
563                        size(px(geometry.size), cross),
564                        point(px(geometry.start), inset),
565                    )
566                };
567                let radius = if vertical {
568                    0.
569                } else {
570                    CornerRole::ExtraLarge.shape().radii(
571                        f32::from(size.width),
572                        f32::from(size.height),
573                        self.direction,
574                    )[0]
575                };
576                let id = item.id;
577                let activate_id = id.clone();
578                let accessible_id = id.clone();
579                let activate = self.activate.clone();
580                let activate_accessible = activate.clone();
581                let state = self.state.clone();
582                let accessible_state = state.clone();
583                let accessible_focus = self.focus[index].focus.clone();
584                let user_scroll_enabled = self.user_scroll_enabled;
585                let content = match item.content {
586                    Content::Element(content) => content,
587                    Content::Image(source) => img(source)
588                        .size_full()
589                        .object_fit(ObjectFit::Cover)
590                        .rounded(px(radius))
591                        .into_any_element(),
592                };
593                let focused = self.focused == Some(index) && window.last_input_was_keyboard();
594                let mut child = Button::new((self.id.clone(), id))
595                    .accessibility_label(item.label)
596                    .aria_position_in_set(index + 1)
597                    .aria_size_of_set(count)
598                    .track_focus(&self.focus[index].focus)
599                    .tab_stop(self.tab_stop == Some(index))
600                    .disabled(item.disabled)
601                    .w(size.width)
602                    .h(size.height)
603                    .bg(self.surface)
604                    .rounded(px(radius))
605                    .overflow_hidden()
606                    .relative()
607                    .group("carousel-item")
608                    .when(!item.disabled, |button| {
609                        button
610                            .on_click(move |_, window, cx| {
611                                if user_scroll_enabled {
612                                    state.update(cx, |state, cx| {
613                                        state.animate_scroll_to_item(index, cx)
614                                    });
615                                }
616                                window.refresh();
617                                if let Some(activate) = &activate {
618                                    activate(&activate_id, window, cx);
619                                }
620                            })
621                            .on_a11y_action(AccessibleAction::Click, move |_, window, cx| {
622                                if user_scroll_enabled {
623                                    accessible_state.update(cx, |state, cx| {
624                                        state.animate_scroll_to_item(index, cx)
625                                    });
626                                }
627                                accessible_focus.focus(window, cx);
628                                window.refresh();
629                                if let Some(activate) = &activate_accessible {
630                                    activate(&accessible_id, window, cx);
631                                }
632                            })
633                    })
634                    .child(content)
635                    .child(
636                        div()
637                            .id("state-layer")
638                            .absolute()
639                            .inset_0()
640                            .rounded(px(radius))
641                            .when(!item.disabled, |state| {
642                                state
643                                    .group_hover("carousel-item", |style| {
644                                        style.bg(self.hover.opacity(0.08))
645                                    })
646                                    .group_active("carousel-item", |style| {
647                                        style.bg(self.hover.opacity(0.1))
648                                    })
649                                    .when(focused, |state| state.border_2().border_color(self.ring))
650                            }),
651                    )
652                    .into_any_element();
653                child.prepaint_as_root(bounds.origin + offset, size.map(Into::into), window, cx);
654                children.push(child);
655            }
656        });
657        Prepaint { children, mask }
658    }
659
660    fn paint(
661        &mut self,
662        _: Option<&GlobalElementId>,
663        _: Option<&InspectorElementId>,
664        _: Bounds<Pixels>,
665        _: &mut (),
666        state: &mut Self::PrepaintState,
667        window: &mut Window,
668        cx: &mut App,
669    ) {
670        window.with_content_mask(Some(ContentMask { bounds: state.mask }), |window| {
671            for child in &mut state.children {
672                child.paint(window, cx);
673            }
674        });
675    }
676}
677
678fn layout<'a>(
679    variant: CarouselVariant,
680    width: Pixels,
681    height: Pixels,
682    preferred_width: Pixels,
683    options: LayoutOptions,
684    items: impl IntoIterator<Item = &'a CarouselItem>,
685) -> Layout {
686    let (main, cross) = if variant.is_vertical() {
687        (height, width)
688    } else {
689        (width, height)
690    };
691    Layout::new(
692        variant,
693        main.into(),
694        cross.into(),
695        preferred_width.into(),
696        options,
697        items.into_iter().map(|item| item.aspect),
698    )
699}
700
701#[derive(Clone)]
702struct Interaction {
703    layout: Rc<RefCell<Option<Layout>>>,
704    focus: Rc<[ItemFocus]>,
705    state: Entity<CarouselState>,
706    vertical: bool,
707    direction: Direction,
708    fling: CarouselFling,
709}
710
711impl Interaction {
712    fn page(&self, delta: isize, window: &mut Window, cx: &mut App) {
713        let state = self.state.read(cx);
714        let index = (state.requested.round() as usize).saturating_add_signed(delta);
715        if index < self.focus.len() {
716            self.state
717                .update(cx, |state, cx| state.animate_scroll_to_item(index, cx));
718            window.refresh();
719        }
720    }
721
722    fn on_scroll(&self, event: &ScrollEvent, window: &mut Window, cx: &mut App) {
723        let delta = event.delta.pixel_delta(px(32.));
724        let x = f32::from(delta.x);
725        let y = f32::from(delta.y);
726        let horizontal_input = if event.modifiers.shift && x.abs() < y.abs() {
727            y
728        } else {
729            x
730        };
731        let main = if self.vertical {
732            if x.abs() > y.abs() {
733                return;
734            }
735            y
736        } else {
737            if !event.modifiers.shift && y.abs() > x.abs() {
738                return;
739            }
740            if self.direction == Direction::Rtl {
741                -horizontal_input
742            } else {
743                horizontal_input
744            }
745        };
746        if self.focus.len() < 2 || !main.is_finite() {
747            return;
748        }
749
750        let moved = self.state.update(cx, |state, cx| {
751            if event.touch_phase == TouchPhase::Cancelled {
752                return finish_gesture(state, &self.fling, true, cx);
753            }
754
755            let previous = state.requested;
756            let limit = (self.focus.len() - 1) as f32;
757            if !event.delta.precise() {
758                let sign = if main == 0. { 0. } else { main.signum() };
759                let target = (previous - sign).clamp(0., limit);
760                if target == previous {
761                    return false;
762                }
763                state.animate_scroll_to_item(target.round() as usize, cx);
764                return true;
765            }
766
767            let delta = {
768                let layout = self.layout.borrow();
769                let Some(layout) = layout.as_ref() else {
770                    return false;
771                };
772                layout.scroll_delta(previous, -main)
773            };
774            let target = (previous + delta).clamp(0., limit);
775            if target != previous {
776                state.gesture_start.get_or_insert(previous);
777                state.set_requested(target, true, cx);
778            }
779
780            if event.touch_phase == TouchPhase::Ended {
781                return finish_gesture(state, &self.fling, false, cx);
782            }
783            if target == previous {
784                return false;
785            }
786
787            // Some desktop drivers omit the terminal phase of a precise gesture.
788            let timer = cx.background_executor().timer(SCROLL_SETTLE);
789            let weak_state = cx.weak_entity();
790            let fling = self.fling.clone();
791            state.settle = Some(window.spawn(cx, async move |cx| {
792                timer.await;
793                let _ = cx.update(|window, cx| {
794                    if weak_state
795                        .update(cx, |state, cx| finish_gesture(state, &fling, false, cx))
796                        .unwrap_or(false)
797                    {
798                        window.refresh();
799                    }
800                });
801            }));
802            true
803        });
804        if !moved {
805            return;
806        }
807
808        // A pointer scroll can move already-contained focus to a visible item.
809        let target = self.state.read(cx).requested;
810        let viewport = {
811            let layout = self.layout.borrow();
812            layout
813                .as_ref()
814                .map(|layout| layout.visible(target, self.direction))
815                .unwrap_or_default()
816        };
817        let current_focus = self
818            .focus
819            .iter()
820            .position(|item| item.focus.is_focused(window));
821        if current_focus.is_some_and(|index| !viewport.iter().any(|(visible, _)| *visible == index))
822            && let Some((index, _)) = viewport
823                .iter()
824                .filter(|(index, _)| self.focus[*index].enabled)
825                .max_by(|(_, a), (_, b)| a.size.total_cmp(&b.size))
826        {
827            self.focus[*index].focus.focus(window, cx);
828        }
829        window.refresh();
830        cx.stop_propagation();
831    }
832}
833
834fn finish_gesture(
835    state: &mut CarouselState,
836    fling: &CarouselFling,
837    cancelled: bool,
838    cx: &mut gpui::Context<CarouselState>,
839) -> bool {
840    let Some(start) = state.gesture_start.take() else {
841        return false;
842    };
843    state.settle = None;
844    let position = state.requested;
845    let resting_item = if cancelled {
846        if matches!(fling, CarouselFling::Free) {
847            state.set_requested(start, true, cx);
848            None
849        } else {
850            Some(start.round() as usize)
851        }
852    } else {
853        let item = position.round() as usize;
854        let initial = start.round() as usize;
855        match fling {
856            CarouselFling::Free => None,
857            CarouselFling::Default | CarouselFling::Snap => Some(item),
858            CarouselFling::SingleAdvance => {
859                Some(item.clamp(initial.saturating_sub(1), initial + 1))
860            }
861            CarouselFling::Custom(target) => target(CarouselFlingContext {
862                start,
863                position,
864                item_count: state.items.len(),
865            }),
866        }
867    };
868    if let Some(item) = resting_item {
869        state.animate_scroll_to_item(item, cx);
870    }
871    true
872}
873
874fn focus_at_position(items: &[ItemFocus], position: f32) -> Option<usize> {
875    let index = (position.round() as usize).min(items.len().saturating_sub(1));
876    (index..items.len())
877        .chain((0..index).rev())
878        .find(|index| items[*index].enabled)
879}
880
881fn navigation_index(
882    items: &[ItemFocus],
883    position: f32,
884    key: &str,
885    vertical: bool,
886    direction: Direction,
887) -> Option<usize> {
888    if items.is_empty() {
889        return None;
890    }
891    let current = (position.round() as usize).min(items.len() - 1);
892    let forward = match key {
893        "home" => return items.iter().position(|item| item.enabled),
894        "end" => return items.iter().rposition(|item| item.enabled),
895        "up" if vertical => false,
896        "down" if vertical => true,
897        "left" if !vertical => direction == Direction::Rtl,
898        "right" if !vertical => direction == Direction::Ltr,
899        _ => return None,
900    };
901    if forward {
902        (current + 1..items.len()).find(|index| items[*index].enabled)
903    } else {
904        (0..current).rev().find(|index| items[*index].enabled)
905    }
906}