Skip to main content

gpui_component/carousel/
carousel.rs

1use std::{panic::Location, sync::Arc};
2
3use gpui::{
4    AnyElement, App, Axis, Bounds, ClickEvent, Element, ElementId, Entity, FocusHandle, Focusable,
5    GlobalElementId, InspectorElementId, InteractiveElement as _, IntoElement, LayoutId,
6    MouseButton, ParentElement, Pixels, Point, RenderOnce, Role, SharedString,
7    StatefulInteractiveElement as _, StyleRefinement, Styled, Subscription, Window, div,
8    prelude::FluentBuilder as _, px,
9};
10use gpui_base::spring;
11use rust_i18n::t;
12
13use super::{CONTEXT, scroll_mask::CarouselScrollMask, state::CarouselState};
14use crate::{
15    AxisExt as _, Disableable as _, ElementExt as _, Selectable as _, Sizable as _, Size,
16    StyledExt as _, ThemeStyled as _,
17    actions::{SelectDown, SelectFirst, SelectLast, SelectLeft, SelectRight, SelectUp},
18    button::Button,
19    icon::IconName,
20    theme::ActiveTheme as _,
21};
22
23/// A composable carousel root.
24///
25/// Add one [`CarouselContent`] and any optional controls as children. Every
26/// part must share the same [`CarouselState`].
27#[derive(IntoElement)]
28pub struct Carousel {
29    id: ElementId,
30    state: Entity<CarouselState>,
31    style: StyleRefinement,
32    accessibility_label: SharedString,
33    focus_ring_enabled: bool,
34    children: Vec<AnyElement>,
35}
36
37struct CarouselStateObserver {
38    _subscription: Subscription,
39}
40
41/// Restores the focus ring once the carousel loses focus, so the next
42/// keyboard focus draws it again.
43struct CarouselFocusOut {
44    _subscription: Subscription,
45}
46
47impl Carousel {
48    /// Creates a Carousel bound to `state`.
49    pub fn new(id: impl Into<ElementId>, state: &Entity<CarouselState>) -> Self {
50        Self {
51            id: id.into(),
52            state: state.clone(),
53            style: StyleRefinement::default(),
54            accessibility_label: t!("Carousel.label").into(),
55            focus_ring_enabled: true,
56            children: Vec::new(),
57        }
58    }
59
60    /// Sets the name announced for the carousel region.
61    pub fn accessibility_label(mut self, label: impl Into<SharedString>) -> Self {
62        self.accessibility_label = label.into();
63        self
64    }
65}
66
67impl ParentElement for Carousel {
68    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
69        self.children.extend(elements);
70    }
71}
72
73impl Styled for Carousel {
74    fn style(&mut self) -> &mut StyleRefinement {
75        &mut self.style
76    }
77}
78
79impl crate::FocusableExt for Carousel {
80    fn focus_ring(mut self, enabled: bool) -> Self {
81        self.focus_ring_enabled = enabled;
82        self
83    }
84
85    fn is_focus_ring_enabled(&self) -> bool {
86        self.focus_ring_enabled
87    }
88}
89
90impl RenderOnce for Carousel {
91    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
92        let observed_state = self.state.clone();
93        let _observer = window.use_keyed_state(
94            ("carousel-state-observer", self.state.entity_id()),
95            cx,
96            move |_, cx| CarouselStateObserver {
97                _subscription: cx.observe(&observed_state, |_, _, cx| cx.notify()),
98            },
99        );
100        let snapshot = self.state.read(cx);
101        let axis = snapshot.axis();
102        let frame_size = snapshot.frame_size();
103        let focus_handle = snapshot.focus_handle(cx);
104        let ring_suppressed = snapshot.is_focus_ring_suppressed();
105        let _focus_out =
106            window.use_keyed_state(("carousel-focus-out", self.state.entity_id()), cx, {
107                let state = self.state.clone();
108                let focus_handle = focus_handle.clone();
109                move |window, cx| CarouselFocusOut {
110                    _subscription: window.on_focus_out(&focus_handle, cx, move |_, _, cx| {
111                        state.update(cx, |state, _| state.suppress_focus_ring(false));
112                    }),
113                }
114            });
115        let is_focused = focus_handle.is_focused(window);
116        let focus_visible = is_focused && !ring_suppressed && self.focus_ring_enabled;
117        let previous_state = self.state.clone();
118        let next_state = self.state.clone();
119        let first_state = self.state.clone();
120        let last_state = self.state.clone();
121
122        div()
123            .id(self.id)
124            .relative()
125            .flex()
126            .flex_col()
127            .gap_4()
128            .role(Role::Region)
129            .aria_label(self.accessibility_label)
130            .track_focus(&focus_handle.tab_stop(true))
131            .key_context(CONTEXT)
132            .on_mouse_down(MouseButton::Left, {
133                let state = self.state.clone();
134                move |_, window, cx| {
135                    // Runs before GPUI moves focus here. A child such as
136                    // Button that keeps focus has already prevented the default.
137                    if !is_focused && !window.default_prevented() {
138                        state.update(cx, |state, _| state.suppress_focus_ring(true));
139                    }
140                }
141            })
142            .on_action(
143                window.listener_for(&previous_state, move |state, _: &SelectLeft, _, cx| {
144                    let handled = axis.is_horizontal() && state.select_previous(cx);
145                    if !handled {
146                        cx.propagate();
147                    }
148                }),
149            )
150            .on_action(
151                window.listener_for(&next_state, move |state, _: &SelectRight, _, cx| {
152                    let handled = axis.is_horizontal() && state.select_next(cx);
153                    if !handled {
154                        cx.propagate();
155                    }
156                }),
157            )
158            .on_action(
159                window.listener_for(&previous_state, move |state, _: &SelectUp, _, cx| {
160                    let handled = axis.is_vertical() && state.select_previous(cx);
161                    if !handled {
162                        cx.propagate();
163                    }
164                }),
165            )
166            .on_action(
167                window.listener_for(&next_state, move |state, _: &SelectDown, _, cx| {
168                    let handled = axis.is_vertical() && state.select_next(cx);
169                    if !handled {
170                        cx.propagate();
171                    }
172                }),
173            )
174            .on_action(
175                window.listener_for(&first_state, |state, _: &SelectFirst, _, cx| {
176                    if !state.select_first(cx) {
177                        cx.propagate();
178                    }
179                }),
180            )
181            .on_action(
182                window.listener_for(&last_state, |state, _: &SelectLast, _, cx| {
183                    if !state.select_last(cx) {
184                        cx.propagate();
185                    }
186                }),
187            )
188            .children(self.children)
189            .when(focus_visible, |this| {
190                this.when_some(frame_size, |this, size| {
191                    this.child(
192                        div()
193                            .absolute()
194                            .top_0()
195                            .left_0()
196                            .w(size.width)
197                            .h(size.height)
198                            .border_1()
199                            .border_color(cx.theme().transparent)
200                            .rounded(cx.theme().radius)
201                            .focus_ring_style(window, cx),
202                    )
203                })
204            })
205            .refine_style(&self.style)
206    }
207}
208
209#[derive(Default, PartialEq)]
210struct CarouselGeometry {
211    viewport: Bounds<Pixels>,
212    frame: Bounds<Pixels>,
213    items: Vec<Bounds<Pixels>>,
214    has_runway: bool,
215    revision: usize,
216}
217
218impl CarouselGeometry {
219    /// Reads the layout relative to the content `frame` origin.
220    ///
221    /// Window-space bounds move whenever an ancestor scrolls or shifts the
222    /// carousel, while every snap and loop calculation uses only differences
223    /// and sizes. Storing frame-relative bounds keeps those moves from being
224    /// treated as layout changes.
225    fn read(
226        state: &CarouselState,
227        frame: Bounds<Pixels>,
228        has_runway: bool,
229        rendered_item_count: usize,
230    ) -> Self {
231        let handle = state.scroll_handle();
232        let item_offset = usize::from(has_runway);
233        let origin = frame.origin;
234        let relative = |bounds: Bounds<Pixels>| Bounds::new(bounds.origin - origin, bounds.size);
235        Self {
236            viewport: relative(handle.bounds()),
237            frame: Bounds::new(Point::default(), frame.size),
238            items: (0..state.item_count().min(rendered_item_count))
239                .filter_map(|ix| handle.bounds_for_item(ix + item_offset).map(&relative))
240                .collect(),
241            has_runway,
242            revision: 0,
243        }
244    }
245
246    /// Compares layouts with a sub-pixel tolerance so float noise from the
247    /// frame-relative subtraction does not register as a layout change.
248    fn same_layout(&self, other: &Self) -> bool {
249        self.has_runway == other.has_runway
250            && same_bounds(self.viewport, other.viewport)
251            && same_bounds(self.frame, other.frame)
252            && self.items.len() == other.items.len()
253            && self
254                .items
255                .iter()
256                .zip(&other.items)
257                .all(|(left, right)| same_bounds(*left, *right))
258    }
259}
260
261fn same_bounds(left: Bounds<Pixels>, right: Bounds<Pixels>) -> bool {
262    const TOLERANCE: Pixels = px(0.01);
263    (left.origin.x - right.origin.x).abs() <= TOLERANCE
264        && (left.origin.y - right.origin.y).abs() <= TOLERANCE
265        && (left.size.width - right.size.width).abs() <= TOLERANCE
266        && (left.size.height - right.size.height).abs() <= TOLERANCE
267}
268
269/// The clipped viewport and snap track for Carousel items.
270#[derive(IntoElement)]
271pub struct CarouselContent {
272    state: Entity<CarouselState>,
273    style: StyleRefinement,
274    track_style: StyleRefinement,
275    children: Vec<AnyElement>,
276}
277
278impl CarouselContent {
279    /// Creates content bound to `state`.
280    pub fn new(state: &Entity<CarouselState>) -> Self {
281        Self {
282            state: state.clone(),
283            style: StyleRefinement::default(),
284            track_style: StyleRefinement::default(),
285            children: Vec::new(),
286        }
287    }
288
289    /// Sets style overrides for the inner flex track.
290    ///
291    /// Use this for paired Carousel spacing such as a negative leading margin.
292    /// The [`Styled`] implementation applies to the clipped viewport itself.
293    pub fn track_style(mut self, style: StyleRefinement) -> Self {
294        self.track_style = style;
295        self
296    }
297}
298
299impl ParentElement for CarouselContent {
300    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
301        self.children.extend(elements);
302    }
303}
304
305impl Styled for CarouselContent {
306    fn style(&mut self) -> &mut StyleRefinement {
307        &mut self.style
308    }
309}
310
311/// A layout-transparent proxy that paints one real item in the closest loop
312/// cycle. The child keeps its original layout id, so ScrollHandle geometry
313/// continues to address logical items without cloning their elements.
314struct CarouselLoopItem {
315    child: AnyElement,
316    index: usize,
317    state: Entity<CarouselState>,
318}
319
320impl Element for CarouselLoopItem {
321    type RequestLayoutState = ();
322    type PrepaintState = Point<Pixels>;
323
324    fn id(&self) -> Option<ElementId> {
325        None
326    }
327
328    fn source_location(&self) -> Option<&'static Location<'static>> {
329        None
330    }
331
332    fn request_layout(
333        &mut self,
334        _: Option<&GlobalElementId>,
335        _: Option<&InspectorElementId>,
336        window: &mut Window,
337        cx: &mut App,
338    ) -> (LayoutId, Self::RequestLayoutState) {
339        (self.child.request_layout(window, cx), ())
340    }
341
342    fn prepaint(
343        &mut self,
344        _: Option<&GlobalElementId>,
345        _: Option<&InspectorElementId>,
346        _: Bounds<Pixels>,
347        _: &mut Self::RequestLayoutState,
348        window: &mut Window,
349        cx: &mut App,
350    ) -> Self::PrepaintState {
351        let offset = self.state.read(cx).loop_item_offset(self.index);
352        window.with_element_offset(offset, |window| {
353            self.child.prepaint(window, cx);
354        });
355        offset
356    }
357
358    fn paint(
359        &mut self,
360        _: Option<&GlobalElementId>,
361        _: Option<&InspectorElementId>,
362        _: Bounds<Pixels>,
363        _: &mut Self::RequestLayoutState,
364        _: &mut Self::PrepaintState,
365        window: &mut Window,
366        cx: &mut App,
367    ) {
368        self.child.paint(window, cx);
369    }
370}
371
372impl RenderOnce for CarouselContent {
373    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
374        let entity_id = self.state.entity_id();
375        let snapshot = self.state.read(cx);
376        let axis = snapshot.axis();
377        let selected_ix = snapshot.selected_index();
378        let item_count = snapshot.item_count();
379        let handle = snapshot.scroll_handle().clone();
380        let interacting = snapshot.is_interacting();
381        let motion_revision = snapshot.motion_revision();
382        let loop_runway = snapshot.loop_runway();
383        let loop_layout_transitioning = snapshot.is_loop_layout_transitioning();
384        let state_snap_target = selected_ix.and_then(|ix| snapshot.motion_target_for(ix));
385
386        let geometry = window.use_keyed_state(
387            ElementId::NamedChild(
388                Arc::new(("carousel-geometry", entity_id).into()),
389                "content".into(),
390            ),
391            cx,
392            |_, _| CarouselGeometry::default(),
393        );
394        let geometry_revision = geometry.read(cx).revision;
395
396        let current = axis_value(handle.offset(), axis);
397        let target = if loop_layout_transitioning {
398            current
399        } else {
400            state_snap_target
401                .map(|target| axis_value(target, axis))
402                .or_else(|| {
403                    selected_ix.and_then(|ix| {
404                        snap_offset(&handle, axis, ix + usize::from(loop_runway.is_some()))
405                    })
406                })
407                .unwrap_or(current)
408        };
409        let target = if interacting { current } else { target };
410        let snap_spring = cx.theme().motion_tokens().spring_move.with_epsilon(0.5);
411        let animated = spring(
412            (
413                ("carousel-content", entity_id),
414                SharedString::from(format!("offset-{motion_revision}-{geometry_revision}")),
415            ),
416            target.as_f32(),
417            snap_spring.with_travel(!interacting),
418            window,
419            cx,
420        );
421        let mut offset = handle.offset();
422        set_axis_value(&mut offset, axis, px(animated));
423        set_axis_value(
424            &mut offset,
425            if axis.is_horizontal() {
426                Axis::Vertical
427            } else {
428                Axis::Horizontal
429            },
430            Pixels::ZERO,
431        );
432        handle.set_offset(offset);
433        if !interacting {
434            let rendered = offset;
435            if let Some(rebased) = self
436                .state
437                .update(cx, |state, cx| state.settle_loop_motion(rendered, cx))
438            {
439                offset = rebased;
440                handle.set_offset(offset);
441            }
442        }
443
444        let geometry_state = self.state.clone();
445        let viewport_id: ElementId = ("carousel-content", entity_id).into();
446
447        let rendered_item_count = self.children.len();
448        let loop_state = self.state.clone();
449        let children = self
450            .children
451            .into_iter()
452            .enumerate()
453            .map(move |(index, child)| CarouselLoopItem {
454                child,
455                index,
456                state: loop_state.clone(),
457            });
458        let runway_spacer = |runway: Pixels| {
459            div()
460                .flex_none()
461                .when(axis.is_horizontal(), |this| this.w(runway))
462                .when(axis.is_vertical(), |this| this.h(runway))
463        };
464        let has_runway = loop_runway.is_some();
465
466        div()
467            .relative()
468            .w_full()
469            .flex()
470            .when(axis.is_horizontal(), |this| this.flex_row())
471            .when(axis.is_vertical(), |this| this.flex_col())
472            .refine_style(&self.style)
473            .overflow_hidden()
474            .child(
475                // As a flex child the track grows by its negative leading
476                // margin, so the padded items fill the frame on both edges.
477                div()
478                    .id(viewport_id.clone())
479                    .flex_1()
480                    .flex()
481                    .when(axis.is_horizontal(), |this| {
482                        this.flex_row().min_w_0().ml_neg_4()
483                    })
484                    .when(axis.is_vertical(), |this| {
485                        this.flex_col().min_h_0().mt_neg_4()
486                    })
487                    .track_scroll(&handle)
488                    .when_some(loop_runway, |this, runway| {
489                        this.child(runway_spacer(runway))
490                    })
491                    .children(children)
492                    .when_some(loop_runway, |this, runway| {
493                        this.child(runway_spacer(runway))
494                    })
495                    .refine_style(&self.track_style),
496            )
497            .child(CarouselScrollMask::new(axis, &self.state).id(viewport_id))
498            .on_prepaint(move |frame, _, cx| {
499                let next = CarouselGeometry::read(
500                    geometry_state.read(cx),
501                    frame,
502                    has_runway,
503                    rendered_item_count,
504                );
505                if !geometry.read(cx).same_layout(&next) {
506                    geometry_state.update(cx, |state, _| {
507                        state.set_geometry_with_runway(
508                            next.viewport,
509                            next.frame,
510                            next.items.clone(),
511                            next.has_runway,
512                        );
513                    });
514                    geometry.update(cx, |current, cx| {
515                        current.viewport = next.viewport;
516                        current.frame = next.frame;
517                        current.items = next.items;
518                        current.has_runway = next.has_runway;
519                        current.revision = current.revision.wrapping_add(1);
520                        cx.notify();
521                    });
522                }
523            })
524            .when(item_count == 0, |this| this.invisible())
525    }
526}
527
528/// One logical slide in a [`CarouselContent`].
529#[derive(IntoElement)]
530pub struct CarouselItem {
531    id: ElementId,
532    index: usize,
533    state: Entity<CarouselState>,
534    style: StyleRefinement,
535    accessibility_label: Option<SharedString>,
536    children: Vec<AnyElement>,
537}
538
539impl CarouselItem {
540    /// Creates the item at the zero-based `index` used by `state`.
541    pub fn new(id: impl Into<ElementId>, index: usize, state: &Entity<CarouselState>) -> Self {
542        Self {
543            id: id.into(),
544            index,
545            state: state.clone(),
546            style: StyleRefinement::default(),
547            accessibility_label: None,
548            children: Vec::new(),
549        }
550    }
551
552    /// Replaces the generated "Slide N of M" accessibility label.
553    pub fn accessibility_label(mut self, label: impl Into<SharedString>) -> Self {
554        self.accessibility_label = Some(label.into());
555        self
556    }
557}
558
559impl ParentElement for CarouselItem {
560    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
561        self.children.extend(elements);
562    }
563}
564
565impl Styled for CarouselItem {
566    fn style(&mut self) -> &mut StyleRefinement {
567        &mut self.style
568    }
569}
570
571impl RenderOnce for CarouselItem {
572    fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
573        let state = self.state.read(cx);
574        let axis = state.axis();
575        let count = state.item_count();
576        let label = self.accessibility_label.unwrap_or_else(|| {
577            t!(
578                "Carousel.slide",
579                current = self.index.saturating_add(1),
580                total = count
581            )
582            .into()
583        });
584
585        div()
586            .id(self.id)
587            .role(Role::Group)
588            .aria_label(label)
589            .aria_position_in_set(self.index.saturating_add(1))
590            .aria_size_of_set(count)
591            .min_w_0()
592            .min_h_0()
593            .flex_none()
594            .when(axis.is_horizontal(), |this| this.w_full().pl_4())
595            .when(axis.is_vertical(), |this| this.h_full().pt_4())
596            .children(self.children)
597            .refine_style(&self.style)
598    }
599}
600
601/// A previous-slide control positioned around the Carousel viewport.
602#[derive(IntoElement)]
603pub struct CarouselPrevious {
604    state: Entity<CarouselState>,
605    size: Size,
606    style: StyleRefinement,
607    accessibility_label: Option<SharedString>,
608    children: Vec<AnyElement>,
609}
610
611impl CarouselPrevious {
612    /// Creates a previous-slide control bound to `state`.
613    pub fn new(state: &Entity<CarouselState>) -> Self {
614        Self {
615            state: state.clone(),
616            size: Size::Medium,
617            style: StyleRefinement::default(),
618            accessibility_label: None,
619            children: Vec::new(),
620        }
621    }
622
623    /// Replaces the generated previous-slide accessibility label and tooltip.
624    pub fn accessibility_label(mut self, label: impl Into<SharedString>) -> Self {
625        self.accessibility_label = Some(label.into());
626        self
627    }
628}
629
630impl crate::Sizable for CarouselPrevious {
631    fn with_size(mut self, size: impl Into<Size>) -> Self {
632        self.size = size.into();
633        self
634    }
635}
636
637impl Styled for CarouselPrevious {
638    fn style(&mut self) -> &mut StyleRefinement {
639        &mut self.style
640    }
641}
642
643impl ParentElement for CarouselPrevious {
644    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
645        self.children.extend(elements);
646    }
647}
648
649impl RenderOnce for CarouselPrevious {
650    fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
651        carousel_control(
652            self.state,
653            self.size,
654            self.style,
655            self.accessibility_label,
656            self.children,
657            false,
658            cx,
659        )
660    }
661}
662
663/// A next-slide control positioned around the Carousel viewport.
664#[derive(IntoElement)]
665pub struct CarouselNext {
666    state: Entity<CarouselState>,
667    size: Size,
668    style: StyleRefinement,
669    accessibility_label: Option<SharedString>,
670    children: Vec<AnyElement>,
671}
672
673impl CarouselNext {
674    /// Creates a next-slide control bound to `state`.
675    pub fn new(state: &Entity<CarouselState>) -> Self {
676        Self {
677            state: state.clone(),
678            size: Size::Medium,
679            style: StyleRefinement::default(),
680            accessibility_label: None,
681            children: Vec::new(),
682        }
683    }
684
685    /// Replaces the generated next-slide accessibility label and tooltip.
686    pub fn accessibility_label(mut self, label: impl Into<SharedString>) -> Self {
687        self.accessibility_label = Some(label.into());
688        self
689    }
690}
691
692impl crate::Sizable for CarouselNext {
693    fn with_size(mut self, size: impl Into<Size>) -> Self {
694        self.size = size.into();
695        self
696    }
697}
698
699impl Styled for CarouselNext {
700    fn style(&mut self) -> &mut StyleRefinement {
701        &mut self.style
702    }
703}
704
705impl ParentElement for CarouselNext {
706    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
707        self.children.extend(elements);
708    }
709}
710
711impl RenderOnce for CarouselNext {
712    fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
713        carousel_control(
714            self.state,
715            self.size,
716            self.style,
717            self.accessibility_label,
718            self.children,
719            true,
720            cx,
721        )
722    }
723}
724
725fn carousel_control(
726    state: Entity<CarouselState>,
727    size: Size,
728    style: StyleRefinement,
729    accessibility_label: Option<SharedString>,
730    children: Vec<AnyElement>,
731    next: bool,
732    cx: &mut App,
733) -> impl IntoElement {
734    let snapshot = state.read(cx);
735    let axis = snapshot.axis();
736    let frame_size = snapshot.frame_size();
737    let focus_handle = snapshot.focus_handle(cx);
738    let disabled = if next {
739        !snapshot.has_next()
740    } else {
741        !snapshot.has_previous()
742    };
743    let (name, default_label, icon) = match (axis, next) {
744        (Axis::Horizontal, false) => ("previous", t!("Carousel.previous"), IconName::ChevronLeft),
745        (Axis::Horizontal, true) => ("next", t!("Carousel.next"), IconName::ChevronRight),
746        (Axis::Vertical, false) => ("previous", t!("Carousel.previous"), IconName::ChevronUp),
747        (Axis::Vertical, true) => ("next", t!("Carousel.next"), IconName::ChevronDown),
748    };
749    let label = accessibility_label.unwrap_or_else(|| default_label.into());
750    let has_custom_content = !children.is_empty();
751    let id = ElementId::NamedChild(
752        Arc::new(("carousel-control", state.entity_id()).into()),
753        name.into(),
754    );
755
756    div()
757        .absolute()
758        .top_0()
759        .left_0()
760        .when_some(frame_size, |this, size| this.w(size.width).h(size.height))
761        .when(frame_size.is_none(), |this| this.right_0().bottom_0())
762        .child(
763            Button::new(id)
764                .outline()
765                .with_size(size)
766                .when(!has_custom_content, |this| this.icon(icon))
767                .accessibility_label(label.clone())
768                .tooltip(label)
769                .disabled(disabled)
770                .absolute()
771                .rounded_full_style(cx)
772                .when(axis.is_horizontal() && !next, |this| {
773                    this.right_full().mr_4().top_0().bottom_0().my_auto()
774                })
775                .when(axis.is_horizontal() && next, |this| {
776                    this.left_full().ml_4().top_0().bottom_0().my_auto()
777                })
778                .when(axis.is_vertical() && !next, |this| {
779                    this.bottom_full().mb_4().left_0().right_0().mx_auto()
780                })
781                .when(axis.is_vertical() && next, |this| {
782                    this.top_full().mt_4().left_0().right_0().mx_auto()
783                })
784                .when(!disabled, |this| {
785                    this.on_click(move |event, window, cx| {
786                        state.update(cx, |state, cx| {
787                            if next {
788                                state.select_next(cx);
789                            } else {
790                                state.select_previous(cx);
791                            }
792                        });
793                        focus_after_pointer_click(&state, &focus_handle, event, window, cx);
794                    })
795                })
796                .children(children)
797                .refine_style(&style),
798        )
799}
800
801/// A composable container for Carousel pagination items.
802#[derive(IntoElement)]
803pub struct CarouselPagination {
804    id: ElementId,
805    style: StyleRefinement,
806    accessibility_label: SharedString,
807    children: Vec<AnyElement>,
808}
809
810impl CarouselPagination {
811    /// Creates an empty pagination container.
812    #[track_caller]
813    pub fn new() -> Self {
814        Self {
815            id: ElementId::CodeLocation(*Location::caller()),
816            style: StyleRefinement::default(),
817            accessibility_label: t!("Carousel.pagination").into(),
818            children: Vec::new(),
819        }
820    }
821
822    /// Sets the name announced for the pagination group.
823    pub fn accessibility_label(mut self, label: impl Into<SharedString>) -> Self {
824        self.accessibility_label = label.into();
825        self
826    }
827}
828
829impl ParentElement for CarouselPagination {
830    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
831        self.children.extend(elements);
832    }
833}
834
835impl Styled for CarouselPagination {
836    fn style(&mut self) -> &mut StyleRefinement {
837        &mut self.style
838    }
839}
840
841impl RenderOnce for CarouselPagination {
842    fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
843        div()
844            .id(self.id)
845            .role(Role::Group)
846            .aria_label(self.accessibility_label)
847            .flex()
848            .items_center()
849            .justify_center()
850            .gap_2()
851            .children(self.children)
852            .refine_style(&self.style)
853    }
854}
855
856/// One application-styled pagination control for a Carousel item.
857#[derive(IntoElement)]
858pub struct CarouselPaginationItem {
859    id: ElementId,
860    index: usize,
861    state: Entity<CarouselState>,
862    size: Size,
863    style: StyleRefinement,
864    accessibility_label: Option<SharedString>,
865    children: Vec<AnyElement>,
866}
867
868impl CarouselPaginationItem {
869    /// Creates a pagination item for the zero-based `index`.
870    pub fn new(id: impl Into<ElementId>, index: usize, state: &Entity<CarouselState>) -> Self {
871        Self {
872            id: id.into(),
873            index,
874            state: state.clone(),
875            size: Size::XSmall,
876            style: StyleRefinement::default(),
877            accessibility_label: None,
878            children: Vec::new(),
879        }
880    }
881
882    /// Replaces the generated "Go to slide N" accessibility label.
883    pub fn accessibility_label(mut self, label: impl Into<SharedString>) -> Self {
884        self.accessibility_label = Some(label.into());
885        self
886    }
887}
888
889impl crate::Sizable for CarouselPaginationItem {
890    fn with_size(mut self, size: impl Into<Size>) -> Self {
891        self.size = size.into();
892        self
893    }
894}
895
896impl ParentElement for CarouselPaginationItem {
897    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
898        self.children.extend(elements);
899    }
900}
901
902impl Styled for CarouselPaginationItem {
903    fn style(&mut self) -> &mut StyleRefinement {
904        &mut self.style
905    }
906}
907
908impl RenderOnce for CarouselPaginationItem {
909    fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
910        let selected = self.state.read(cx).selected_index() == Some(self.index);
911        let disabled = self.index >= self.state.read(cx).item_count();
912        let focus_handle = self.state.read(cx).focus_handle(cx);
913        let label = self.accessibility_label.unwrap_or_else(|| {
914            t!(
915                "Carousel.go_to_slide",
916                current = self.index.saturating_add(1)
917            )
918            .into()
919        });
920        let state = self.state;
921        let index = self.index;
922
923        Button::new(self.id)
924            .compact()
925            .with_size(self.size)
926            .selected(selected)
927            .accessibility_label(label)
928            .disabled(disabled)
929            .children(self.children)
930            .when(!disabled, |this| {
931                this.on_click(move |event, window, cx| {
932                    state.update(cx, |state, cx| {
933                        state.select_index(index, cx);
934                    });
935                    focus_after_pointer_click(&state, &focus_handle, event, window, cx);
936                })
937            })
938            .refine_style(&self.style)
939    }
940}
941
942/// Moves keyboard focus to the carousel after a pointer click on one of its
943/// controls, so the arrow keys keep working without drawing the ring. A
944/// keyboard activation leaves focus on the control.
945fn focus_after_pointer_click(
946    state: &Entity<CarouselState>,
947    focus_handle: &FocusHandle,
948    event: &ClickEvent,
949    window: &mut Window,
950    cx: &mut App,
951) {
952    if event.is_keyboard() || focus_handle.contains_focused(window, cx) {
953        return;
954    }
955    state.update(cx, |state, _| state.suppress_focus_ring(true));
956    window.focus(focus_handle, cx);
957}
958
959fn axis_value(point: Point<Pixels>, axis: Axis) -> Pixels {
960    if axis.is_horizontal() {
961        point.x
962    } else {
963        point.y
964    }
965}
966
967fn set_axis_value(point: &mut Point<Pixels>, axis: Axis, value: Pixels) {
968    if axis.is_horizontal() {
969        point.x = value;
970    } else {
971        point.y = value;
972    }
973}
974
975fn snap_offset(handle: &gpui::ScrollHandle, axis: Axis, index: usize) -> Option<Pixels> {
976    let viewport = handle.bounds();
977    let item = handle.bounds_for_item(index)?;
978    let target = if axis.is_horizontal() {
979        viewport.left() - item.left()
980    } else {
981        viewport.top() - item.top()
982    };
983    let max = axis_value(handle.max_offset(), axis).max(Pixels::ZERO);
984    Some(target.clamp(-max, Pixels::ZERO))
985}
986
987#[cfg(test)]
988mod tests {
989    use std::{cell::Cell, rc::Rc};
990
991    use super::*;
992    use gpui::{AppContext as _, Context, Render, VisualTestContext, point};
993    use gpui_base::FocusableExt as _;
994
995    #[test]
996    fn axis_helpers_only_change_the_requested_coordinate() {
997        let mut value = point(px(3.), px(7.));
998        set_axis_value(&mut value, Axis::Horizontal, px(11.));
999        assert_eq!(value, point(px(11.), px(7.)));
1000        set_axis_value(&mut value, Axis::Vertical, px(-5.));
1001        assert_eq!(value, point(px(11.), px(-5.)));
1002    }
1003
1004    #[gpui::test]
1005    fn carousel_controls_accept_semantic_sizes(cx: &mut gpui::TestAppContext) {
1006        let state = cx.update(|cx| cx.new(|_| CarouselState::new(2)));
1007
1008        assert_eq!(CarouselPrevious::new(&state).size, Size::Medium);
1009        assert_eq!(CarouselNext::new(&state).size, Size::Medium);
1010        assert_eq!(CarouselPrevious::new(&state).large().size, Size::Large);
1011        assert_eq!(CarouselNext::new(&state).xsmall().size, Size::XSmall);
1012        assert_eq!(
1013            CarouselPaginationItem::new("pagination", 0, &state)
1014                .small()
1015                .size,
1016            Size::Small
1017        );
1018    }
1019
1020    #[gpui::test]
1021    fn carousel_focus_ring_is_configurable(cx: &mut gpui::TestAppContext) {
1022        let state = cx.update(|cx| cx.new(|_| CarouselState::new(2)));
1023
1024        assert!(Carousel::new("carousel", &state).is_focus_ring_enabled());
1025        assert!(
1026            !Carousel::new("carousel", &state)
1027                .focus_ring(false)
1028                .is_focus_ring_enabled()
1029        );
1030    }
1031
1032    struct KeyboardHarness {
1033        state: Entity<CarouselState>,
1034    }
1035
1036    impl Render for KeyboardHarness {
1037        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1038            div().tab_group().child(
1039                Carousel::new("carousel", &self.state)
1040                    .w(px(100.))
1041                    .h(px(100.))
1042                    .child(
1043                        CarouselContent::new(&self.state)
1044                            .h(px(100.))
1045                            .children((0..3).map(|index| {
1046                                CarouselItem::new(("carousel-item", index), index, &self.state)
1047                                    .child(index.to_string())
1048                            })),
1049                    ),
1050            )
1051        }
1052    }
1053
1054    fn assert_contextual_navigation_keys(cx: &mut gpui::TestAppContext, axis: Axis) {
1055        cx.update(crate::init);
1056        let state = cx.update(|cx| cx.new(|_| CarouselState::new(3).with_axis(axis)));
1057        let (_, cx) = cx.add_window_view({
1058            let state = state.clone();
1059            move |_, _| KeyboardHarness { state }
1060        });
1061        cx.update(|window, cx| window.draw(cx).clear(cx));
1062
1063        cx.update(|window, cx| window.focus_next(cx));
1064        let (primary, secondary) = if axis.is_horizontal() {
1065            ("right", "down")
1066        } else {
1067            ("down", "right")
1068        };
1069        cx.simulate_keystrokes(primary);
1070        assert_eq!(
1071            state.read_with(cx, |state, _| state.selected_index()),
1072            Some(1)
1073        );
1074        cx.simulate_keystrokes(secondary);
1075        assert_eq!(
1076            state.read_with(cx, |state, _| state.selected_index()),
1077            Some(1)
1078        );
1079        cx.simulate_keystrokes("end");
1080        assert_eq!(
1081            state.read_with(cx, |state, _| state.selected_index()),
1082            Some(2)
1083        );
1084        cx.simulate_keystrokes("home");
1085        assert_eq!(
1086            state.read_with(cx, |state, _| state.selected_index()),
1087            Some(0)
1088        );
1089    }
1090
1091    #[gpui::test]
1092    fn horizontal_carousel_dispatches_contextual_navigation_keys(cx: &mut gpui::TestAppContext) {
1093        assert_contextual_navigation_keys(cx, Axis::Horizontal);
1094    }
1095
1096    #[gpui::test]
1097    fn vertical_carousel_dispatches_contextual_navigation_keys(cx: &mut gpui::TestAppContext) {
1098        assert_contextual_navigation_keys(cx, Axis::Vertical);
1099    }
1100
1101    struct PropagationHarness {
1102        state: Entity<CarouselState>,
1103        outer_actions: Rc<Cell<usize>>,
1104    }
1105
1106    impl Render for PropagationHarness {
1107        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1108            let down = self.outer_actions.clone();
1109            let left = self.outer_actions.clone();
1110            let right = self.outer_actions.clone();
1111            div()
1112                .tab_group()
1113                .on_action(move |_: &SelectDown, _, _| down.set(down.get() + 1))
1114                .on_action(move |_: &SelectLeft, _, _| left.set(left.get() + 1))
1115                .on_action(move |_: &SelectRight, _, _| right.set(right.get() + 1))
1116                .child(
1117                    Carousel::new("carousel", &self.state)
1118                        .w(px(100.))
1119                        .h(px(100.))
1120                        .child(
1121                            CarouselContent::new(&self.state)
1122                                .h(px(100.))
1123                                .children((0..3).map(|index| {
1124                                    CarouselItem::new(("carousel-item", index), index, &self.state)
1125                                        .child(index.to_string())
1126                                })),
1127                        ),
1128                )
1129        }
1130    }
1131
1132    #[gpui::test]
1133    fn unhandled_navigation_keys_reach_ancestors(cx: &mut gpui::TestAppContext) {
1134        cx.update(crate::init);
1135        let state = cx.update(|cx| cx.new(|_| CarouselState::new(3)));
1136        let outer_actions = Rc::new(Cell::new(0));
1137        let (_, cx) = cx.add_window_view({
1138            let state = state.clone();
1139            let outer_actions = outer_actions.clone();
1140            move |_, _| PropagationHarness {
1141                state,
1142                outer_actions,
1143            }
1144        });
1145        cx.update(|window, cx| window.draw(cx).clear(cx));
1146        cx.update(|window, cx| window.focus_next(cx));
1147
1148        cx.simulate_keystrokes("down");
1149        assert_eq!(outer_actions.get(), 1);
1150
1151        cx.simulate_keystrokes("left");
1152        assert_eq!(outer_actions.get(), 2);
1153        assert_eq!(
1154            state.read_with(cx, |state, _| state.selected_index()),
1155            Some(0)
1156        );
1157
1158        cx.simulate_keystrokes("right");
1159        assert_eq!(
1160            state.read_with(cx, |state, _| state.selected_index()),
1161            Some(1)
1162        );
1163        assert_eq!(outer_actions.get(), 2);
1164    }
1165
1166    #[gpui::test]
1167    fn track_grows_by_its_leading_margin_so_items_fill_the_frame(cx: &mut gpui::TestAppContext) {
1168        cx.update(crate::init);
1169        for axis in [Axis::Horizontal, Axis::Vertical] {
1170            let state = cx.update(|cx| cx.new(|_| CarouselState::new(3).with_axis(axis)));
1171            let (_, cx) = cx.add_window_view({
1172                let state = state.clone();
1173                move |_, _| KeyboardHarness { state }
1174            });
1175            cx.update(|window, cx| window.draw(cx).clear(cx));
1176
1177            let (track, first_item, frame_size) = state.read_with(cx, |state, _| {
1178                let handle = state.scroll_handle();
1179                (
1180                    handle.bounds(),
1181                    handle.bounds_for_item(0).unwrap(),
1182                    state.frame_size().unwrap(),
1183                )
1184            });
1185            assert_eq!(frame_size, gpui::size(px(100.), px(100.)), "{axis:?}");
1186            let expected = if axis.is_horizontal() {
1187                Bounds::new(point(px(-16.), px(0.)), gpui::size(px(116.), px(100.)))
1188            } else {
1189                Bounds::new(point(px(0.), px(-16.)), gpui::size(px(100.), px(116.)))
1190            };
1191            assert_eq!(track, expected, "{axis:?}");
1192            assert_eq!(first_item, expected, "{axis:?}");
1193        }
1194    }
1195
1196    #[gpui::test]
1197    fn clicking_a_slide_focuses_the_carousel_for_keyboard_navigation(
1198        cx: &mut gpui::TestAppContext,
1199    ) {
1200        cx.update(crate::init);
1201        let state = cx.update(|cx| cx.new(|_| CarouselState::new(3)));
1202        let (_, cx) = cx.add_window_view({
1203            let state = state.clone();
1204            move |_, _| KeyboardHarness { state }
1205        });
1206        cx.update(|window, cx| window.draw(cx).clear(cx));
1207        assert!(cx.update(|window, cx| window.focused(cx).is_none()));
1208
1209        cx.simulate_click(point(px(50.), px(50.)), gpui::Modifiers::default());
1210        assert!(cx.update(|window, cx| window.focused(cx).is_some()));
1211
1212        cx.simulate_keystrokes("right");
1213        assert_eq!(
1214            state.read_with(cx, |state, _| state.selected_index()),
1215            Some(1)
1216        );
1217    }
1218
1219    struct ControlsHarness {
1220        state: Entity<CarouselState>,
1221    }
1222
1223    impl Render for ControlsHarness {
1224        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1225            div().tab_group().child(
1226                Carousel::new("carousel", &self.state)
1227                    .w(px(100.))
1228                    .h(px(100.))
1229                    .child(
1230                        CarouselContent::new(&self.state)
1231                            .h(px(100.))
1232                            .children((0..3).map(|index| {
1233                                CarouselItem::new(("carousel-item", index), index, &self.state)
1234                                    .child(index.to_string())
1235                            })),
1236                    )
1237                    .child(CarouselPrevious::new(&self.state))
1238                    .child(CarouselNext::new(&self.state)),
1239            )
1240        }
1241    }
1242
1243    #[gpui::test]
1244    fn clicking_a_control_focuses_the_carousel_for_keyboard_navigation(
1245        cx: &mut gpui::TestAppContext,
1246    ) {
1247        cx.update(crate::init);
1248        let state = cx.update(|cx| cx.new(|_| CarouselState::new(3)));
1249        let (_, cx) = cx.add_window_view({
1250            let state = state.clone();
1251            move |_, _| ControlsHarness { state }
1252        });
1253        cx.update(|window, cx| window.draw(cx).clear(cx));
1254        let selected =
1255            |cx: &mut VisualTestContext| state.read_with(cx, |state, _| state.selected_index());
1256        let root_focused = |cx: &mut VisualTestContext| {
1257            cx.update(|window, cx| state.read(cx).focus_handle(cx).is_focused(window))
1258        };
1259
1260        // A pointer click on Next moves focus to the carousel.
1261        cx.simulate_click(point(px(134.), px(50.)), gpui::Modifiers::default());
1262        assert_eq!(selected(cx), Some(1));
1263        assert!(root_focused(cx));
1264        cx.simulate_keystrokes("right");
1265        assert_eq!(selected(cx), Some(2));
1266
1267        // Keyboard activation of a control leaves focus on the control.
1268        cx.simulate_keystrokes("left");
1269        cx.update(|window, cx| window.focus_next(cx));
1270        cx.update(|window, cx| window.focus_next(cx));
1271        cx.update(|window, cx| window.draw(cx).clear(cx));
1272        let keystroke = gpui::Keystroke::parse("enter").unwrap();
1273        cx.simulate_event(gpui::KeyDownEvent {
1274            keystroke: keystroke.clone(),
1275            is_held: false,
1276            prefer_character_input: false,
1277        });
1278        cx.simulate_event(gpui::KeyUpEvent { keystroke });
1279        assert_eq!(selected(cx), Some(2));
1280        assert!(!root_focused(cx));
1281        assert!(cx.update(|window, cx| window.focused(cx).is_some()));
1282    }
1283
1284    #[gpui::test]
1285    fn carousel_controls_accept_accessibility_labels_and_children(cx: &mut gpui::TestAppContext) {
1286        let state = cx.update(|cx| cx.new(|_| CarouselState::new(2)));
1287        let previous = CarouselPrevious::new(&state)
1288            .accessibility_label("Previous project")
1289            .child("Back");
1290        let next = CarouselNext::new(&state)
1291            .accessibility_label("Next project")
1292            .child("Forward");
1293
1294        assert_eq!(
1295            previous.accessibility_label.as_deref(),
1296            Some("Previous project")
1297        );
1298        assert_eq!(next.accessibility_label.as_deref(), Some("Next project"));
1299        assert_eq!(previous.children.len(), 1);
1300        assert_eq!(next.children.len(), 1);
1301    }
1302}