A horizontal track of slides with previous/next buttons and optional dot indicators.
use gpui::{div, prelude::*, px, Context, FontWeight, Window};
use crate::theme::ActiveTheme;
use crate::ui::carousel::Carousel;
#[derive(Default)]
pub struct CarouselView {
index: usize,
}
impl Render for CarouselView {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let theme = cx.theme();
Carousel::new("carousel", self.index)
.slide_width(px(240.0))
.dots(true)
.slides((1..=5).map(|number| {
// A small gap between slides, like shadcn's `pl-1` items.
div().px_1().child(
div()
.h(px(232.0))
.flex()
.items_center()
.justify_center()
.rounded(theme.radius)
.border_1()
.border_color(theme.border)
.bg(theme.card)
.text_color(theme.card_foreground)
.text_size(px(36.0))
.font_weight(FontWeight::SEMIBOLD)
.child(number.to_string()),
)
}))
.on_change(cx.listener(|this, index: &usize, _, cx| {
this.index = *index;
cx.notify();
}))
}
}Installation
Copies src/ui/carousel.rs into your project, along with any components it depends on, and registers the module in src/ui/mod.rs.
Install the theme
Every component reads colors from
crate::theme. Follow the installation guide if you have not added it yet.Install the icons
This component draws icons from
crate::icons. Copy src/icons.rs into your project and declaremod icons;next tomod theme;.Copy the source
Paste the code below into
src/ui/carousel.rs.src/ui/carousel.rs use std::rc::Rc; use gpui::{ div, prelude::*, px, svg, AnimationExt, AnyElement, App, ElementId, Pixels, SpringAnimation, SpringConfig, Window, }; use crate::theme::ActiveTheme; use crate::icons::{ARROW_LEFT, ARROW_RIGHT}; /// Critically damped (damping = 2 * sqrt(stiffness)), so the track settles in ~300ms without /// overshooting past the first or last slide. const SLIDE_SPRING: SpringConfig = SpringConfig::new(300.0, 34.64, 1.0); const NAV_BUTTON: Pixels = px(32.0); type ChangeHandler = Rc<dyn Fn(&usize, &mut Window, &mut App) + 'static>; /// A horizontal track of slides with previous/next buttons and optional dot indicators. /// The parent view owns `index` and updates it in `on_change`. #[derive(IntoElement)] pub struct Carousel { id: ElementId, index: usize, slides: Vec<AnyElement>, slide_width: Pixels, dots: bool, on_change: Option<ChangeHandler>, } impl Carousel { pub fn new(id: impl Into<ElementId>, index: usize) -> Self { Self { id: id.into(), index, slides: Vec::new(), slide_width: px(240.0), dots: false, on_change: None, } } pub fn slide(mut self, slide: impl IntoElement) -> Self { self.slides.push(slide.into_any_element()); self } pub fn slides(mut self, slides: impl IntoIterator<Item = impl IntoElement>) -> Self { self.slides.extend(slides.into_iter().map(IntoElement::into_any_element)); self } /// The width of the visible area; each slide fills it. pub fn slide_width(mut self, width: impl Into<Pixels>) -> Self { self.slide_width = width.into(); self } /// Shows a dot per slide below the track. Clicking a dot jumps to that slide. pub fn dots(mut self, dots: bool) -> Self { self.dots = dots; self } /// Receives the index of the slide to show next. pub fn on_change(mut self, handler: impl Fn(&usize, &mut Window, &mut App) + 'static) -> Self { self.on_change = Some(Rc::new(handler)); self } } impl RenderOnce for Carousel { fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement { let theme = cx.theme(); let count = self.slides.len(); let index = self.index.min(count.saturating_sub(1)); let width = self.slide_width; let handler = self.on_change; let nav_button = |id: &'static str, icon: &'static [u8], target: Option<usize>| { let enabled = target.is_some(); div() .id(id) .flex() .flex_none() .items_center() .justify_center() .size(NAV_BUTTON) .rounded_full() .border_1() .border_color(theme.input) .bg(theme.background) .shadow_xs() .when(!enabled, |this| this.opacity(0.5).cursor_not_allowed()) .when(enabled, |this| this.cursor_pointer().hover(|style| style.bg(theme.accent))) .when_some(target.zip(handler.clone()), |this, (target, handler)| { this.on_click(move |_, window, cx| handler(&target, window, cx)) }) .child(svg().data(icon).flex_none().size(px(16.0)).text_color(theme.foreground)) }; // The spring keeps its velocity when the index changes mid-slide, and a freshly mounted // spring starts at its target, so the first render doesn't scroll in from slide 0. let track = div() .relative() .flex() .children(self.slides.into_iter().map(|slide| div().flex_none().w(width).child(slide))) .with_spring( "track", SpringAnimation::new(SLIDE_SPRING).to(index as f32), move |this, position| this.left(-width * position), ); let dots = self.dots.then(|| { div().flex().justify_center().gap_2().children((0..count).map(|ix| { let active = ix == index; div() .id(("dot", ix)) .size(px(8.0)) .rounded_full() .bg(if active { theme.primary } else { theme.muted_foreground.opacity(0.3) }) .when(!active, |this| { this.cursor_pointer().hover(|style| style.bg(theme.muted_foreground)) }) .when_some(handler.clone().filter(|_| !active), |this, handler| { this.on_click(move |_, window, cx| handler(&ix, window, cx)) }) })) }); div() .id(self.id) .flex() .flex_col() .gap_4() .child( div() .flex() .items_center() .gap_4() .child(nav_button("previous", ARROW_LEFT, index.checked_sub(1))) .child(div().w(width).overflow_hidden().child(track)) .child(nav_button("next", ARROW_RIGHT, (index + 1 < count).then_some(index + 1))), ) .children(dots) } }Register the module
// src/ui/mod.rs pub mod carousel;
Usage
use crate::ui::carousel::*;API Reference
Carousel
A horizontal track of slides with previous/next buttons and optional dot indicators. The parent view owns index and updates it in on_change.
Carousel::new(id: impl Into<ElementId>, index: usize) -> Self.slide(slide: impl IntoElement).slides(slides: impl IntoIterator<Item = impl IntoElement>).slide_width(width: impl Into<Pixels>)The width of the visible area; each slide fills it.
.dots(dots: bool)Shows a dot per slide below the track. Clicking a dot jumps to that slide.
.on_change(handler: impl Fn(&usize, &mut Window, &mut App) + 'static)Receives the index of the slide to show next.