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
320#[cfg(not(feature = "gpui-fast"))]
321impl IntoElement for CarouselLoopItem {
322    type Element = Self;
323
324    fn into_element(self) -> Self::Element {
325        self
326    }
327}
328
329impl Element for CarouselLoopItem {
330    type RequestLayoutState = ();
331    type PrepaintState = Point<Pixels>;
332
333    fn id(&self) -> Option<ElementId> {
334        None
335    }
336
337    fn source_location(&self) -> Option<&'static Location<'static>> {
338        None
339    }
340
341    fn request_layout(
342        &mut self,
343        _: Option<&GlobalElementId>,
344        _: Option<&InspectorElementId>,
345        window: &mut Window,
346        cx: &mut App,
347    ) -> (LayoutId, Self::RequestLayoutState) {
348        (self.child.request_layout(window, cx), ())
349    }
350
351    fn prepaint(
352        &mut self,
353        _: Option<&GlobalElementId>,
354        _: Option<&InspectorElementId>,
355        _: Bounds<Pixels>,
356        _: &mut Self::RequestLayoutState,
357        window: &mut Window,
358        cx: &mut App,
359    ) -> Self::PrepaintState {
360        let offset = self.state.read(cx).loop_item_offset(self.index);
361        window.with_element_offset(offset, |window| {
362            self.child.prepaint(window, cx);
363        });
364        offset
365    }
366
367    fn paint(
368        &mut self,
369        _: Option<&GlobalElementId>,
370        _: Option<&InspectorElementId>,
371        _: Bounds<Pixels>,
372        _: &mut Self::RequestLayoutState,
373        _: &mut Self::PrepaintState,
374        window: &mut Window,
375        cx: &mut App,
376    ) {
377        self.child.paint(window, cx);
378    }
379}
380
381impl RenderOnce for CarouselContent {
382    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
383        let entity_id = self.state.entity_id();
384        let snapshot = self.state.read(cx);
385        let axis = snapshot.axis();
386        let selected_ix = snapshot.selected_index();
387        let item_count = snapshot.item_count();
388        let handle = snapshot.scroll_handle().clone();
389        let interacting = snapshot.is_interacting();
390        let motion_revision = snapshot.motion_revision();
391        let loop_runway = snapshot.loop_runway();
392        let loop_layout_transitioning = snapshot.is_loop_layout_transitioning();
393        let state_snap_target = selected_ix.and_then(|ix| snapshot.motion_target_for(ix));
394
395        let geometry = window.use_keyed_state(
396            ElementId::NamedChild(
397                Arc::new(("carousel-geometry", entity_id).into()),
398                "content".into(),
399            ),
400            cx,
401            |_, _| CarouselGeometry::default(),
402        );
403        let geometry_revision = geometry.read(cx).revision;
404
405        let current = axis_value(handle.offset(), axis);
406        let target = if loop_layout_transitioning {
407            current
408        } else {
409            state_snap_target
410                .map(|target| axis_value(target, axis))
411                .or_else(|| {
412                    selected_ix.and_then(|ix| {
413                        snap_offset(&handle, axis, ix + usize::from(loop_runway.is_some()))
414                    })
415                })
416                .unwrap_or(current)
417        };
418        let target = if interacting { current } else { target };
419        let snap_spring = cx.theme().motion_tokens().spring_move.with_epsilon(0.5);
420        let animated = spring(
421            (
422                ("carousel-content", entity_id),
423                SharedString::from(format!("offset-{motion_revision}-{geometry_revision}")),
424            ),
425            target.as_f32(),
426            snap_spring.with_travel(!interacting),
427            window,
428            cx,
429        );
430        let mut offset = handle.offset();
431        set_axis_value(&mut offset, axis, px(animated));
432        set_axis_value(
433            &mut offset,
434            if axis.is_horizontal() {
435                Axis::Vertical
436            } else {
437                Axis::Horizontal
438            },
439            Pixels::ZERO,
440        );
441        handle.set_offset(offset);
442        if !interacting {
443            let rendered = offset;
444            if let Some(rebased) = self
445                .state
446                .update(cx, |state, cx| state.settle_loop_motion(rendered, cx))
447            {
448                offset = rebased;
449                handle.set_offset(offset);
450            }
451        }
452
453        let geometry_state = self.state.clone();
454        let viewport_id: ElementId = ("carousel-content", entity_id).into();
455
456        let rendered_item_count = self.children.len();
457        let loop_state = self.state.clone();
458        let children = self
459            .children
460            .into_iter()
461            .enumerate()
462            .map(move |(index, child)| CarouselLoopItem {
463                child,
464                index,
465                state: loop_state.clone(),
466            });
467        let runway_spacer = |runway: Pixels| {
468            div()
469                .flex_none()
470                .when(axis.is_horizontal(), |this| this.w(runway))
471                .when(axis.is_vertical(), |this| this.h(runway))
472        };
473        let has_runway = loop_runway.is_some();
474
475        div()
476            .relative()
477            .w_full()
478            .flex()
479            .when(axis.is_horizontal(), |this| this.flex_row())
480            .when(axis.is_vertical(), |this| this.flex_col())
481            .refine_style(&self.style)
482            .overflow_hidden()
483            .child(
484                // As a flex child the track grows by its negative leading
485                // margin, so the padded items fill the frame on both edges.
486                div()
487                    .id(viewport_id.clone())
488                    .flex_1()
489                    .flex()
490                    .when(axis.is_horizontal(), |this| {
491                        this.flex_row().min_w_0().ml_neg_4()
492                    })
493                    .when(axis.is_vertical(), |this| {
494                        this.flex_col().min_h_0().mt_neg_4()
495                    })
496                    .track_scroll(&handle)
497                    .when_some(loop_runway, |this, runway| {
498                        this.child(runway_spacer(runway))
499                    })
500                    .children(children)
501                    .when_some(loop_runway, |this, runway| {
502                        this.child(runway_spacer(runway))
503                    })
504                    .refine_style(&self.track_style),
505            )
506            .child(CarouselScrollMask::new(axis, &self.state).id(viewport_id))
507            .on_prepaint(move |frame, _, cx| {
508                let next = CarouselGeometry::read(
509                    geometry_state.read(cx),
510                    frame,
511                    has_runway,
512                    rendered_item_count,
513                );
514                if !geometry.read(cx).same_layout(&next) {
515                    geometry_state.update(cx, |state, _| {
516                        state.set_geometry_with_runway(
517                            next.viewport,
518                            next.frame,
519                            next.items.clone(),
520                            next.has_runway,
521                        );
522                    });
523                    geometry.update(cx, |current, cx| {
524                        current.viewport = next.viewport;
525                        current.frame = next.frame;
526                        current.items = next.items;
527                        current.has_runway = next.has_runway;
528                        current.revision = current.revision.wrapping_add(1);
529                        cx.notify();
530                    });
531                }
532            })
533            .when(item_count == 0, |this| this.invisible())
534    }
535}
536
537/// One logical slide in a [`CarouselContent`].
538#[derive(IntoElement)]
539pub struct CarouselItem {
540    id: ElementId,
541    index: usize,
542    state: Entity<CarouselState>,
543    style: StyleRefinement,
544    accessibility_label: Option<SharedString>,
545    children: Vec<AnyElement>,
546}
547
548impl CarouselItem {
549    /// Creates the item at the zero-based `index` used by `state`.
550    pub fn new(id: impl Into<ElementId>, index: usize, state: &Entity<CarouselState>) -> Self {
551        Self {
552            id: id.into(),
553            index,
554            state: state.clone(),
555            style: StyleRefinement::default(),
556            accessibility_label: None,
557            children: Vec::new(),
558        }
559    }
560
561    /// Replaces the generated "Slide N of M" accessibility label.
562    pub fn accessibility_label(mut self, label: impl Into<SharedString>) -> Self {
563        self.accessibility_label = Some(label.into());
564        self
565    }
566}
567
568impl ParentElement for CarouselItem {
569    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
570        self.children.extend(elements);
571    }
572}
573
574impl Styled for CarouselItem {
575    fn style(&mut self) -> &mut StyleRefinement {
576        &mut self.style
577    }
578}
579
580impl RenderOnce for CarouselItem {
581    fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
582        let state = self.state.read(cx);
583        let axis = state.axis();
584        let count = state.item_count();
585        let label = self.accessibility_label.unwrap_or_else(|| {
586            t!(
587                "Carousel.slide",
588                current = self.index.saturating_add(1),
589                total = count
590            )
591            .into()
592        });
593
594        div()
595            .id(self.id)
596            .role(Role::Group)
597            .aria_label(label)
598            .aria_position_in_set(self.index.saturating_add(1))
599            .aria_size_of_set(count)
600            .min_w_0()
601            .min_h_0()
602            .flex_none()
603            .when(axis.is_horizontal(), |this| this.w_full().pl_4())
604            .when(axis.is_vertical(), |this| this.h_full().pt_4())
605            .children(self.children)
606            .refine_style(&self.style)
607    }
608}
609
610/// A previous-slide control positioned around the Carousel viewport.
611#[derive(IntoElement)]
612pub struct CarouselPrevious {
613    state: Entity<CarouselState>,
614    size: Size,
615    style: StyleRefinement,
616    accessibility_label: Option<SharedString>,
617    children: Vec<AnyElement>,
618}
619
620impl CarouselPrevious {
621    /// Creates a previous-slide control bound to `state`.
622    pub fn new(state: &Entity<CarouselState>) -> Self {
623        Self {
624            state: state.clone(),
625            size: Size::Medium,
626            style: StyleRefinement::default(),
627            accessibility_label: None,
628            children: Vec::new(),
629        }
630    }
631
632    /// Replaces the generated previous-slide accessibility label and tooltip.
633    pub fn accessibility_label(mut self, label: impl Into<SharedString>) -> Self {
634        self.accessibility_label = Some(label.into());
635        self
636    }
637}
638
639impl crate::Sizable for CarouselPrevious {
640    fn with_size(mut self, size: impl Into<Size>) -> Self {
641        self.size = size.into();
642        self
643    }
644}
645
646impl Styled for CarouselPrevious {
647    fn style(&mut self) -> &mut StyleRefinement {
648        &mut self.style
649    }
650}
651
652impl ParentElement for CarouselPrevious {
653    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
654        self.children.extend(elements);
655    }
656}
657
658impl RenderOnce for CarouselPrevious {
659    fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
660        carousel_control(
661            self.state,
662            self.size,
663            self.style,
664            self.accessibility_label,
665            self.children,
666            false,
667            cx,
668        )
669    }
670}
671
672/// A next-slide control positioned around the Carousel viewport.
673#[derive(IntoElement)]
674pub struct CarouselNext {
675    state: Entity<CarouselState>,
676    size: Size,
677    style: StyleRefinement,
678    accessibility_label: Option<SharedString>,
679    children: Vec<AnyElement>,
680}
681
682impl CarouselNext {
683    /// Creates a next-slide control bound to `state`.
684    pub fn new(state: &Entity<CarouselState>) -> Self {
685        Self {
686            state: state.clone(),
687            size: Size::Medium,
688            style: StyleRefinement::default(),
689            accessibility_label: None,
690            children: Vec::new(),
691        }
692    }
693
694    /// Replaces the generated next-slide accessibility label and tooltip.
695    pub fn accessibility_label(mut self, label: impl Into<SharedString>) -> Self {
696        self.accessibility_label = Some(label.into());
697        self
698    }
699}
700
701impl crate::Sizable for CarouselNext {
702    fn with_size(mut self, size: impl Into<Size>) -> Self {
703        self.size = size.into();
704        self
705    }
706}
707
708impl Styled for CarouselNext {
709    fn style(&mut self) -> &mut StyleRefinement {
710        &mut self.style
711    }
712}
713
714impl ParentElement for CarouselNext {
715    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
716        self.children.extend(elements);
717    }
718}
719
720impl RenderOnce for CarouselNext {
721    fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
722        carousel_control(
723            self.state,
724            self.size,
725            self.style,
726            self.accessibility_label,
727            self.children,
728            true,
729            cx,
730        )
731    }
732}
733
734fn carousel_control(
735    state: Entity<CarouselState>,
736    size: Size,
737    style: StyleRefinement,
738    accessibility_label: Option<SharedString>,
739    children: Vec<AnyElement>,
740    next: bool,
741    cx: &mut App,
742) -> impl IntoElement {
743    let snapshot = state.read(cx);
744    let axis = snapshot.axis();
745    let frame_size = snapshot.frame_size();
746    let focus_handle = snapshot.focus_handle(cx);
747    let disabled = if next {
748        !snapshot.has_next()
749    } else {
750        !snapshot.has_previous()
751    };
752    let (name, default_label, icon) = match (axis, next) {
753        (Axis::Horizontal, false) => ("previous", t!("Carousel.previous"), IconName::ChevronLeft),
754        (Axis::Horizontal, true) => ("next", t!("Carousel.next"), IconName::ChevronRight),
755        (Axis::Vertical, false) => ("previous", t!("Carousel.previous"), IconName::ChevronUp),
756        (Axis::Vertical, true) => ("next", t!("Carousel.next"), IconName::ChevronDown),
757    };
758    let label = accessibility_label.unwrap_or_else(|| default_label.into());
759    let has_custom_content = !children.is_empty();
760    let id = ElementId::NamedChild(
761        Arc::new(("carousel-control", state.entity_id()).into()),
762        name.into(),
763    );
764
765    div()
766        .absolute()
767        .top_0()
768        .left_0()
769        .when_some(frame_size, |this, size| this.w(size.width).h(size.height))
770        .when(frame_size.is_none(), |this| this.right_0().bottom_0())
771        .child(
772            Button::new(id)
773                .outline()
774                .with_size(size)
775                .when(!has_custom_content, |this| this.icon(icon))
776                .accessibility_label(label.clone())
777                .tooltip(label)
778                .disabled(disabled)
779                .absolute()
780                .rounded_full_style(cx)
781                .when(axis.is_horizontal() && !next, |this| {
782                    this.right_full().mr_4().top_0().bottom_0().my_auto()
783                })
784                .when(axis.is_horizontal() && next, |this| {
785                    this.left_full().ml_4().top_0().bottom_0().my_auto()
786                })
787                .when(axis.is_vertical() && !next, |this| {
788                    this.bottom_full().mb_4().left_0().right_0().mx_auto()
789                })
790                .when(axis.is_vertical() && next, |this| {
791                    this.top_full().mt_4().left_0().right_0().mx_auto()
792                })
793                .when(!disabled, |this| {
794                    this.on_click(move |event, window, cx| {
795                        state.update(cx, |state, cx| {
796                            if next {
797                                state.select_next(cx);
798                            } else {
799                                state.select_previous(cx);
800                            }
801                        });
802                        focus_after_pointer_click(&state, &focus_handle, event, window, cx);
803                    })
804                })
805                .children(children)
806                .refine_style(&style),
807        )
808}
809
810/// A composable container for Carousel pagination items.
811#[derive(IntoElement)]
812pub struct CarouselPagination {
813    id: ElementId,
814    style: StyleRefinement,
815    accessibility_label: SharedString,
816    children: Vec<AnyElement>,
817}
818
819impl CarouselPagination {
820    /// Creates an empty pagination container.
821    #[track_caller]
822    pub fn new() -> Self {
823        Self {
824            id: ElementId::CodeLocation(*Location::caller()),
825            style: StyleRefinement::default(),
826            accessibility_label: t!("Carousel.pagination").into(),
827            children: Vec::new(),
828        }
829    }
830
831    /// Sets the name announced for the pagination group.
832    pub fn accessibility_label(mut self, label: impl Into<SharedString>) -> Self {
833        self.accessibility_label = label.into();
834        self
835    }
836}
837
838impl ParentElement for CarouselPagination {
839    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
840        self.children.extend(elements);
841    }
842}
843
844impl Styled for CarouselPagination {
845    fn style(&mut self) -> &mut StyleRefinement {
846        &mut self.style
847    }
848}
849
850impl RenderOnce for CarouselPagination {
851    fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
852        div()
853            .id(self.id)
854            .role(Role::Group)
855            .aria_label(self.accessibility_label)
856            .flex()
857            .items_center()
858            .justify_center()
859            .gap_2()
860            .children(self.children)
861            .refine_style(&self.style)
862    }
863}
864
865/// One application-styled pagination control for a Carousel item.
866#[derive(IntoElement)]
867pub struct CarouselPaginationItem {
868    id: ElementId,
869    index: usize,
870    state: Entity<CarouselState>,
871    size: Size,
872    style: StyleRefinement,
873    accessibility_label: Option<SharedString>,
874    children: Vec<AnyElement>,
875}
876
877impl CarouselPaginationItem {
878    /// Creates a pagination item for the zero-based `index`.
879    pub fn new(id: impl Into<ElementId>, index: usize, state: &Entity<CarouselState>) -> Self {
880        Self {
881            id: id.into(),
882            index,
883            state: state.clone(),
884            size: Size::XSmall,
885            style: StyleRefinement::default(),
886            accessibility_label: None,
887            children: Vec::new(),
888        }
889    }
890
891    /// Replaces the generated "Go to slide N" accessibility label.
892    pub fn accessibility_label(mut self, label: impl Into<SharedString>) -> Self {
893        self.accessibility_label = Some(label.into());
894        self
895    }
896}
897
898impl crate::Sizable for CarouselPaginationItem {
899    fn with_size(mut self, size: impl Into<Size>) -> Self {
900        self.size = size.into();
901        self
902    }
903}
904
905impl ParentElement for CarouselPaginationItem {
906    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
907        self.children.extend(elements);
908    }
909}
910
911impl Styled for CarouselPaginationItem {
912    fn style(&mut self) -> &mut StyleRefinement {
913        &mut self.style
914    }
915}
916
917impl RenderOnce for CarouselPaginationItem {
918    fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
919        let selected = self.state.read(cx).selected_index() == Some(self.index);
920        let disabled = self.index >= self.state.read(cx).item_count();
921        let focus_handle = self.state.read(cx).focus_handle(cx);
922        let label = self.accessibility_label.unwrap_or_else(|| {
923            t!(
924                "Carousel.go_to_slide",
925                current = self.index.saturating_add(1)
926            )
927            .into()
928        });
929        let state = self.state;
930        let index = self.index;
931
932        Button::new(self.id)
933            .compact()
934            .with_size(self.size)
935            .selected(selected)
936            .accessibility_label(label)
937            .disabled(disabled)
938            .children(self.children)
939            .when(!disabled, |this| {
940                this.on_click(move |event, window, cx| {
941                    state.update(cx, |state, cx| {
942                        state.select_index(index, cx);
943                    });
944                    focus_after_pointer_click(&state, &focus_handle, event, window, cx);
945                })
946            })
947            .refine_style(&self.style)
948    }
949}
950
951/// Moves keyboard focus to the carousel after a pointer click on one of its
952/// controls, so the arrow keys keep working without drawing the ring. A
953/// keyboard activation leaves focus on the control.
954fn focus_after_pointer_click(
955    state: &Entity<CarouselState>,
956    focus_handle: &FocusHandle,
957    event: &ClickEvent,
958    window: &mut Window,
959    cx: &mut App,
960) {
961    if event.is_keyboard() || focus_handle.contains_focused(window, cx) {
962        return;
963    }
964    state.update(cx, |state, _| state.suppress_focus_ring(true));
965    window.focus(focus_handle, cx);
966}
967
968fn axis_value(point: Point<Pixels>, axis: Axis) -> Pixels {
969    if axis.is_horizontal() {
970        point.x
971    } else {
972        point.y
973    }
974}
975
976fn set_axis_value(point: &mut Point<Pixels>, axis: Axis, value: Pixels) {
977    if axis.is_horizontal() {
978        point.x = value;
979    } else {
980        point.y = value;
981    }
982}
983
984fn snap_offset(handle: &gpui::ScrollHandle, axis: Axis, index: usize) -> Option<Pixels> {
985    let viewport = handle.bounds();
986    let item = handle.bounds_for_item(index)?;
987    let target = if axis.is_horizontal() {
988        viewport.left() - item.left()
989    } else {
990        viewport.top() - item.top()
991    };
992    let max = axis_value(handle.max_offset(), axis).max(Pixels::ZERO);
993    Some(target.clamp(-max, Pixels::ZERO))
994}
995
996#[cfg(test)]
997mod tests {
998    use std::{cell::Cell, rc::Rc};
999
1000    use super::*;
1001    use gpui::{AppContext as _, Context, Render, VisualTestContext, point};
1002    use gpui_base::FocusableExt as _;
1003
1004    #[test]
1005    fn axis_helpers_only_change_the_requested_coordinate() {
1006        let mut value = point(px(3.), px(7.));
1007        set_axis_value(&mut value, Axis::Horizontal, px(11.));
1008        assert_eq!(value, point(px(11.), px(7.)));
1009        set_axis_value(&mut value, Axis::Vertical, px(-5.));
1010        assert_eq!(value, point(px(11.), px(-5.)));
1011    }
1012
1013    #[gpui::test]
1014    fn carousel_controls_accept_semantic_sizes(cx: &mut gpui::TestAppContext) {
1015        let state = cx.update(|cx| cx.new(|_| CarouselState::new(2)));
1016
1017        assert_eq!(CarouselPrevious::new(&state).size, Size::Medium);
1018        assert_eq!(CarouselNext::new(&state).size, Size::Medium);
1019        assert_eq!(CarouselPrevious::new(&state).large().size, Size::Large);
1020        assert_eq!(CarouselNext::new(&state).xsmall().size, Size::XSmall);
1021        assert_eq!(
1022            CarouselPaginationItem::new("pagination", 0, &state)
1023                .small()
1024                .size,
1025            Size::Small
1026        );
1027    }
1028
1029    #[gpui::test]
1030    fn carousel_focus_ring_is_configurable(cx: &mut gpui::TestAppContext) {
1031        let state = cx.update(|cx| cx.new(|_| CarouselState::new(2)));
1032
1033        assert!(Carousel::new("carousel", &state).is_focus_ring_enabled());
1034        assert!(
1035            !Carousel::new("carousel", &state)
1036                .focus_ring(false)
1037                .is_focus_ring_enabled()
1038        );
1039    }
1040
1041    struct KeyboardHarness {
1042        state: Entity<CarouselState>,
1043    }
1044
1045    impl Render for KeyboardHarness {
1046        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1047            div().tab_group().child(
1048                Carousel::new("carousel", &self.state)
1049                    .w(px(100.))
1050                    .h(px(100.))
1051                    .child(
1052                        CarouselContent::new(&self.state)
1053                            .h(px(100.))
1054                            .children((0..3).map(|index| {
1055                                CarouselItem::new(("carousel-item", index), index, &self.state)
1056                                    .child(index.to_string())
1057                            })),
1058                    ),
1059            )
1060        }
1061    }
1062
1063    fn assert_contextual_navigation_keys(cx: &mut gpui::TestAppContext, axis: Axis) {
1064        cx.update(crate::init);
1065        let state = cx.update(|cx| cx.new(|_| CarouselState::new(3).with_axis(axis)));
1066        let (_, cx) = cx.add_window_view({
1067            let state = state.clone();
1068            move |_, _| KeyboardHarness { state }
1069        });
1070        cx.update(|window, cx| window.draw(cx).clear(cx));
1071
1072        cx.update(|window, cx| window.focus_next(cx));
1073        let (primary, secondary) = if axis.is_horizontal() {
1074            ("right", "down")
1075        } else {
1076            ("down", "right")
1077        };
1078        cx.simulate_keystrokes(primary);
1079        assert_eq!(
1080            state.read_with(cx, |state, _| state.selected_index()),
1081            Some(1)
1082        );
1083        cx.simulate_keystrokes(secondary);
1084        assert_eq!(
1085            state.read_with(cx, |state, _| state.selected_index()),
1086            Some(1)
1087        );
1088        cx.simulate_keystrokes("end");
1089        assert_eq!(
1090            state.read_with(cx, |state, _| state.selected_index()),
1091            Some(2)
1092        );
1093        cx.simulate_keystrokes("home");
1094        assert_eq!(
1095            state.read_with(cx, |state, _| state.selected_index()),
1096            Some(0)
1097        );
1098    }
1099
1100    #[gpui::test]
1101    fn horizontal_carousel_dispatches_contextual_navigation_keys(cx: &mut gpui::TestAppContext) {
1102        assert_contextual_navigation_keys(cx, Axis::Horizontal);
1103    }
1104
1105    #[gpui::test]
1106    fn vertical_carousel_dispatches_contextual_navigation_keys(cx: &mut gpui::TestAppContext) {
1107        assert_contextual_navigation_keys(cx, Axis::Vertical);
1108    }
1109
1110    struct PropagationHarness {
1111        state: Entity<CarouselState>,
1112        outer_actions: Rc<Cell<usize>>,
1113    }
1114
1115    impl Render for PropagationHarness {
1116        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1117            let down = self.outer_actions.clone();
1118            let left = self.outer_actions.clone();
1119            let right = self.outer_actions.clone();
1120            div()
1121                .tab_group()
1122                .on_action(move |_: &SelectDown, _, _| down.set(down.get() + 1))
1123                .on_action(move |_: &SelectLeft, _, _| left.set(left.get() + 1))
1124                .on_action(move |_: &SelectRight, _, _| right.set(right.get() + 1))
1125                .child(
1126                    Carousel::new("carousel", &self.state)
1127                        .w(px(100.))
1128                        .h(px(100.))
1129                        .child(
1130                            CarouselContent::new(&self.state)
1131                                .h(px(100.))
1132                                .children((0..3).map(|index| {
1133                                    CarouselItem::new(("carousel-item", index), index, &self.state)
1134                                        .child(index.to_string())
1135                                })),
1136                        ),
1137                )
1138        }
1139    }
1140
1141    #[gpui::test]
1142    fn unhandled_navigation_keys_reach_ancestors(cx: &mut gpui::TestAppContext) {
1143        cx.update(crate::init);
1144        let state = cx.update(|cx| cx.new(|_| CarouselState::new(3)));
1145        let outer_actions = Rc::new(Cell::new(0));
1146        let (_, cx) = cx.add_window_view({
1147            let state = state.clone();
1148            let outer_actions = outer_actions.clone();
1149            move |_, _| PropagationHarness {
1150                state,
1151                outer_actions,
1152            }
1153        });
1154        cx.update(|window, cx| window.draw(cx).clear(cx));
1155        cx.update(|window, cx| window.focus_next(cx));
1156
1157        cx.simulate_keystrokes("down");
1158        assert_eq!(outer_actions.get(), 1);
1159
1160        cx.simulate_keystrokes("left");
1161        assert_eq!(outer_actions.get(), 2);
1162        assert_eq!(
1163            state.read_with(cx, |state, _| state.selected_index()),
1164            Some(0)
1165        );
1166
1167        cx.simulate_keystrokes("right");
1168        assert_eq!(
1169            state.read_with(cx, |state, _| state.selected_index()),
1170            Some(1)
1171        );
1172        assert_eq!(outer_actions.get(), 2);
1173    }
1174
1175    #[gpui::test]
1176    fn track_grows_by_its_leading_margin_so_items_fill_the_frame(cx: &mut gpui::TestAppContext) {
1177        cx.update(crate::init);
1178        for axis in [Axis::Horizontal, Axis::Vertical] {
1179            let state = cx.update(|cx| cx.new(|_| CarouselState::new(3).with_axis(axis)));
1180            let (_, cx) = cx.add_window_view({
1181                let state = state.clone();
1182                move |_, _| KeyboardHarness { state }
1183            });
1184            cx.update(|window, cx| window.draw(cx).clear(cx));
1185
1186            let (track, first_item, frame_size) = state.read_with(cx, |state, _| {
1187                let handle = state.scroll_handle();
1188                (
1189                    handle.bounds(),
1190                    handle.bounds_for_item(0).unwrap(),
1191                    state.frame_size().unwrap(),
1192                )
1193            });
1194            assert_eq!(frame_size, gpui::size(px(100.), px(100.)), "{axis:?}");
1195            let expected = if axis.is_horizontal() {
1196                Bounds::new(point(px(-16.), px(0.)), gpui::size(px(116.), px(100.)))
1197            } else {
1198                Bounds::new(point(px(0.), px(-16.)), gpui::size(px(100.), px(116.)))
1199            };
1200            assert_eq!(track, expected, "{axis:?}");
1201            assert_eq!(first_item, expected, "{axis:?}");
1202        }
1203    }
1204
1205    #[gpui::test]
1206    fn clicking_a_slide_focuses_the_carousel_for_keyboard_navigation(
1207        cx: &mut gpui::TestAppContext,
1208    ) {
1209        cx.update(crate::init);
1210        let state = cx.update(|cx| cx.new(|_| CarouselState::new(3)));
1211        let (_, cx) = cx.add_window_view({
1212            let state = state.clone();
1213            move |_, _| KeyboardHarness { state }
1214        });
1215        cx.update(|window, cx| window.draw(cx).clear(cx));
1216        assert!(cx.update(|window, cx| window.focused(cx).is_none()));
1217
1218        cx.simulate_click(point(px(50.), px(50.)), gpui::Modifiers::default());
1219        assert!(cx.update(|window, cx| window.focused(cx).is_some()));
1220
1221        cx.simulate_keystrokes("right");
1222        assert_eq!(
1223            state.read_with(cx, |state, _| state.selected_index()),
1224            Some(1)
1225        );
1226    }
1227
1228    struct ControlsHarness {
1229        state: Entity<CarouselState>,
1230    }
1231
1232    impl Render for ControlsHarness {
1233        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1234            div().tab_group().child(
1235                Carousel::new("carousel", &self.state)
1236                    .w(px(100.))
1237                    .h(px(100.))
1238                    .child(
1239                        CarouselContent::new(&self.state)
1240                            .h(px(100.))
1241                            .children((0..3).map(|index| {
1242                                CarouselItem::new(("carousel-item", index), index, &self.state)
1243                                    .child(index.to_string())
1244                            })),
1245                    )
1246                    .child(CarouselPrevious::new(&self.state))
1247                    .child(CarouselNext::new(&self.state)),
1248            )
1249        }
1250    }
1251
1252    #[gpui::test]
1253    fn clicking_a_control_focuses_the_carousel_for_keyboard_navigation(
1254        cx: &mut gpui::TestAppContext,
1255    ) {
1256        cx.update(crate::init);
1257        let state = cx.update(|cx| cx.new(|_| CarouselState::new(3)));
1258        let (_, cx) = cx.add_window_view({
1259            let state = state.clone();
1260            move |_, _| ControlsHarness { state }
1261        });
1262        cx.update(|window, cx| window.draw(cx).clear(cx));
1263        let selected =
1264            |cx: &mut VisualTestContext| state.read_with(cx, |state, _| state.selected_index());
1265        let root_focused = |cx: &mut VisualTestContext| {
1266            cx.update(|window, cx| state.read(cx).focus_handle(cx).is_focused(window))
1267        };
1268
1269        // A pointer click on Next moves focus to the carousel.
1270        cx.simulate_click(point(px(134.), px(50.)), gpui::Modifiers::default());
1271        assert_eq!(selected(cx), Some(1));
1272        assert!(root_focused(cx));
1273        cx.simulate_keystrokes("right");
1274        assert_eq!(selected(cx), Some(2));
1275
1276        // Keyboard activation of a control leaves focus on the control.
1277        cx.simulate_keystrokes("left");
1278        cx.update(|window, cx| window.focus_next(cx));
1279        cx.update(|window, cx| window.focus_next(cx));
1280        cx.update(|window, cx| window.draw(cx).clear(cx));
1281        let keystroke = gpui::Keystroke::parse("enter").unwrap();
1282        cx.simulate_event(gpui::KeyDownEvent {
1283            keystroke: keystroke.clone(),
1284            is_held: false,
1285            prefer_character_input: false,
1286        });
1287        cx.simulate_event(gpui::KeyUpEvent { keystroke });
1288        assert_eq!(selected(cx), Some(2));
1289        assert!(!root_focused(cx));
1290        assert!(cx.update(|window, cx| window.focused(cx).is_some()));
1291    }
1292
1293    #[gpui::test]
1294    fn carousel_controls_accept_accessibility_labels_and_children(cx: &mut gpui::TestAppContext) {
1295        let state = cx.update(|cx| cx.new(|_| CarouselState::new(2)));
1296        let previous = CarouselPrevious::new(&state)
1297            .accessibility_label("Previous project")
1298            .child("Back");
1299        let next = CarouselNext::new(&state)
1300            .accessibility_label("Next project")
1301            .child("Forward");
1302
1303        assert_eq!(
1304            previous.accessibility_label.as_deref(),
1305            Some("Previous project")
1306        );
1307        assert_eq!(next.accessibility_label.as_deref(), Some("Next project"));
1308        assert_eq!(previous.children.len(), 1);
1309        assert_eq!(next.children.len(), 1);
1310    }
1311}