use std::{cell::RefCell, rc::Rc, time::Instant};
use arc_motion::{arc_spring_with_options, is_reduced_motion, spring::SpringOptions};
use arc_tokens::{ActiveArcTheme as _, Radii, Spacing, SpringSpec, Typography, oklab_mix};
use gpui_kit::{
AnyElement, App, Bounds, ElementId, FocusHandle, Hsla, IntoElement, KeyDownEvent, MouseButton,
MouseDownEvent, MouseMoveEvent, MouseUpEvent, ParentElement, PathBuilder, Pixels, RenderOnce,
Role, ScrollDelta, ScrollEvent, SharedString, Styled, Window, canvas, div, point, prelude::*,
px,
};
pub const CAROUSEL_DOT_PX: f32 = 6.0;
pub const CAROUSEL_PILL_PX: f32 = 22.0;
pub const CAROUSEL_NEIGHBOUR_SCALE: f32 = 0.90;
pub const CAROUSEL_NEIGHBOUR_DIM: f32 = 0.50;
pub const CAROUSEL_FLICK_PX_S: f32 = 360.0;
const CAROUSEL_GAP_PX: f32 = 16.0;
const CAROUSEL_SLOP_PX: f32 = 6.0;
pub fn carousel_rubber(overshoot: f32, dimension: f32) -> f32 {
if overshoot <= 0.0 || dimension <= 0.0 {
return 0.0;
}
overshoot * dimension * 0.55 / (dimension + 0.55 * overshoot)
}
pub fn carousel_project(velocity_px_s: f32) -> f32 {
let rate = 0.995_f32;
(velocity_px_s / 1000.0) * rate / (1.0 - rate)
}
pub fn carousel_slide_emphasis(slide_index: usize, progress: f32) -> (f32, f32) {
let dist = (progress - slide_index as f32).abs().clamp(0.0, 1.0);
let scale = 1.0 - (1.0 - CAROUSEL_NEIGHBOUR_SCALE) * dist;
let opacity = 1.0 - (1.0 - CAROUSEL_NEIGHBOUR_DIM) * dist;
(scale, opacity)
}
pub fn carousel_dot_metrics(dot_index: usize, last_index: usize, progress: f32) -> (f32, f32) {
let clamped = progress.clamp(0.0, last_index as f32);
let emphasis = (1.0 - (clamped - dot_index as f32).abs()).max(0.0);
let width = CAROUSEL_DOT_PX + (CAROUSEL_PILL_PX - CAROUSEL_DOT_PX) * emphasis;
(width, emphasis)
}
pub fn carousel_resolve_release(
current_x: f32,
velocity_px_s: f32,
from_index: usize,
step_px: f32,
last_index: usize,
) -> usize {
if step_px <= 1.0 || last_index == 0 {
return 0;
}
let projected = current_x + carousel_project(velocity_px_s);
let mut to = (-projected / step_px).round() as isize;
if velocity_px_s.abs() > CAROUSEL_FLICK_PX_S {
let dir: isize = if velocity_px_s < 0.0 { 1 } else { -1 };
if (to - from_index as isize) * dir < 1 {
to = from_index as isize + dir;
}
}
to.clamp(0, last_index as isize) as usize
}
fn paint_chevron(cx: f32, cy: f32, right: bool, color: Hsla, window: &mut Window) {
let mut pb = PathBuilder::stroke(px(1.75));
if right {
pb.move_to(point(px(cx - 2.5), px(cy - 4.5)));
pb.line_to(point(px(cx + 2.5), px(cy)));
pb.line_to(point(px(cx - 2.5), px(cy + 4.5)));
} else {
pb.move_to(point(px(cx + 2.5), px(cy - 4.5)));
pb.line_to(point(px(cx - 2.5), px(cy)));
pb.line_to(point(px(cx + 2.5), px(cy + 4.5)));
}
if let Ok(path) = pb.build() {
window.paint_path(path, color);
}
}
fn paint_play_pause(cx: f32, cy: f32, playing: bool, color: Hsla, window: &mut Window) {
if playing {
let mut left = PathBuilder::stroke(px(2.0));
left.move_to(point(px(cx - 2.6), px(cy - 4.2)));
left.line_to(point(px(cx - 2.6), px(cy + 4.2)));
if let Ok(p) = left.build() {
window.paint_path(p, color);
}
let mut right = PathBuilder::stroke(px(2.0));
right.move_to(point(px(cx + 2.6), px(cy - 4.2)));
right.line_to(point(px(cx + 2.6), px(cy + 4.2)));
if let Ok(p) = right.build() {
window.paint_path(p, color);
}
} else {
let mut tri = PathBuilder::fill();
tri.move_to(point(px(cx - 3.0), px(cy - 4.5)));
tri.line_to(point(px(cx + 4.5), px(cy)));
tri.line_to(point(px(cx - 3.0), px(cy + 4.5)));
tri.close();
if let Ok(p) = tri.build() {
window.paint_path(p, color);
}
}
}
type SlideBuilder = Rc<dyn Fn(bool, &mut Window, &mut App) -> AnyElement>;
type IndexCallback = Rc<dyn Fn(usize, &mut Window, &mut App)>;
#[derive(Clone)]
struct CarouselSlideSpec {
label: SharedString,
render: SlideBuilder,
}
#[derive(Clone)]
struct DragSession {
start_x: f32,
start_y: f32,
origin_x: f32,
from_index: usize,
locked_x: bool,
samples: Vec<(Instant, f32)>,
}
#[derive(Clone)]
struct CarouselInternal {
index: usize,
playing: bool,
hovered: bool,
dragging: bool,
drag_x: f32,
drag: Option<DragSession>,
viewport_bounds: Option<Bounds<Pixels>>,
drain_start: Instant,
drain_paused_fraction: f32,
focus_handle: FocusHandle,
}
impl CarouselInternal {
fn velocity_px_s(&self, now: Instant) -> f32 {
let Some(drag) = &self.drag else {
return 0.0;
};
let recent: Vec<&(Instant, f32)> = drag
.samples
.iter()
.filter(|(t, _)| now.saturating_duration_since(*t).as_millis() <= 90)
.collect();
if recent.len() < 2 {
return 0.0;
}
let (t0, x0) = *recent[0];
let (t1, x1) = *recent[recent.len() - 1];
if now.saturating_duration_since(t1).as_millis() > 50 {
return 0.0;
}
let secs = t1.saturating_duration_since(t0).as_secs_f32();
if secs > 0.001 { (x1 - x0) / secs } else { 0.0 }
}
}
#[derive(IntoElement)]
pub struct Carousel {
id: ElementId,
label: SharedString,
slides: Vec<CarouselSlideSpec>,
index_override: Option<usize>,
default_index: usize,
slide_width: f32,
slide_height: f32,
interval_ms: Option<u64>,
autoplay: bool,
on_index_change: Option<IndexCallback>,
}
impl Carousel {
pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
Self {
id: id.into(),
label: label.into(),
slides: Vec::new(),
index_override: None,
default_index: 0,
slide_width: 320.0,
slide_height: 220.0,
interval_ms: None,
autoplay: false,
on_index_change: None,
}
}
pub fn slide(
mut self,
label: impl Into<SharedString>,
render: impl Fn(bool, &mut Window, &mut App) -> AnyElement + 'static,
) -> Self {
self.slides.push(CarouselSlideSpec {
label: label.into(),
render: Rc::new(render),
});
self
}
pub fn index(mut self, index: usize) -> Self {
self.index_override = Some(index);
self
}
pub fn default_index(mut self, index: usize) -> Self {
self.default_index = index;
self
}
pub fn slide_width(mut self, width: f32) -> Self {
self.slide_width = width.max(160.0);
self
}
pub fn slide_height(mut self, height: f32) -> Self {
self.slide_height = height.max(120.0);
self
}
pub fn interval_ms(mut self, ms: u64) -> Self {
self.interval_ms = if ms > 0 { Some(ms) } else { None };
self
}
pub fn autoplay(mut self, autoplay: bool) -> Self {
self.autoplay = autoplay;
self
}
pub fn on_index_change(
mut self,
handler: impl Fn(usize, &mut Window, &mut App) + 'static,
) -> Self {
self.on_index_change = Some(Rc::new(handler));
self
}
}
impl RenderOnce for Carousel {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let theme = cx.arc_theme().clone();
let reduced = is_reduced_motion(cx);
let count = self.slides.len();
let last = count.saturating_sub(1);
let default_idx = self.default_index.min(last);
let initial_playing = self.autoplay && self.interval_ms.is_some();
let state = window.use_keyed_state(
ElementId::Name(format!("arc-carousel-state-{:?}", self.id).into()),
cx,
|_, cx| {
Rc::new(RefCell::new(CarouselInternal {
index: default_idx,
playing: initial_playing,
hovered: false,
dragging: false,
drag_x: 0.0,
drag: None,
viewport_bounds: None,
drain_start: Instant::now(),
drain_paused_fraction: 0.0,
focus_handle: cx.focus_handle(),
}))
},
);
let shared = state.read(cx).clone();
let focus_handle = shared.borrow().focus_handle.clone();
let active_index = self
.index_override
.unwrap_or_else(|| shared.borrow().index)
.min(last);
let prev_idx = shared.borrow().index;
if self.index_override.is_some() && prev_idx != active_index {
let mut st = shared.borrow_mut();
st.index = active_index;
st.drain_start = Instant::now();
st.drain_paused_fraction = 0.0;
}
let viewport_w = shared
.borrow()
.viewport_bounds
.map(|b| f32::from(b.size.width))
.unwrap_or(self.slide_width + 120.0)
.max(200.0);
let slide_w = self.slide_width.min((viewport_w * 0.82).max(160.0));
let step_px = slide_w + CAROUSEL_GAP_PX;
let can_rotate = self.interval_ms.is_some() && count > 1 && !reduced;
let is_playing = can_rotate && shared.borrow().playing;
let is_hovered = shared.borrow().hovered;
let is_dragging = shared.borrow().dragging;
let running = is_playing && !is_hovered && !is_dragging;
let drain_fraction = if let Some(interval_ms) = self.interval_ms {
if running {
let elapsed_ms = {
let st = shared.borrow();
st.drain_paused_fraction * interval_ms as f32
+ st.drain_start.elapsed().as_secs_f32() * 1000.0
};
let frac = (elapsed_ms / interval_ms as f32).clamp(0.0, 1.0);
if frac >= 1.0 {
let next = if active_index >= last {
0
} else {
active_index + 1
};
{
let mut st = shared.borrow_mut();
st.index = next;
st.drain_start = Instant::now();
st.drain_paused_fraction = 0.0;
}
if let Some(cb) = self.on_index_change.clone() {
window.defer(cx, move |window, cx| {
cb(next, window, cx);
});
}
window.request_animation_frame();
0.0
} else {
window.request_animation_frame();
frac
}
} else {
shared.borrow().drain_paused_fraction
}
} else {
0.0
};
let target_x = -(active_index as f32) * step_px;
let spring_key = format!("arc-carousel-x-{:?}", self.id);
let smooth_x = if reduced {
target_x
} else {
arc_spring_with_options(
spring_key,
if is_dragging {
shared.borrow().drag_x
} else {
target_x
},
SpringOptions::new(SpringSpec::visual(0.36, 0.0)),
window,
cx,
)
.value
};
let shown_x = if is_dragging {
shared.borrow().drag_x
} else {
smooth_x
};
let progress = if step_px > 1.0 {
-shown_x / step_px
} else {
active_index as f32
};
let select_slide = {
let shared = shared.clone();
let on_change = self.on_index_change.clone();
Rc::new(move |next: usize, window: &mut Window, cx: &mut App| {
let clamped = next.min(last);
let changed = {
let mut st = shared.borrow_mut();
let changed = st.index != clamped;
st.index = clamped;
st.drain_start = Instant::now();
st.drain_paused_fraction = 0.0;
changed
};
if changed && let Some(cb) = &on_change {
cb(clamped, window, cx);
}
window.refresh();
})
};
let shared_bounds = shared.clone();
let shared_move = shared.clone();
let shared_up = shared.clone();
let select_up = select_slide.clone();
let min_x = -(last as f32) * step_px;
let measurement_canvas = canvas(
move |bounds, _, _| {
shared_bounds.borrow_mut().viewport_bounds = Some(bounds);
bounds
},
move |bounds, _, window, _cx| {
let width = f32::from(bounds.size.width).max(1.0);
let shared_m = shared_move.clone();
window.on_mouse_event(move |event: &MouseMoveEvent, _, window, _cx| {
let mut st = shared_m.borrow_mut();
let px_x = f32::from(event.position.x);
let px_y = f32::from(event.position.y);
let mut became_dragging = false;
let mut cancel_drag = false;
let banded = {
let Some(drag) = st.drag.as_mut() else {
return;
};
if !drag.locked_x {
let dx = px_x - drag.start_x;
let dy = px_y - drag.start_y;
if dx.abs() < CAROUSEL_SLOP_PX && dy.abs() < CAROUSEL_SLOP_PX {
return;
}
if dy.abs() > dx.abs() {
cancel_drag = true;
0.0
} else {
drag.locked_x = true;
drag.start_x = px_x;
became_dragging = true;
drag.origin_x
}
} else {
let raw = drag.origin_x + (px_x - drag.start_x);
let b = if raw > 0.0 {
carousel_rubber(raw, width)
} else if raw < min_x {
min_x - carousel_rubber(min_x - raw, width)
} else {
raw
};
drag.samples.push((Instant::now(), px_x));
if drag.samples.len() > 16 {
drag.samples.remove(0);
}
b
}
};
if cancel_drag {
st.drag = None;
return;
}
if became_dragging {
st.dragging = true;
}
st.drag_x = banded;
window.refresh();
});
let shared_u = shared_up.clone();
let select_u = select_up.clone();
window.on_mouse_event(move |event: &MouseUpEvent, _, window, cx| {
let (was_locked, current_x, velocity, from_idx, click_x) = {
let mut st = shared_u.borrow_mut();
let Some(drag) = st.drag.clone() else {
return;
};
let vel = st.velocity_px_s(Instant::now());
let locked = drag.locked_x;
let cur_x = st.drag_x;
let from = drag.from_index;
st.drag = None;
st.dragging = false;
st.drain_start = Instant::now();
(locked, cur_x, vel, from, f32::from(event.position.x))
};
if was_locked {
let next =
carousel_resolve_release(current_x, velocity, from_idx, step_px, last);
select_u(next, window, cx);
} else {
let bounds = shared_u.borrow().viewport_bounds;
if let Some(b) = bounds {
let center_x = f32::from(b.origin.x) + f32::from(b.size.width) * 0.5;
let offset = click_x - center_x;
if offset.abs() > slide_w * 0.52 {
let next = if offset > 0.0 {
(from_idx + 1).min(last)
} else {
from_idx.saturating_sub(1)
};
if next != from_idx {
select_u(next, window, cx);
}
}
}
}
});
},
)
.size_full()
.absolute()
.inset_0();
let side_pad = ((viewport_w - slide_w) * 0.5).max(0.0);
let track_left = side_pad + shown_x;
let mut slide_nodes = Vec::with_capacity(count);
for (i, spec) in self.slides.into_iter().enumerate() {
let (scale, opacity) = carousel_slide_emphasis(i, progress);
let is_active = i == active_index;
let scaled_w = slide_w * scale;
let scaled_h = self.slide_height * scale;
let left_px = track_left + (i as f32) * step_px + (slide_w - scaled_w) * 0.5;
let top_px = (self.slide_height - scaled_h) * 0.5;
let content = (spec.render)(is_active, window, cx);
slide_nodes.push(
div()
.id(ElementId::Name(
format!("arc-carousel-slide-{:?}-{}", self.id, i).into(),
))
.role(Role::TabPanel)
.aria_label(spec.label)
.absolute()
.left(px(left_px))
.top(px(top_px))
.w(px(scaled_w))
.h(px(scaled_h))
.opacity(opacity)
.overflow_hidden()
.rounded(Radii::SURFACE)
.child(content),
);
}
let shared_down = shared.clone();
let fh_down = focus_handle.clone();
let shared_hover = shared.clone();
let interval_for_hover = self.interval_ms;
let select_wheel = select_slide.clone();
let shared_wheel = shared.clone();
let select_key = select_slide.clone();
let shared_key = shared.clone();
let viewport = div()
.id(ElementId::Name(
format!("arc-carousel-viewport-{:?}", self.id).into(),
))
.role(Role::Group)
.aria_label("Slides")
.track_focus(&focus_handle)
.relative()
.w_full()
.h(px(self.slide_height))
.overflow_hidden()
.rounded(Radii::PANEL)
.cursor_grab()
.on_hover(move |hovered, window, _cx| {
let mut st = shared_hover.borrow_mut();
if st.hovered == *hovered {
return;
}
if let Some(ms) = interval_for_hover {
if *hovered && st.playing {
let extra = st.drain_start.elapsed().as_secs_f32() * 1000.0 / ms as f32;
st.drain_paused_fraction = (st.drain_paused_fraction + extra).min(0.99);
} else if !*hovered && st.playing {
st.drain_start = Instant::now();
}
}
st.hovered = *hovered;
window.refresh();
})
.on_mouse_down(
MouseButton::Left,
move |event: &MouseDownEvent, window, cx| {
if count < 2 {
return;
}
window.focus(&fh_down, cx);
let px_x = f32::from(event.position.x);
let px_y = f32::from(event.position.y);
let mut st = shared_down.borrow_mut();
st.drag_x = shown_x;
st.drag = Some(DragSession {
start_x: px_x,
start_y: px_y,
origin_x: shown_x,
from_index: active_index,
locked_x: false,
samples: vec![(Instant::now(), px_x)],
});
},
)
.on_scroll(move |event: &ScrollEvent, window, cx| {
if count < 2 {
return;
}
let delta_x = match event.delta {
ScrollDelta::Pixels(p) => f32::from(p.x),
ScrollDelta::Lines(p) => p.x * 24.0,
};
let delta_y = match event.delta {
ScrollDelta::Pixels(p) => f32::from(p.y),
ScrollDelta::Lines(p) => p.y * 24.0,
};
if delta_x.abs() <= delta_y.abs() || delta_x.abs() < 12.0 {
return;
}
let cur = shared_wheel.borrow().index;
let next = if delta_x < 0.0 {
(cur + 1).min(last)
} else {
cur.saturating_sub(1)
};
if next != cur {
select_wheel(next, window, cx);
}
})
.on_key_down(move |event: &KeyDownEvent, window, cx| {
if count < 2 {
return;
}
let cur = shared_key.borrow().index;
let next = match event.keystroke.key.as_str() {
"left" => Some(cur.saturating_sub(1)),
"right" => Some((cur + 1).min(last)),
"home" => Some(0),
"end" => Some(last),
_ => None,
};
if let Some(target) = next {
select_key(target, window, cx);
}
})
.child(measurement_canvas)
.children(slide_nodes);
let mut root = div()
.id(self.id.clone())
.role(Role::Region)
.aria_label(self.label)
.w_full()
.flex()
.flex_col()
.gap(Spacing::S4)
.child(viewport);
if count > 1 {
let mut controls = div()
.w_full()
.px(px(side_pad))
.flex()
.items_center()
.gap(Spacing::S2);
if can_rotate {
let shared_play = shared.clone();
let fg_color = theme.colors.foreground;
let play_btn = div()
.id(ElementId::Name(
format!("arc-carousel-play-{:?}", self.id).into(),
))
.role(Role::Button)
.aria_label(if is_playing {
"Pause slide rotation"
} else {
"Start slide rotation"
})
.w(px(32.0))
.h(px(32.0))
.rounded(Radii::PILL)
.border_1()
.border_color(theme.colors.border)
.bg(theme.colors.surface)
.hover(|s| s.bg(theme.colors.surface_muted))
.cursor_pointer()
.flex()
.items_center()
.justify_center()
.on_mouse_down(MouseButton::Left, move |_, window, _| {
let mut st = shared_play.borrow_mut();
st.playing = !st.playing;
st.drain_start = Instant::now();
if !st.playing {
st.drain_paused_fraction = 0.0;
}
window.refresh();
})
.child(
canvas(
|bounds, _, _| bounds,
move |bounds, _, window, _| {
let cx =
f32::from(bounds.origin.x) + f32::from(bounds.size.width) * 0.5;
let cy = f32::from(bounds.origin.y)
+ f32::from(bounds.size.height) * 0.5;
paint_play_pause(cx, cy, is_playing, fg_color, window);
},
)
.w(px(16.0))
.h(px(16.0)),
);
controls = controls.child(play_btn);
}
let mut tabs = div()
.id(ElementId::Name(
format!("arc-carousel-tabs-{:?}", self.id).into(),
))
.role(Role::TabList)
.aria_label("Choose a slide")
.flex()
.items_center()
.gap(px(2.0));
for i in 0..count {
let (dot_w, emphasis) = carousel_dot_metrics(i, last, progress);
let fill_color = oklab_mix(
theme.colors.border_strong,
theme.colors.foreground,
emphasis,
);
let select_dot = select_slide.clone();
let show_drain =
can_rotate && i == active_index && is_playing && drain_fraction > 0.0;
let drain_w = (dot_w * drain_fraction).clamp(0.0, dot_w);
let mut dot_track = div()
.relative()
.w(px(dot_w))
.h(px(CAROUSEL_DOT_PX))
.rounded(Radii::PILL)
.bg(fill_color)
.overflow_hidden();
if show_drain {
dot_track = dot_track.child(
div()
.absolute()
.top_0()
.bottom_0()
.right_0()
.w(px(drain_w))
.bg(theme.colors.border_strong),
);
}
let tab_btn = div()
.id(ElementId::Name(
format!("arc-carousel-dot-{:?}-{}", self.id, i).into(),
))
.role(Role::Tab)
.aria_label(format!("{} of {}", i + 1, count))
.h(px(32.0))
.px(px(5.0))
.rounded(Radii::PILL)
.cursor_pointer()
.flex()
.items_center()
.justify_center()
.on_mouse_down(MouseButton::Left, move |_, window, cx| {
select_dot(i, window, cx);
})
.child(dot_track);
tabs = tabs.child(tab_btn);
}
controls = controls.child(tabs);
let at_start = active_index == 0;
let at_end = active_index >= last;
let select_prev = select_slide.clone();
let select_next = select_slide.clone();
let prev_icon_color = if at_start {
theme.colors.text_muted
} else {
theme.colors.foreground
};
let next_icon_color = if at_end {
theme.colors.text_muted
} else {
theme.colors.foreground
};
let prev_btn = div()
.id(ElementId::Name(
format!("arc-carousel-prev-{:?}", self.id).into(),
))
.role(Role::Button)
.aria_label("Previous slide")
.w(px(32.0))
.h(px(32.0))
.rounded(Radii::PILL)
.border_1()
.border_color(theme.colors.border)
.bg(theme.colors.surface)
.opacity(if at_start { 0.45 } else { 1.0 })
.when(!at_start, |el| {
el.cursor_pointer()
.hover(|s| s.bg(theme.colors.surface_muted))
})
.flex()
.items_center()
.justify_center()
.on_mouse_down(MouseButton::Left, move |_, window, cx| {
if !at_start {
select_prev(active_index.saturating_sub(1), window, cx);
}
})
.child(
canvas(
|bounds, _, _| bounds,
move |bounds, _, window, _| {
let cx =
f32::from(bounds.origin.x) + f32::from(bounds.size.width) * 0.5;
let cy =
f32::from(bounds.origin.y) + f32::from(bounds.size.height) * 0.5;
paint_chevron(cx, cy, false, prev_icon_color, window);
},
)
.w(px(16.0))
.h(px(16.0)),
);
let next_btn = div()
.id(ElementId::Name(
format!("arc-carousel-next-{:?}", self.id).into(),
))
.role(Role::Button)
.aria_label("Next slide")
.w(px(32.0))
.h(px(32.0))
.rounded(Radii::PILL)
.border_1()
.border_color(theme.colors.border)
.bg(theme.colors.surface)
.opacity(if at_end { 0.45 } else { 1.0 })
.when(!at_end, |el| {
el.cursor_pointer()
.hover(|s| s.bg(theme.colors.surface_muted))
})
.flex()
.items_center()
.justify_center()
.on_mouse_down(MouseButton::Left, move |_, window, cx| {
if !at_end {
select_next((active_index + 1).min(last), window, cx);
}
})
.child(
canvas(
|bounds, _, _| bounds,
move |bounds, _, window, _| {
let cx =
f32::from(bounds.origin.x) + f32::from(bounds.size.width) * 0.5;
let cy =
f32::from(bounds.origin.y) + f32::from(bounds.size.height) * 0.5;
paint_chevron(cx, cy, true, next_icon_color, window);
},
)
.w(px(16.0))
.h(px(16.0)),
);
let counter_chip = div()
.text_size(Typography::TEXT_XS)
.text_color(theme.colors.text_muted)
.child(format!("{} / {}", active_index + 1, count));
let arrows = div()
.ml_auto()
.flex()
.items_center()
.gap(Spacing::S2)
.child(counter_chip)
.child(prev_btn)
.child(next_btn);
controls = controls.child(arrows);
root = root.child(controls);
}
root
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn carousel_math_rubber_projection_dots_and_release() {
let r1 = carousel_rubber(40.0, 320.0);
let r2 = carousel_rubber(120.0, 320.0);
assert!(r1 > 0.0 && r1 < 40.0);
assert!(r2 > r1 && r2 < 120.0);
let (s0, o0) = carousel_slide_emphasis(1, 1.0);
assert!((s0 - 1.0).abs() < 1e-4 && (o0 - 1.0).abs() < 1e-4);
let (s1, o1) = carousel_slide_emphasis(2, 1.0);
assert!((s1 - CAROUSEL_NEIGHBOUR_SCALE).abs() < 1e-4);
assert!((o1 - CAROUSEL_NEIGHBOUR_DIM).abs() < 1e-4);
let (w_active, e_active) = carousel_dot_metrics(1, 3, 1.0);
assert!((w_active - CAROUSEL_PILL_PX).abs() < 1e-4 && (e_active - 1.0).abs() < 1e-4);
let (w_mid, _) = carousel_dot_metrics(1, 3, 1.5);
assert!((w_mid - 14.0).abs() < 1e-4);
let landed = carousel_resolve_release(-20.0, -500.0, 0, 336.0, 3);
assert_eq!(landed, 1);
}
}