1use std::{cell::RefCell, rc::Rc, time::Instant};
15
16use arc_motion::{arc_spring_with_options, is_reduced_motion, spring::SpringOptions};
17use arc_tokens::{ActiveArcTheme as _, Radii, Spacing, SpringSpec, Typography, oklab_mix};
18use gpui_kit::{
19 AnyElement, App, Bounds, ElementId, FocusHandle, Hsla, IntoElement, KeyDownEvent, MouseButton,
20 MouseDownEvent, MouseMoveEvent, MouseUpEvent, ParentElement, PathBuilder, Pixels, RenderOnce,
21 Role, ScrollDelta, ScrollEvent, SharedString, Styled, Window, canvas, div, point, prelude::*,
22 px,
23};
24
25pub const CAROUSEL_DOT_PX: f32 = 6.0;
27pub const CAROUSEL_PILL_PX: f32 = 22.0;
28pub const CAROUSEL_NEIGHBOUR_SCALE: f32 = 0.90;
30pub const CAROUSEL_NEIGHBOUR_DIM: f32 = 0.50;
31pub const CAROUSEL_FLICK_PX_S: f32 = 360.0;
33const CAROUSEL_GAP_PX: f32 = 16.0;
35const CAROUSEL_SLOP_PX: f32 = 6.0;
37
38pub fn carousel_rubber(overshoot: f32, dimension: f32) -> f32 {
40 if overshoot <= 0.0 || dimension <= 0.0 {
41 return 0.0;
42 }
43 overshoot * dimension * 0.55 / (dimension + 0.55 * overshoot)
44}
45
46pub fn carousel_project(velocity_px_s: f32) -> f32 {
48 let rate = 0.995_f32;
49 (velocity_px_s / 1000.0) * rate / (1.0 - rate)
50}
51
52pub fn carousel_slide_emphasis(slide_index: usize, progress: f32) -> (f32, f32) {
54 let dist = (progress - slide_index as f32).abs().clamp(0.0, 1.0);
55 let scale = 1.0 - (1.0 - CAROUSEL_NEIGHBOUR_SCALE) * dist;
56 let opacity = 1.0 - (1.0 - CAROUSEL_NEIGHBOUR_DIM) * dist;
57 (scale, opacity)
58}
59
60pub fn carousel_dot_metrics(dot_index: usize, last_index: usize, progress: f32) -> (f32, f32) {
62 let clamped = progress.clamp(0.0, last_index as f32);
63 let emphasis = (1.0 - (clamped - dot_index as f32).abs()).max(0.0);
64 let width = CAROUSEL_DOT_PX + (CAROUSEL_PILL_PX - CAROUSEL_DOT_PX) * emphasis;
65 (width, emphasis)
66}
67
68pub fn carousel_resolve_release(
70 current_x: f32,
71 velocity_px_s: f32,
72 from_index: usize,
73 step_px: f32,
74 last_index: usize,
75) -> usize {
76 if step_px <= 1.0 || last_index == 0 {
77 return 0;
78 }
79 let projected = current_x + carousel_project(velocity_px_s);
80 let mut to = (-projected / step_px).round() as isize;
81 if velocity_px_s.abs() > CAROUSEL_FLICK_PX_S {
82 let dir: isize = if velocity_px_s < 0.0 { 1 } else { -1 };
83 if (to - from_index as isize) * dir < 1 {
84 to = from_index as isize + dir;
85 }
86 }
87 to.clamp(0, last_index as isize) as usize
88}
89
90fn paint_chevron(cx: f32, cy: f32, right: bool, color: Hsla, window: &mut Window) {
91 let mut pb = PathBuilder::stroke(px(1.75));
92 if right {
93 pb.move_to(point(px(cx - 2.5), px(cy - 4.5)));
94 pb.line_to(point(px(cx + 2.5), px(cy)));
95 pb.line_to(point(px(cx - 2.5), px(cy + 4.5)));
96 } else {
97 pb.move_to(point(px(cx + 2.5), px(cy - 4.5)));
98 pb.line_to(point(px(cx - 2.5), px(cy)));
99 pb.line_to(point(px(cx + 2.5), px(cy + 4.5)));
100 }
101 if let Ok(path) = pb.build() {
102 window.paint_path(path, color);
103 }
104}
105
106fn paint_play_pause(cx: f32, cy: f32, playing: bool, color: Hsla, window: &mut Window) {
107 if playing {
108 let mut left = PathBuilder::stroke(px(2.0));
110 left.move_to(point(px(cx - 2.6), px(cy - 4.2)));
111 left.line_to(point(px(cx - 2.6), px(cy + 4.2)));
112 if let Ok(p) = left.build() {
113 window.paint_path(p, color);
114 }
115 let mut right = PathBuilder::stroke(px(2.0));
116 right.move_to(point(px(cx + 2.6), px(cy - 4.2)));
117 right.line_to(point(px(cx + 2.6), px(cy + 4.2)));
118 if let Ok(p) = right.build() {
119 window.paint_path(p, color);
120 }
121 } else {
122 let mut tri = PathBuilder::fill();
124 tri.move_to(point(px(cx - 3.0), px(cy - 4.5)));
125 tri.line_to(point(px(cx + 4.5), px(cy)));
126 tri.line_to(point(px(cx - 3.0), px(cy + 4.5)));
127 tri.close();
128 if let Ok(p) = tri.build() {
129 window.paint_path(p, color);
130 }
131 }
132}
133
134type SlideBuilder = Rc<dyn Fn(bool, &mut Window, &mut App) -> AnyElement>;
135type IndexCallback = Rc<dyn Fn(usize, &mut Window, &mut App)>;
136
137#[derive(Clone)]
138struct CarouselSlideSpec {
139 label: SharedString,
140 render: SlideBuilder,
141}
142
143#[derive(Clone)]
144struct DragSession {
145 start_x: f32,
146 start_y: f32,
147 origin_x: f32,
148 from_index: usize,
149 locked_x: bool,
150 samples: Vec<(Instant, f32)>,
151}
152
153#[derive(Clone)]
154struct CarouselInternal {
155 index: usize,
156 playing: bool,
157 hovered: bool,
158 dragging: bool,
159 drag_x: f32,
160 drag: Option<DragSession>,
161 viewport_bounds: Option<Bounds<Pixels>>,
162 drain_start: Instant,
163 drain_paused_fraction: f32,
164 focus_handle: FocusHandle,
165}
166
167impl CarouselInternal {
168 fn velocity_px_s(&self, now: Instant) -> f32 {
169 let Some(drag) = &self.drag else {
170 return 0.0;
171 };
172 let recent: Vec<&(Instant, f32)> = drag
173 .samples
174 .iter()
175 .filter(|(t, _)| now.saturating_duration_since(*t).as_millis() <= 90)
176 .collect();
177 if recent.len() < 2 {
178 return 0.0;
179 }
180 let (t0, x0) = *recent[0];
181 let (t1, x1) = *recent[recent.len() - 1];
182 if now.saturating_duration_since(t1).as_millis() > 50 {
183 return 0.0;
184 }
185 let secs = t1.saturating_duration_since(t0).as_secs_f32();
186 if secs > 0.001 { (x1 - x0) / secs } else { 0.0 }
187 }
188}
189
190#[derive(IntoElement)]
192pub struct Carousel {
193 id: ElementId,
194 label: SharedString,
195 slides: Vec<CarouselSlideSpec>,
196 index_override: Option<usize>,
197 default_index: usize,
198 slide_width: f32,
199 slide_height: f32,
200 interval_ms: Option<u64>,
201 autoplay: bool,
202 on_index_change: Option<IndexCallback>,
203}
204
205impl Carousel {
206 pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
207 Self {
208 id: id.into(),
209 label: label.into(),
210 slides: Vec::new(),
211 index_override: None,
212 default_index: 0,
213 slide_width: 320.0,
214 slide_height: 220.0,
215 interval_ms: None,
216 autoplay: false,
217 on_index_change: None,
218 }
219 }
220
221 pub fn slide(
223 mut self,
224 label: impl Into<SharedString>,
225 render: impl Fn(bool, &mut Window, &mut App) -> AnyElement + 'static,
226 ) -> Self {
227 self.slides.push(CarouselSlideSpec {
228 label: label.into(),
229 render: Rc::new(render),
230 });
231 self
232 }
233
234 pub fn index(mut self, index: usize) -> Self {
236 self.index_override = Some(index);
237 self
238 }
239
240 pub fn default_index(mut self, index: usize) -> Self {
242 self.default_index = index;
243 self
244 }
245
246 pub fn slide_width(mut self, width: f32) -> Self {
248 self.slide_width = width.max(160.0);
249 self
250 }
251
252 pub fn slide_height(mut self, height: f32) -> Self {
254 self.slide_height = height.max(120.0);
255 self
256 }
257
258 pub fn interval_ms(mut self, ms: u64) -> Self {
260 self.interval_ms = if ms > 0 { Some(ms) } else { None };
261 self
262 }
263
264 pub fn autoplay(mut self, autoplay: bool) -> Self {
266 self.autoplay = autoplay;
267 self
268 }
269
270 pub fn on_index_change(
272 mut self,
273 handler: impl Fn(usize, &mut Window, &mut App) + 'static,
274 ) -> Self {
275 self.on_index_change = Some(Rc::new(handler));
276 self
277 }
278}
279
280impl RenderOnce for Carousel {
281 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
282 let theme = cx.arc_theme().clone();
283 let reduced = is_reduced_motion(cx);
284 let count = self.slides.len();
285 let last = count.saturating_sub(1);
286 let default_idx = self.default_index.min(last);
287 let initial_playing = self.autoplay && self.interval_ms.is_some();
288
289 let state = window.use_keyed_state(
290 ElementId::Name(format!("arc-carousel-state-{:?}", self.id).into()),
291 cx,
292 |_, cx| {
293 Rc::new(RefCell::new(CarouselInternal {
294 index: default_idx,
295 playing: initial_playing,
296 hovered: false,
297 dragging: false,
298 drag_x: 0.0,
299 drag: None,
300 viewport_bounds: None,
301 drain_start: Instant::now(),
302 drain_paused_fraction: 0.0,
303 focus_handle: cx.focus_handle(),
304 }))
305 },
306 );
307 let shared = state.read(cx).clone();
308 let focus_handle = shared.borrow().focus_handle.clone();
309
310 let active_index = self
311 .index_override
312 .unwrap_or_else(|| shared.borrow().index)
313 .min(last);
314 let prev_idx = shared.borrow().index;
315 if self.index_override.is_some() && prev_idx != active_index {
316 let mut st = shared.borrow_mut();
317 st.index = active_index;
318 st.drain_start = Instant::now();
319 st.drain_paused_fraction = 0.0;
320 }
321
322 let viewport_w = shared
323 .borrow()
324 .viewport_bounds
325 .map(|b| f32::from(b.size.width))
326 .unwrap_or(self.slide_width + 120.0)
327 .max(200.0);
328 let slide_w = self.slide_width.min((viewport_w * 0.82).max(160.0));
329 let step_px = slide_w + CAROUSEL_GAP_PX;
330
331 let can_rotate = self.interval_ms.is_some() && count > 1 && !reduced;
332 let is_playing = can_rotate && shared.borrow().playing;
333 let is_hovered = shared.borrow().hovered;
334 let is_dragging = shared.borrow().dragging;
335 let running = is_playing && !is_hovered && !is_dragging;
336
337 let drain_fraction = if let Some(interval_ms) = self.interval_ms {
339 if running {
340 let elapsed_ms = {
341 let st = shared.borrow();
342 st.drain_paused_fraction * interval_ms as f32
343 + st.drain_start.elapsed().as_secs_f32() * 1000.0
344 };
345 let frac = (elapsed_ms / interval_ms as f32).clamp(0.0, 1.0);
346 if frac >= 1.0 {
347 let next = if active_index >= last {
348 0
349 } else {
350 active_index + 1
351 };
352 {
353 let mut st = shared.borrow_mut();
354 st.index = next;
355 st.drain_start = Instant::now();
356 st.drain_paused_fraction = 0.0;
357 }
358 if let Some(cb) = self.on_index_change.clone() {
359 window.defer(cx, move |window, cx| {
360 cb(next, window, cx);
361 });
362 }
363 window.request_animation_frame();
364 0.0
365 } else {
366 window.request_animation_frame();
367 frac
368 }
369 } else {
370 shared.borrow().drain_paused_fraction
371 }
372 } else {
373 0.0
374 };
375
376 let target_x = -(active_index as f32) * step_px;
378 let spring_key = format!("arc-carousel-x-{:?}", self.id);
379 let smooth_x = if reduced {
380 target_x
381 } else {
382 arc_spring_with_options(
383 spring_key,
384 if is_dragging {
385 shared.borrow().drag_x
386 } else {
387 target_x
388 },
389 SpringOptions::new(SpringSpec::visual(0.36, 0.0)),
390 window,
391 cx,
392 )
393 .value
394 };
395 let shown_x = if is_dragging {
396 shared.borrow().drag_x
397 } else {
398 smooth_x
399 };
400 let progress = if step_px > 1.0 {
401 -shown_x / step_px
402 } else {
403 active_index as f32
404 };
405
406 let select_slide = {
407 let shared = shared.clone();
408 let on_change = self.on_index_change.clone();
409 Rc::new(move |next: usize, window: &mut Window, cx: &mut App| {
410 let clamped = next.min(last);
411 let changed = {
412 let mut st = shared.borrow_mut();
413 let changed = st.index != clamped;
414 st.index = clamped;
415 st.drain_start = Instant::now();
416 st.drain_paused_fraction = 0.0;
417 changed
418 };
419 if changed && let Some(cb) = &on_change {
420 cb(clamped, window, cx);
421 }
422 window.refresh();
423 })
424 };
425
426 let shared_bounds = shared.clone();
428 let shared_move = shared.clone();
429 let shared_up = shared.clone();
430 let select_up = select_slide.clone();
431 let min_x = -(last as f32) * step_px;
432
433 let measurement_canvas = canvas(
434 move |bounds, _, _| {
435 shared_bounds.borrow_mut().viewport_bounds = Some(bounds);
436 bounds
437 },
438 move |bounds, _, window, _cx| {
439 let width = f32::from(bounds.size.width).max(1.0);
440 let shared_m = shared_move.clone();
441 window.on_mouse_event(move |event: &MouseMoveEvent, _, window, _cx| {
442 let mut st = shared_m.borrow_mut();
443 let px_x = f32::from(event.position.x);
444 let px_y = f32::from(event.position.y);
445 let mut became_dragging = false;
446 let mut cancel_drag = false;
447 let banded = {
448 let Some(drag) = st.drag.as_mut() else {
449 return;
450 };
451 if !drag.locked_x {
452 let dx = px_x - drag.start_x;
453 let dy = px_y - drag.start_y;
454 if dx.abs() < CAROUSEL_SLOP_PX && dy.abs() < CAROUSEL_SLOP_PX {
455 return;
456 }
457 if dy.abs() > dx.abs() {
458 cancel_drag = true;
459 0.0
460 } else {
461 drag.locked_x = true;
462 drag.start_x = px_x;
463 became_dragging = true;
464 drag.origin_x
465 }
466 } else {
467 let raw = drag.origin_x + (px_x - drag.start_x);
468 let b = if raw > 0.0 {
469 carousel_rubber(raw, width)
470 } else if raw < min_x {
471 min_x - carousel_rubber(min_x - raw, width)
472 } else {
473 raw
474 };
475 drag.samples.push((Instant::now(), px_x));
476 if drag.samples.len() > 16 {
477 drag.samples.remove(0);
478 }
479 b
480 }
481 };
482 if cancel_drag {
483 st.drag = None;
484 return;
485 }
486 if became_dragging {
487 st.dragging = true;
488 }
489 st.drag_x = banded;
490 window.refresh();
491 });
492
493 let shared_u = shared_up.clone();
494 let select_u = select_up.clone();
495 window.on_mouse_event(move |event: &MouseUpEvent, _, window, cx| {
496 let (was_locked, current_x, velocity, from_idx, click_x) = {
497 let mut st = shared_u.borrow_mut();
498 let Some(drag) = st.drag.clone() else {
499 return;
500 };
501 let vel = st.velocity_px_s(Instant::now());
502 let locked = drag.locked_x;
503 let cur_x = st.drag_x;
504 let from = drag.from_index;
505 st.drag = None;
506 st.dragging = false;
507 st.drain_start = Instant::now();
508 (locked, cur_x, vel, from, f32::from(event.position.x))
509 };
510 if was_locked {
511 let next =
512 carousel_resolve_release(current_x, velocity, from_idx, step_px, last);
513 select_u(next, window, cx);
514 } else {
515 let bounds = shared_u.borrow().viewport_bounds;
516 if let Some(b) = bounds {
517 let center_x = f32::from(b.origin.x) + f32::from(b.size.width) * 0.5;
519 let offset = click_x - center_x;
520 if offset.abs() > slide_w * 0.52 {
521 let next = if offset > 0.0 {
522 (from_idx + 1).min(last)
523 } else {
524 from_idx.saturating_sub(1)
525 };
526 if next != from_idx {
527 select_u(next, window, cx);
528 }
529 }
530 }
531 }
532 });
533 },
534 )
535 .size_full()
536 .absolute()
537 .inset_0();
538
539 let side_pad = ((viewport_w - slide_w) * 0.5).max(0.0);
541 let track_left = side_pad + shown_x;
542
543 let mut slide_nodes = Vec::with_capacity(count);
545 for (i, spec) in self.slides.into_iter().enumerate() {
546 let (scale, opacity) = carousel_slide_emphasis(i, progress);
547 let is_active = i == active_index;
548 let scaled_w = slide_w * scale;
549 let scaled_h = self.slide_height * scale;
550 let left_px = track_left + (i as f32) * step_px + (slide_w - scaled_w) * 0.5;
551 let top_px = (self.slide_height - scaled_h) * 0.5;
552 let content = (spec.render)(is_active, window, cx);
553
554 slide_nodes.push(
555 div()
556 .id(ElementId::Name(
557 format!("arc-carousel-slide-{:?}-{}", self.id, i).into(),
558 ))
559 .role(Role::TabPanel)
560 .aria_label(spec.label)
561 .absolute()
562 .left(px(left_px))
563 .top(px(top_px))
564 .w(px(scaled_w))
565 .h(px(scaled_h))
566 .opacity(opacity)
567 .overflow_hidden()
568 .rounded(Radii::SURFACE)
569 .child(content),
570 );
571 }
572
573 let shared_down = shared.clone();
575 let fh_down = focus_handle.clone();
576 let shared_hover = shared.clone();
577 let interval_for_hover = self.interval_ms;
578 let select_wheel = select_slide.clone();
579 let shared_wheel = shared.clone();
580 let select_key = select_slide.clone();
581 let shared_key = shared.clone();
582
583 let viewport = div()
584 .id(ElementId::Name(
585 format!("arc-carousel-viewport-{:?}", self.id).into(),
586 ))
587 .role(Role::Group)
588 .aria_label("Slides")
589 .track_focus(&focus_handle)
590 .relative()
591 .w_full()
592 .h(px(self.slide_height))
593 .overflow_hidden()
594 .rounded(Radii::PANEL)
595 .cursor_grab()
596 .on_hover(move |hovered, window, _cx| {
597 let mut st = shared_hover.borrow_mut();
598 if st.hovered == *hovered {
599 return;
600 }
601 if let Some(ms) = interval_for_hover {
602 if *hovered && st.playing {
603 let extra = st.drain_start.elapsed().as_secs_f32() * 1000.0 / ms as f32;
604 st.drain_paused_fraction = (st.drain_paused_fraction + extra).min(0.99);
605 } else if !*hovered && st.playing {
606 st.drain_start = Instant::now();
607 }
608 }
609 st.hovered = *hovered;
610 window.refresh();
611 })
612 .on_mouse_down(
613 MouseButton::Left,
614 move |event: &MouseDownEvent, window, cx| {
615 if count < 2 {
616 return;
617 }
618 window.focus(&fh_down, cx);
619 let px_x = f32::from(event.position.x);
620 let px_y = f32::from(event.position.y);
621 let mut st = shared_down.borrow_mut();
622 st.drag_x = shown_x;
623 st.drag = Some(DragSession {
624 start_x: px_x,
625 start_y: px_y,
626 origin_x: shown_x,
627 from_index: active_index,
628 locked_x: false,
629 samples: vec![(Instant::now(), px_x)],
630 });
631 },
632 )
633 .on_scroll(move |event: &ScrollEvent, window, cx| {
634 if count < 2 {
635 return;
636 }
637 let delta_x = match event.delta {
638 ScrollDelta::Pixels(p) => f32::from(p.x),
639 ScrollDelta::Lines(p) => p.x * 24.0,
640 };
641 let delta_y = match event.delta {
642 ScrollDelta::Pixels(p) => f32::from(p.y),
643 ScrollDelta::Lines(p) => p.y * 24.0,
644 };
645 if delta_x.abs() <= delta_y.abs() || delta_x.abs() < 12.0 {
646 return;
647 }
648 let cur = shared_wheel.borrow().index;
649 let next = if delta_x < 0.0 {
650 (cur + 1).min(last)
651 } else {
652 cur.saturating_sub(1)
653 };
654 if next != cur {
655 select_wheel(next, window, cx);
656 }
657 })
658 .on_key_down(move |event: &KeyDownEvent, window, cx| {
659 if count < 2 {
660 return;
661 }
662 let cur = shared_key.borrow().index;
663 let next = match event.keystroke.key.as_str() {
664 "left" => Some(cur.saturating_sub(1)),
665 "right" => Some((cur + 1).min(last)),
666 "home" => Some(0),
667 "end" => Some(last),
668 _ => None,
669 };
670 if let Some(target) = next {
671 select_key(target, window, cx);
672 }
673 })
674 .child(measurement_canvas)
675 .children(slide_nodes);
676
677 let mut root = div()
679 .id(self.id.clone())
680 .role(Role::Region)
681 .aria_label(self.label)
682 .w_full()
683 .flex()
684 .flex_col()
685 .gap(Spacing::S4)
686 .child(viewport);
687
688 if count > 1 {
689 let mut controls = div()
690 .w_full()
691 .px(px(side_pad))
692 .flex()
693 .items_center()
694 .gap(Spacing::S2);
695
696 if can_rotate {
698 let shared_play = shared.clone();
699 let fg_color = theme.colors.foreground;
700 let play_btn = div()
701 .id(ElementId::Name(
702 format!("arc-carousel-play-{:?}", self.id).into(),
703 ))
704 .role(Role::Button)
705 .aria_label(if is_playing {
706 "Pause slide rotation"
707 } else {
708 "Start slide rotation"
709 })
710 .w(px(32.0))
711 .h(px(32.0))
712 .rounded(Radii::PILL)
713 .border_1()
714 .border_color(theme.colors.border)
715 .bg(theme.colors.surface)
716 .hover(|s| s.bg(theme.colors.surface_muted))
717 .cursor_pointer()
718 .flex()
719 .items_center()
720 .justify_center()
721 .on_mouse_down(MouseButton::Left, move |_, window, _| {
722 let mut st = shared_play.borrow_mut();
723 st.playing = !st.playing;
724 st.drain_start = Instant::now();
725 if !st.playing {
726 st.drain_paused_fraction = 0.0;
727 }
728 window.refresh();
729 })
730 .child(
731 canvas(
732 |bounds, _, _| bounds,
733 move |bounds, _, window, _| {
734 let cx =
735 f32::from(bounds.origin.x) + f32::from(bounds.size.width) * 0.5;
736 let cy = f32::from(bounds.origin.y)
737 + f32::from(bounds.size.height) * 0.5;
738 paint_play_pause(cx, cy, is_playing, fg_color, window);
739 },
740 )
741 .w(px(16.0))
742 .h(px(16.0)),
743 );
744 controls = controls.child(play_btn);
745 }
746
747 let mut tabs = div()
749 .id(ElementId::Name(
750 format!("arc-carousel-tabs-{:?}", self.id).into(),
751 ))
752 .role(Role::TabList)
753 .aria_label("Choose a slide")
754 .flex()
755 .items_center()
756 .gap(px(2.0));
757
758 for i in 0..count {
759 let (dot_w, emphasis) = carousel_dot_metrics(i, last, progress);
760 let fill_color = oklab_mix(
761 theme.colors.border_strong,
762 theme.colors.foreground,
763 emphasis,
764 );
765 let select_dot = select_slide.clone();
766 let show_drain =
767 can_rotate && i == active_index && is_playing && drain_fraction > 0.0;
768 let drain_w = (dot_w * drain_fraction).clamp(0.0, dot_w);
769
770 let mut dot_track = div()
771 .relative()
772 .w(px(dot_w))
773 .h(px(CAROUSEL_DOT_PX))
774 .rounded(Radii::PILL)
775 .bg(fill_color)
776 .overflow_hidden();
777
778 if show_drain {
779 dot_track = dot_track.child(
780 div()
781 .absolute()
782 .top_0()
783 .bottom_0()
784 .right_0()
785 .w(px(drain_w))
786 .bg(theme.colors.border_strong),
787 );
788 }
789
790 let tab_btn = div()
791 .id(ElementId::Name(
792 format!("arc-carousel-dot-{:?}-{}", self.id, i).into(),
793 ))
794 .role(Role::Tab)
795 .aria_label(format!("{} of {}", i + 1, count))
796 .h(px(32.0))
797 .px(px(5.0))
798 .rounded(Radii::PILL)
799 .cursor_pointer()
800 .flex()
801 .items_center()
802 .justify_center()
803 .on_mouse_down(MouseButton::Left, move |_, window, cx| {
804 select_dot(i, window, cx);
805 })
806 .child(dot_track);
807 tabs = tabs.child(tab_btn);
808 }
809 controls = controls.child(tabs);
810
811 let at_start = active_index == 0;
813 let at_end = active_index >= last;
814 let select_prev = select_slide.clone();
815 let select_next = select_slide.clone();
816 let prev_icon_color = if at_start {
817 theme.colors.text_muted
818 } else {
819 theme.colors.foreground
820 };
821 let next_icon_color = if at_end {
822 theme.colors.text_muted
823 } else {
824 theme.colors.foreground
825 };
826
827 let prev_btn = div()
828 .id(ElementId::Name(
829 format!("arc-carousel-prev-{:?}", self.id).into(),
830 ))
831 .role(Role::Button)
832 .aria_label("Previous slide")
833 .w(px(32.0))
834 .h(px(32.0))
835 .rounded(Radii::PILL)
836 .border_1()
837 .border_color(theme.colors.border)
838 .bg(theme.colors.surface)
839 .opacity(if at_start { 0.45 } else { 1.0 })
840 .when(!at_start, |el| {
841 el.cursor_pointer()
842 .hover(|s| s.bg(theme.colors.surface_muted))
843 })
844 .flex()
845 .items_center()
846 .justify_center()
847 .on_mouse_down(MouseButton::Left, move |_, window, cx| {
848 if !at_start {
849 select_prev(active_index.saturating_sub(1), window, cx);
850 }
851 })
852 .child(
853 canvas(
854 |bounds, _, _| bounds,
855 move |bounds, _, window, _| {
856 let cx =
857 f32::from(bounds.origin.x) + f32::from(bounds.size.width) * 0.5;
858 let cy =
859 f32::from(bounds.origin.y) + f32::from(bounds.size.height) * 0.5;
860 paint_chevron(cx, cy, false, prev_icon_color, window);
861 },
862 )
863 .w(px(16.0))
864 .h(px(16.0)),
865 );
866
867 let next_btn = div()
868 .id(ElementId::Name(
869 format!("arc-carousel-next-{:?}", self.id).into(),
870 ))
871 .role(Role::Button)
872 .aria_label("Next slide")
873 .w(px(32.0))
874 .h(px(32.0))
875 .rounded(Radii::PILL)
876 .border_1()
877 .border_color(theme.colors.border)
878 .bg(theme.colors.surface)
879 .opacity(if at_end { 0.45 } else { 1.0 })
880 .when(!at_end, |el| {
881 el.cursor_pointer()
882 .hover(|s| s.bg(theme.colors.surface_muted))
883 })
884 .flex()
885 .items_center()
886 .justify_center()
887 .on_mouse_down(MouseButton::Left, move |_, window, cx| {
888 if !at_end {
889 select_next((active_index + 1).min(last), window, cx);
890 }
891 })
892 .child(
893 canvas(
894 |bounds, _, _| bounds,
895 move |bounds, _, window, _| {
896 let cx =
897 f32::from(bounds.origin.x) + f32::from(bounds.size.width) * 0.5;
898 let cy =
899 f32::from(bounds.origin.y) + f32::from(bounds.size.height) * 0.5;
900 paint_chevron(cx, cy, true, next_icon_color, window);
901 },
902 )
903 .w(px(16.0))
904 .h(px(16.0)),
905 );
906
907 let counter_chip = div()
908 .text_size(Typography::TEXT_XS)
909 .text_color(theme.colors.text_muted)
910 .child(format!("{} / {}", active_index + 1, count));
911
912 let arrows = div()
913 .ml_auto()
914 .flex()
915 .items_center()
916 .gap(Spacing::S2)
917 .child(counter_chip)
918 .child(prev_btn)
919 .child(next_btn);
920
921 controls = controls.child(arrows);
922 root = root.child(controls);
923 }
924
925 root
926 }
927}
928
929#[cfg(test)]
930mod tests {
931 use super::*;
932
933 #[test]
934 fn carousel_math_rubber_projection_dots_and_release() {
935 let r1 = carousel_rubber(40.0, 320.0);
937 let r2 = carousel_rubber(120.0, 320.0);
938 assert!(r1 > 0.0 && r1 < 40.0);
939 assert!(r2 > r1 && r2 < 120.0);
940
941 let (s0, o0) = carousel_slide_emphasis(1, 1.0);
943 assert!((s0 - 1.0).abs() < 1e-4 && (o0 - 1.0).abs() < 1e-4);
944 let (s1, o1) = carousel_slide_emphasis(2, 1.0);
945 assert!((s1 - CAROUSEL_NEIGHBOUR_SCALE).abs() < 1e-4);
946 assert!((o1 - CAROUSEL_NEIGHBOUR_DIM).abs() < 1e-4);
947
948 let (w_active, e_active) = carousel_dot_metrics(1, 3, 1.0);
950 assert!((w_active - CAROUSEL_PILL_PX).abs() < 1e-4 && (e_active - 1.0).abs() < 1e-4);
951 let (w_mid, _) = carousel_dot_metrics(1, 3, 1.5);
952 assert!((w_mid - 14.0).abs() < 1e-4);
953
954 let landed = carousel_resolve_release(-20.0, -500.0, 0, 336.0, 3);
956 assert_eq!(landed, 1);
957 }
958}