Skip to main content

fc_ui/capabilities/controls/
carousel.rs

1use crate::capabilities::foundation::theme::use_theme;
2use gpui::{prelude::FluentBuilder as _, Animation, AnimationExt, *};
3use std::rc::Rc;
4use std::time::Duration;
5
6#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
7pub enum CarouselTransition {
8    #[default]
9    Slide,
10    Fade,
11}
12
13#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
14pub enum CarouselSize {
15    Sm,
16    #[default]
17    Md,
18    Lg,
19}
20
21impl CarouselSize {
22    fn arrow_size(&self) -> Pixels {
23        match self {
24            CarouselSize::Sm => px(28.0),
25            CarouselSize::Md => px(36.0),
26            CarouselSize::Lg => px(44.0),
27        }
28    }
29
30    fn dot_size(&self) -> Pixels {
31        match self {
32            CarouselSize::Sm => px(6.0),
33            CarouselSize::Md => px(8.0),
34            CarouselSize::Lg => px(10.0),
35        }
36    }
37
38    fn icon_size(&self) -> Pixels {
39        match self {
40            CarouselSize::Sm => px(14.0),
41            CarouselSize::Md => px(18.0),
42            CarouselSize::Lg => px(22.0),
43        }
44    }
45}
46
47fn emit_if_index_changed(
48    before: usize,
49    state: &CarouselState,
50    on_change: &Option<Rc<dyn Fn(usize, &mut Window, &mut App)>>,
51    window: &mut Window,
52    cx: &mut Context<CarouselState>,
53) {
54    if state.current_index != before {
55        if let Some(handler) = on_change {
56            handler(state.current_index, window, cx);
57        }
58    }
59}
60
61pub struct CarouselState {
62    current_index: usize,
63    previous_index: Option<usize>,
64    slide_count: usize,
65    focus_handle: FocusHandle,
66    transition_id: usize,
67    auto_play_running: bool,
68    auto_play_generation: usize,
69}
70
71impl CarouselState {
72    pub fn new(cx: &mut Context<Self>) -> Self {
73        Self {
74            current_index: 0,
75            previous_index: None,
76            slide_count: 0,
77            focus_handle: cx.focus_handle(),
78            transition_id: 0,
79            auto_play_running: false,
80            auto_play_generation: 0,
81        }
82    }
83
84    pub fn previous_index(&self) -> Option<usize> {
85        self.previous_index
86    }
87
88    pub fn transition_id(&self) -> usize {
89        self.transition_id
90    }
91
92    pub fn current_index(&self) -> usize {
93        self.current_index
94    }
95
96    pub fn slide_count(&self) -> usize {
97        self.slide_count
98    }
99
100    pub fn set_slide_count(&mut self, count: usize, cx: &mut Context<Self>) {
101        self.slide_count = count;
102        if self.current_index >= count && count > 0 {
103            self.current_index = count - 1;
104        }
105        cx.notify();
106    }
107
108    pub fn go_to(&mut self, index: usize, infinite: bool, cx: &mut Context<Self>) {
109        if self.slide_count == 0 {
110            return;
111        }
112
113        let new_index = if infinite {
114            index % self.slide_count
115        } else {
116            index.min(self.slide_count.saturating_sub(1))
117        };
118
119        if new_index != self.current_index {
120            self.previous_index = Some(self.current_index);
121            self.current_index = new_index;
122            self.transition_id = self.transition_id.wrapping_add(1);
123            cx.notify();
124        }
125    }
126
127    pub fn next(&mut self, infinite: bool, cx: &mut Context<Self>) {
128        if self.slide_count == 0 {
129            return;
130        }
131
132        let next_index = if infinite {
133            (self.current_index + 1) % self.slide_count
134        } else if self.current_index < self.slide_count - 1 {
135            self.current_index + 1
136        } else {
137            return;
138        };
139
140        self.previous_index = Some(self.current_index);
141        self.current_index = next_index;
142        self.transition_id = self.transition_id.wrapping_add(1);
143        cx.notify();
144    }
145
146    pub fn prev(&mut self, infinite: bool, cx: &mut Context<Self>) {
147        if self.slide_count == 0 {
148            return;
149        }
150
151        let prev_index = if infinite {
152            if self.current_index == 0 {
153                self.slide_count - 1
154            } else {
155                self.current_index - 1
156            }
157        } else if self.current_index > 0 {
158            self.current_index - 1
159        } else {
160            return;
161        };
162
163        self.previous_index = Some(self.current_index);
164        self.current_index = prev_index;
165        self.transition_id = self.transition_id.wrapping_add(1);
166        cx.notify();
167    }
168
169    fn can_go_prev(&self, infinite: bool) -> bool {
170        if self.slide_count == 0 {
171            return false;
172        }
173        infinite || self.current_index > 0
174    }
175
176    fn can_go_next(&self, infinite: bool) -> bool {
177        if self.slide_count == 0 {
178            return false;
179        }
180        infinite || self.current_index < self.slide_count - 1
181    }
182}
183
184impl Focusable for CarouselState {
185    fn focus_handle(&self, _: &App) -> FocusHandle {
186        self.focus_handle.clone()
187    }
188}
189
190impl Render for CarouselState {
191    fn render(&mut self, _: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
192        div()
193    }
194}
195
196pub struct CarouselSlide {
197    content: AnyElement,
198}
199
200impl CarouselSlide {
201    pub fn new(content: impl IntoElement) -> Self {
202        Self {
203            content: content.into_any_element(),
204        }
205    }
206}
207
208pub use gpui::{bounce, ease_in_out, ease_out_quint, linear, pulsating_between, quadratic};
209
210#[derive(IntoElement)]
211pub struct Carousel {
212    id: ElementId,
213    state: Entity<CarouselState>,
214    slides: Vec<CarouselSlide>,
215    size: CarouselSize,
216    transition: CarouselTransition,
217    transition_duration: Duration,
218    easing: Rc<dyn Fn(f32) -> f32>,
219    infinite: bool,
220    auto_play: bool,
221    auto_play_interval: Duration,
222    show_arrows: bool,
223    show_dots: bool,
224    disabled: bool,
225    on_change: Option<Rc<dyn Fn(usize, &mut Window, &mut App) + 'static>>,
226    style: StyleRefinement,
227}
228
229impl Carousel {
230    pub fn new(id: impl Into<ElementId>, state: Entity<CarouselState>) -> Self {
231        Self {
232            id: id.into(),
233            state,
234            slides: Vec::new(),
235            size: CarouselSize::Md,
236            transition: CarouselTransition::Slide,
237            transition_duration: Duration::from_millis(300),
238            easing: Rc::new(ease_in_out),
239            infinite: false,
240            auto_play: false,
241            auto_play_interval: Duration::from_secs(5),
242            show_arrows: true,
243            show_dots: true,
244            disabled: false,
245            on_change: None,
246            style: StyleRefinement::default(),
247        }
248    }
249
250    pub fn transition_duration(mut self, duration: Duration) -> Self {
251        self.transition_duration = duration;
252        self
253    }
254
255    pub fn easing(mut self, easing: impl Fn(f32) -> f32 + 'static) -> Self {
256        self.easing = Rc::new(easing);
257        self
258    }
259
260    pub fn slides(mut self, slides: Vec<CarouselSlide>) -> Self {
261        self.slides = slides;
262        self
263    }
264
265    pub fn slide(mut self, slide: CarouselSlide) -> Self {
266        self.slides.push(slide);
267        self
268    }
269
270    pub fn size(mut self, size: CarouselSize) -> Self {
271        self.size = size;
272        self
273    }
274
275    pub fn transition(mut self, transition: CarouselTransition) -> Self {
276        self.transition = transition;
277        self
278    }
279
280    pub fn infinite(mut self, infinite: bool) -> Self {
281        self.infinite = infinite;
282        self
283    }
284
285    pub fn auto_play(mut self, auto_play: bool) -> Self {
286        self.auto_play = auto_play;
287        self
288    }
289
290    pub fn auto_play_interval(mut self, interval: Duration) -> Self {
291        self.auto_play_interval = interval;
292        self
293    }
294
295    pub fn show_arrows(mut self, show: bool) -> Self {
296        self.show_arrows = show;
297        self
298    }
299
300    pub fn show_dots(mut self, show: bool) -> Self {
301        self.show_dots = show;
302        self
303    }
304
305    pub fn disabled(mut self, disabled: bool) -> Self {
306        self.disabled = disabled;
307        self
308    }
309
310    pub fn on_change(mut self, handler: impl Fn(usize, &mut Window, &mut App) + 'static) -> Self {
311        self.on_change = Some(Rc::new(handler));
312        self
313    }
314}
315
316impl Styled for Carousel {
317    fn style(&mut self) -> &mut StyleRefinement {
318        &mut self.style
319    }
320}
321
322impl RenderOnce for Carousel {
323    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
324        let theme = use_theme(cx);
325        let state = self.state.clone();
326        let slide_count = self.slides.len();
327
328        state.update(cx, |s, cx| {
329            if s.slide_count != slide_count {
330                s.set_slide_count(slide_count, cx);
331            }
332        });
333
334        let current_index = state.read(cx).current_index();
335        let previous_index = state.read(cx).previous_index();
336        let transition_id = state.read(cx).transition_id();
337        let focus_handle = state.read(cx).focus_handle(cx);
338        let is_focused = focus_handle.is_focused(window);
339
340        let can_prev = state.read(cx).can_go_prev(self.infinite);
341        let can_next = state.read(cx).can_go_next(self.infinite);
342
343        let arrow_size = self.size.arrow_size();
344        let dot_size = self.size.dot_size();
345        let icon_size = self.size.icon_size();
346        let user_style = self.style.clone();
347
348        let want_auto_play = self.auto_play && !self.disabled && slide_count > 1;
349        if want_auto_play && !state.read(cx).auto_play_running {
350            let infinite = self.infinite;
351            let interval = self.auto_play_interval;
352            let generation = state.update(cx, |s, _| {
353                s.auto_play_running = true;
354                s.auto_play_generation = s.auto_play_generation.wrapping_add(1);
355                s.auto_play_generation
356            });
357
358            let state_loop = self.state.clone();
359            cx.spawn(async move |cx| loop {
360                cx.background_executor().timer(interval).await;
361                let keep_running = state_loop
362                    .update(cx, |s, cx| {
363                        if s.auto_play_running && s.auto_play_generation == generation {
364                            s.next(infinite, cx);
365                            true
366                        } else {
367                            s.auto_play_running = false;
368                            false
369                        }
370                    })
371                    .unwrap_or(false);
372                if !keep_running {
373                    break;
374                }
375            })
376            .detach();
377        } else if !want_auto_play && state.read(cx).auto_play_running {
378            state.update(cx, |s, _| {
379                s.auto_play_running = false;
380                s.auto_play_generation = s.auto_play_generation.wrapping_add(1);
381            });
382        }
383
384        div()
385            .id(self.id.clone())
386            .relative()
387            .w_full()
388            .overflow_hidden()
389            .when(!self.disabled, |this| {
390                this.track_focus(&focus_handle.clone().tab_index(0).tab_stop(true))
391            })
392            .when(is_focused && !self.disabled, |this| {
393                this.shadow(smallvec::smallvec![theme.tokens.focus_ring_light()])
394            })
395            .rounded(theme.tokens.radius_lg)
396            .bg(theme.tokens.background)
397            .map(|this| {
398                let mut div = this;
399                div.style().refine(&user_style);
400                div
401            })
402            .when(!self.disabled, |this| {
403                let state_key = self.state.clone();
404                let infinite = self.infinite;
405                let on_change_key = self.on_change.clone();
406
407                this.on_key_down(window.listener_for(
408                    &state_key,
409                    move |state, event: &KeyDownEvent, window, cx| {
410                        match event.keystroke.key.as_str() {
411                            "left" | "ArrowLeft" => {
412                                let before = state.current_index;
413                                state.prev(infinite, cx);
414                                emit_if_index_changed(before, state, &on_change_key, window, cx);
415                                cx.stop_propagation();
416                            }
417                            "right" | "ArrowRight" => {
418                                let before = state.current_index;
419                                state.next(infinite, cx);
420                                emit_if_index_changed(before, state, &on_change_key, window, cx);
421                                cx.stop_propagation();
422                            }
423                            "home" | "Home" => {
424                                let before = state.current_index;
425                                state.go_to(0, infinite, cx);
426                                emit_if_index_changed(before, state, &on_change_key, window, cx);
427                                cx.stop_propagation();
428                            }
429                            "end" | "End" => {
430                                let before = state.current_index;
431                                let last = state.slide_count.saturating_sub(1);
432                                state.go_to(last, infinite, cx);
433                                emit_if_index_changed(before, state, &on_change_key, window, cx);
434                                cx.stop_propagation();
435                            }
436                            _ => {}
437                        }
438                    },
439                ))
440            })
441            .child(
442                div()
443                    .relative()
444                    .w_full()
445                    .overflow_hidden()
446                    .child(match self.transition {
447                        CarouselTransition::Slide => {
448                            let track_width_pct = slide_count as f32 * 100.0;
449                            let slide_width_pct = if slide_count > 0 {
450                                100.0 / slide_count as f32
451                            } else {
452                                100.0
453                            };
454                            let offset = -(current_index as f32);
455
456                            div()
457                                .flex()
458                                .w(relative(track_width_pct / 100.0))
459                                .left(relative(offset))
460                                .children(self.slides.into_iter().map(move |slide| {
461                                    div()
462                                        .flex_shrink_0()
463                                        .w(relative(slide_width_pct / 100.0))
464                                        .child(slide.content)
465                                }))
466                        }
467                        CarouselTransition::Fade => {
468                            let tid = transition_id as u64;
469                            let duration = self.transition_duration;
470                            let easing = self.easing.clone();
471                            let easing2 = self.easing.clone();
472
473                            div().relative().w_full().children(
474                                self.slides
475                                    .into_iter()
476                                    .enumerate()
477                                    .map(move |(idx, slide)| {
478                                        let is_current = idx == current_index;
479                                        let is_previous = previous_index == Some(idx);
480                                        let easing_fn = easing.clone();
481                                        let easing_fn2 = easing2.clone();
482
483                                        if is_current {
484                                            div()
485                                                .relative()
486                                                .w_full()
487                                                .child(slide.content)
488                                                .with_animation(
489                                                    ElementId::NamedInteger("fade-in".into(), tid),
490                                                    Animation::new(duration)
491                                                        .with_easing(move |t| easing_fn(t)),
492                                                    |el, delta| el.opacity(delta),
493                                                )
494                                                .into_any_element()
495                                        } else if is_previous {
496                                            div()
497                                                .absolute()
498                                                .top_0()
499                                                .left_0()
500                                                .w_full()
501                                                .child(slide.content)
502                                                .with_animation(
503                                                    ElementId::NamedInteger("fade-out".into(), tid),
504                                                    Animation::new(duration)
505                                                        .with_easing(move |t| easing_fn2(t)),
506                                                    |el, delta| el.opacity(1.0 - delta),
507                                                )
508                                                .into_any_element()
509                                        } else {
510                                            div()
511                                                .absolute()
512                                                .top_0()
513                                                .left_0()
514                                                .w_full()
515                                                .opacity(0.0)
516                                                .child(slide.content)
517                                                .into_any_element()
518                                        }
519                                    }),
520                            )
521                        }
522                    }),
523            )
524            .when(self.show_arrows && slide_count > 1, |this| {
525                let state_prev = self.state.clone();
526                let state_next = self.state.clone();
527                let infinite = self.infinite;
528                let on_change_prev = self.on_change.clone();
529                let on_change_next = self.on_change.clone();
530                let disabled = self.disabled;
531
532                this.child(
533                    div()
534                        .id("carousel-prev-btn")
535                        .absolute()
536                        .left(px(12.0))
537                        .top_1_2()
538                        .mt(-(arrow_size / 2.0))
539                        .size(arrow_size)
540                        .flex()
541                        .items_center()
542                        .justify_center()
543                        .rounded_full()
544                        .bg(theme.tokens.background.opacity(0.8))
545                        .border_1()
546                        .border_color(theme.tokens.border)
547                        .when(can_prev && !disabled, |this| {
548                            this.cursor(CursorStyle::PointingHand)
549                                .hover(|style| style.bg(theme.tokens.accent))
550                                .on_mouse_down(MouseButton::Left, |_, window, _| {
551                                    window.prevent_default();
552                                })
553                                .on_click(window.listener_for(
554                                    &state_prev,
555                                    move |state, _, window, cx| {
556                                        let before = state.current_index;
557                                        state.prev(infinite, cx);
558                                        emit_if_index_changed(
559                                            before,
560                                            state,
561                                            &on_change_prev,
562                                            window,
563                                            cx,
564                                        );
565                                    },
566                                ))
567                        })
568                        .when(!can_prev || disabled, |this| {
569                            this.opacity(0.5).cursor(CursorStyle::Arrow)
570                        })
571                        .child(
572                            svg()
573                                .path("assets/icons/chevron-left.svg")
574                                .size(icon_size)
575                                .text_color(if can_prev && !disabled {
576                                    theme.tokens.foreground
577                                } else {
578                                    theme.tokens.muted_foreground
579                                }),
580                        ),
581                )
582                .child(
583                    div()
584                        .id("carousel-next-btn")
585                        .absolute()
586                        .right(px(12.0))
587                        .top_1_2()
588                        .mt(-(arrow_size / 2.0))
589                        .size(arrow_size)
590                        .flex()
591                        .items_center()
592                        .justify_center()
593                        .rounded_full()
594                        .bg(theme.tokens.background.opacity(0.8))
595                        .border_1()
596                        .border_color(theme.tokens.border)
597                        .when(can_next && !disabled, |this| {
598                            this.cursor(CursorStyle::PointingHand)
599                                .hover(|style| style.bg(theme.tokens.accent))
600                                .on_mouse_down(MouseButton::Left, |_, window, _| {
601                                    window.prevent_default();
602                                })
603                                .on_click(window.listener_for(
604                                    &state_next,
605                                    move |state, _, window, cx| {
606                                        let before = state.current_index;
607                                        state.next(infinite, cx);
608                                        emit_if_index_changed(
609                                            before,
610                                            state,
611                                            &on_change_next,
612                                            window,
613                                            cx,
614                                        );
615                                    },
616                                ))
617                        })
618                        .when(!can_next || disabled, |this| {
619                            this.opacity(0.5).cursor(CursorStyle::Arrow)
620                        })
621                        .child(
622                            svg()
623                                .path("assets/icons/chevron-right.svg")
624                                .size(icon_size)
625                                .text_color(if can_next && !disabled {
626                                    theme.tokens.foreground
627                                } else {
628                                    theme.tokens.muted_foreground
629                                }),
630                        ),
631                )
632            })
633            .when(self.show_dots && slide_count > 1, |this| {
634                let state_dots = self.state.clone();
635                let infinite = self.infinite;
636                let on_change_dots = self.on_change.clone();
637                let disabled = self.disabled;
638
639                this.child(
640                    div()
641                        .absolute()
642                        .bottom(px(12.0))
643                        .left_0()
644                        .right_0()
645                        .flex()
646                        .justify_center()
647                        .gap(px(6.0))
648                        .children((0..slide_count).map(|idx| {
649                            let is_active = idx == current_index;
650                            let state_dot = state_dots.clone();
651                            let on_change_dot = on_change_dots.clone();
652
653                            div()
654                                .id(("carousel-dot", idx))
655                                .h(dot_size)
656                                .w(if is_active { dot_size * 2.0 } else { dot_size })
657                                .rounded_full()
658                                .bg(if is_active {
659                                    theme.tokens.primary
660                                } else {
661                                    theme.tokens.muted
662                                })
663                                .when(!disabled, |this| {
664                                    this.cursor(CursorStyle::PointingHand)
665                                        .hover(|style| style.opacity(0.8))
666                                        .on_mouse_down(MouseButton::Left, |_, window, _| {
667                                            window.prevent_default();
668                                        })
669                                        .on_click(window.listener_for(
670                                            &state_dot,
671                                            move |state, _, window, cx| {
672                                                let before = state.current_index;
673                                                state.go_to(idx, infinite, cx);
674                                                emit_if_index_changed(
675                                                    before,
676                                                    state,
677                                                    &on_change_dot,
678                                                    window,
679                                                    cx,
680                                                );
681                                            },
682                                        ))
683                                })
684                        })),
685                )
686            })
687    }
688}