arc-ui 0.4.0

Physics-first native Rust desktop UI component library & charts for GPUI (120+ interactive components ported from Arc).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
//! Ported from Arc (MIT) © 2026 Elia Kuratli
//! Reference: `Arc源码/arc-library/registry/components/carousel/carousel.tsx` & `.module.css`
//!
//! P6 Component #13: `carousel`
//!
//! - Horizontal row of slides centered in the viewport with peeking neighbours that shrink
//!   (`0.90` at 1 step) and dim (`0.50` at 1 step) continuously with track position.
//! - Supports 1:1 pointer dragging with iOS-style rubber-band resistance past the edges,
//!   momentum projection & flick threshold (`360 px/s`), trackpad horizontal wheel swiping,
//!   clicking peeking neighbour slides, keyboard navigation (`ArrowLeft` / `ArrowRight` /
//!   `Home` / `End`), continuous pill-morphing pagination dots (`6px -> 22px`), and optional
//!   auto-rotation (`interval_ms`) with draining pill progress bar and pause-on-hover/drag.

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,
};

/// Resting dot width (px) and active pill width (px) matching `carousel.tsx`.
pub const CAROUSEL_DOT_PX: f32 = 6.0;
pub const CAROUSEL_PILL_PX: f32 = 22.0;
/// Scale and opacity of a slide one full step away from center.
pub const CAROUSEL_NEIGHBOUR_SCALE: f32 = 0.90;
pub const CAROUSEL_NEIGHBOUR_DIM: f32 = 0.50;
/// Release velocity in px/s that guarantees advancing at least one slide.
pub const CAROUSEL_FLICK_PX_S: f32 = 360.0;
/// Gap between slides (`--space-4`).
const CAROUSEL_GAP_PX: f32 = 16.0;
/// Movement slop before a press becomes a horizontal drag.
const CAROUSEL_SLOP_PX: f32 = 6.0;

/// Rubber-band resistance past a carousel edge (`carousel.tsx`: `rubber`).
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)
}

/// Momentum projection matching `carousel.tsx` (`rate = 0.995`).
pub fn carousel_project(velocity_px_s: f32) -> f32 {
    let rate = 0.995_f32;
    (velocity_px_s / 1000.0) * rate / (1.0 - rate)
}

/// Computes continuous `(scale, opacity)` for a slide at `slide_index` given `progress`.
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)
}

/// Computes continuous indicator dot width and emphasis `[0..1]` for `dot_index`.
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)
}

/// Computes landing slide index after a drag release with momentum and flick detection.
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 {
        // Two pause bars
        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 {
        // Filled play triangle
        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 }
    }
}

/// Arc `Carousel` — centered peeking slide track with momentum drag, pill dots, and autoplay.
#[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,
        }
    }

    /// Appends one slide with an accessible label and render closure `(is_active, window, cx)`.
    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
    }

    /// Controlled active slide index.
    pub fn index(mut self, index: usize) -> Self {
        self.index_override = Some(index);
        self
    }

    /// Initial active slide index when uncontrolled.
    pub fn default_index(mut self, index: usize) -> Self {
        self.default_index = index;
        self
    }

    /// Width of each slide in px (default `320px`, clamped to 80% of viewport if smaller).
    pub fn slide_width(mut self, width: f32) -> Self {
        self.slide_width = width.max(160.0);
        self
    }

    /// Height of the slide viewport in px (default `220px`).
    pub fn slide_height(mut self, height: f32) -> Self {
        self.slide_height = height.max(120.0);
        self
    }

    /// Auto-rotation interval in ms; adds a Play/Pause button and draining indicator pill.
    pub fn interval_ms(mut self, ms: u64) -> Self {
        self.interval_ms = if ms > 0 { Some(ms) } else { None };
        self
    }

    /// Starts rotating automatically on mount (requires `interval_ms`).
    pub fn autoplay(mut self, autoplay: bool) -> Self {
        self.autoplay = autoplay;
        self
    }

    /// Called whenever the active slide changes.
    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;

        // Advance autoplay drain timer when running
        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
        };

        // Track X coordinate: direct pointer position while dragging, smooth spring otherwise
        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();
            })
        };

        // Measure viewport bounds and bind global mouse move/up for smooth drag + flick release
        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 {
                            // Tapping a peeking neighbour slide selects it directly
                            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();

        // Center padding so slide 0 sits centered in viewport
        let side_pad = ((viewport_w - slide_w) * 0.5).max(0.0);
        let track_left = side_pad + shown_x;

        // Build slide elements positioned along the track
        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),
            );
        }

        // Viewport container with drag, hover, wheel, and keyboard handlers
        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);

        // Controls row: optional Play/Pause + pill dots + Prev/Next circular buttons
        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);

            // Play / Pause control when interval_ms is set
            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);
            }

            // Pill-morphing pagination dots
            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);

            // Prev / Next arrow controls
            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() {
        // Rubber band is strictly sublinear and monotonic
        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);

        // Slide emphasis: center is 1.0/1.0, 1 step away is 0.90/0.50
        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);

        // Pill width hand-off between adjacent dots
        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);

        // Fast leftward flick from slide 0 advances to slide 1 even on short drag
        let landed = carousel_resolve_release(-20.0, -500.0, 0, 336.0, 3);
        assert_eq!(landed, 1);
    }
}