Skip to main content

arc_ui/inputs/
elastic_slider.rs

1//! Ported from Arc (MIT) © 2026 Elia Kuratli
2//! Reference: `Arc源码/arc-library/registry/components/elastic-slider/elastic-slider.tsx` & `.module.css`
3//!
4//! P1 Sample Component #3: `elastic-slider`
5//!
6//! - Rubber-band elastic overscroll past min/max (`STRETCH = 26px`, iOS resistance formula via
7//!   `arc_motion::rubber_band_signed`) with track elongation/thinning (`scaled_bounds` anchored
8//!   to opposite edge) and start/end icon push-out.
9//! - Detent snapping (`DETENT_PX = 7px`) with catch-up spring glide and tick pulse.
10//! - Trailing value bubble (`stiffness: 420, damping: 30, mass: 0.7`) with velocity-driven pivot
11//!   sway, `ArcPresence` + `BlurFallback(2px)`, and 700ms post-release linger.
12//! - Full keyboard accessibility (`Role::Slider`, Arrow / Shift+Arrow / PageUp / PageDown /
13//!   Home / End + boundary wall-bump `velocity = ±260px/s`).
14
15use std::{cell::RefCell, rc::Rc};
16
17use arc_motion::{
18    ArcPresence, ArcPresenceConfig, BlurFallback, DragTracker, Transform2D, TransformOrigin,
19    arc_spring, arc_spring_with_options, arc_transition, is_reduced_motion, motion_now,
20    rubber_band_signed, scaled_bounds, spring::SpringOptions,
21};
22use arc_tokens::{
23    ActiveArcTheme as _, ControlHeights, Radii, Shadows, Spacing, SpringSpec, Typography, oklab_mix,
24};
25use gpui_kit::{
26    App, BorderStyle, Bounds, Edges, ElementId, FocusHandle, Hsla, IntoElement, KeyDownEvent,
27    MouseButton, MouseMoveEvent, MouseUpEvent, Orientation, ParentElement, Pixels, RenderOnce,
28    Role, SharedString, Styled, TestSupportExt as _, Window, assets::IconName, bounds, canvas, div,
29    point, prelude::*, px, quad, size,
30};
31
32const THUMB_SIZE: f32 = 18.0;
33const TRACK_HEIGHT: f32 = 6.0;
34const STRETCH: f32 = 22.0;
35const DETENT_PX: f32 = 7.0;
36const BUMP_PX: f32 = 260.0;
37const LINGER_SECS: f64 = 0.7;
38
39type ValueHandler = Rc<dyn Fn(&f32, &mut Window, &mut App)>;
40type Formatter = Rc<dyn Fn(f32) -> SharedString>;
41
42/// Detent mark along an [`ElasticSlider`].
43#[derive(Clone, Debug, PartialEq)]
44pub struct ElasticSliderMark {
45    pub value: f32,
46    pub label: Option<SharedString>,
47}
48
49impl ElasticSliderMark {
50    pub fn new(value: f32) -> Self {
51        Self { value, label: None }
52    }
53
54    pub fn labelled(value: f32, label: impl Into<SharedString>) -> Self {
55        Self {
56            value,
57            label: Some(label.into()),
58        }
59    }
60}
61
62#[derive(Clone)]
63struct ElasticSliderState {
64    uncontrolled_value: f32,
65    dragging: bool,
66    keyed: bool,
67    linger_until_secs: f64,
68    drag_raw_pct: f32,
69    drag_over_px: f32,
70    grab_offset_pct: f32,
71    active_detent: Option<f32>,
72    tracker: DragTracker,
73    /// One-shot velocity impulse injected into `pos` or `over` spring on release/bump.
74    pos_impulse: Option<f32>,
75    over_impulse: Option<f32>,
76    /// Last tick value pulsed and start time.
77    pulsed_mark: Option<(f32, f64)>,
78    rail_bounds: Rc<RefCell<Option<Bounds<Pixels>>>>,
79    focus_handle: FocusHandle,
80}
81
82impl ElasticSliderState {
83    fn new(initial: f32, focus_handle: FocusHandle) -> Self {
84        Self {
85            uncontrolled_value: initial,
86            dragging: false,
87            keyed: false,
88            linger_until_secs: f64::NEG_INFINITY,
89            drag_raw_pct: 0.0,
90            drag_over_px: 0.0,
91            grab_offset_pct: 0.0,
92            active_detent: None,
93            tracker: DragTracker::new(0.0),
94            pos_impulse: None,
95            over_impulse: None,
96            pulsed_mark: None,
97            rail_bounds: Rc::new(RefCell::new(None)),
98            focus_handle,
99        }
100    }
101}
102
103fn decimal_places(step: f32) -> usize {
104    let s = format!("{step}");
105    s.split('.')
106        .nth(1)
107        .map_or(0, |frac| frac.trim_end_matches('0').len())
108}
109
110fn snap_value(input: f32, min: f32, max: f32, step: f32) -> f32 {
111    let step = if step > 0.0 { step } else { 1.0 };
112    let decimals = decimal_places(step).max(decimal_places(min));
113    let factor = 10.0_f32.powi(decimals as i32);
114    let snapped = min + ((input - min) / step).round() * step;
115    ((snapped * factor).round() / factor).clamp(min, max)
116}
117
118fn pct_of(value: f32, min: f32, span: f32) -> f32 {
119    (((value - min) / span) * 100.0).clamp(0.0, 100.0)
120}
121
122fn detent_at(
123    percent: f32,
124    min: f32,
125    span: f32,
126    width: f32,
127    marks: &[ElasticSliderMark],
128) -> Option<f32> {
129    let mut best = None;
130    let mut best_gap = DETENT_PX + 1.0;
131    for mark in marks {
132        let mark_pct = pct_of(mark.value, min, span);
133        let dist = ((percent - mark_pct) / 100.0 * width).abs();
134        if dist <= DETENT_PX && dist < best_gap {
135            best = Some(mark.value);
136            best_gap = dist;
137        }
138    }
139    best
140}
141
142/// Arc `ElasticSlider` component with elastic overscroll, detents, velocity-swaying value bubble,
143/// and full keyboard navigation.
144#[derive(IntoElement)]
145pub struct ElasticSlider {
146    id: ElementId,
147    label: SharedString,
148    value: Option<f32>,
149    default_value: Option<f32>,
150    min: f32,
151    max: f32,
152    step: f32,
153    large_step: Option<f32>,
154    marks: Vec<ElasticSliderMark>,
155    format: Option<Formatter>,
156    show_value: bool,
157    start_icon: Option<IconName>,
158    end_icon: Option<IconName>,
159    disabled: bool,
160    on_value_change: Option<ValueHandler>,
161    on_value_commit: Option<ValueHandler>,
162}
163
164impl ElasticSlider {
165    pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
166        Self {
167            id: id.into(),
168            label: label.into(),
169            value: None,
170            default_value: None,
171            min: 0.0,
172            max: 100.0,
173            step: 1.0,
174            large_step: None,
175            marks: Vec::new(),
176            format: None,
177            show_value: true,
178            start_icon: None,
179            end_icon: None,
180            disabled: false,
181            on_value_change: None,
182            on_value_commit: None,
183        }
184    }
185
186    pub fn value(mut self, value: f32) -> Self {
187        self.value = Some(value);
188        self
189    }
190
191    pub fn default_value(mut self, default_value: f32) -> Self {
192        self.default_value = Some(default_value);
193        self
194    }
195
196    pub fn min(mut self, min: f32) -> Self {
197        self.min = min;
198        self
199    }
200
201    pub fn max(mut self, max: f32) -> Self {
202        self.max = max;
203        self
204    }
205
206    pub fn step(mut self, step: f32) -> Self {
207        self.step = if step > 0.0 { step } else { 1.0 };
208        self
209    }
210
211    pub fn large_step(mut self, large_step: f32) -> Self {
212        self.large_step = Some(large_step);
213        self
214    }
215
216    pub fn marks(mut self, marks: impl IntoIterator<Item = ElasticSliderMark>) -> Self {
217        self.marks = marks.into_iter().collect();
218        self
219    }
220
221    pub fn format(mut self, formatter: impl Fn(f32) -> SharedString + 'static) -> Self {
222        self.format = Some(Rc::new(formatter));
223        self
224    }
225
226    pub fn show_value(mut self, show_value: bool) -> Self {
227        self.show_value = show_value;
228        self
229    }
230
231    pub fn start_icon(mut self, icon: IconName) -> Self {
232        self.start_icon = Some(icon);
233        self
234    }
235
236    pub fn end_icon(mut self, icon: IconName) -> Self {
237        self.end_icon = Some(icon);
238        self
239    }
240
241    pub fn disabled(mut self, disabled: bool) -> Self {
242        self.disabled = disabled;
243        self
244    }
245
246    pub fn on_value_change(
247        mut self,
248        handler: impl Fn(&f32, &mut Window, &mut App) + 'static,
249    ) -> Self {
250        self.on_value_change = Some(Rc::new(handler));
251        self
252    }
253
254    pub fn on_value_commit(
255        mut self,
256        handler: impl Fn(&f32, &mut Window, &mut App) + 'static,
257    ) -> Self {
258        self.on_value_commit = Some(Rc::new(handler));
259        self
260    }
261}
262
263impl RenderOnce for ElasticSlider {
264    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
265        let theme = cx.arc_theme().clone();
266        let colors = theme.colors;
267        let motion = theme.motion;
268        let reduced = is_reduced_motion(cx);
269        let now = motion_now(cx);
270
271        let min = self.min;
272        let max = self.max;
273        let step = if self.step > 0.0 { self.step } else { 1.0 };
274        let span = if (max - min).abs() > f32::EPSILON {
275            max - min
276        } else {
277            1.0
278        };
279        let decimals = decimal_places(step).max(decimal_places(min));
280        let initial = self.default_value.unwrap_or(min).clamp(min, max);
281        let valid_marks: Vec<ElasticSliderMark> = self
282            .marks
283            .into_iter()
284            .filter(|m| m.value >= min && m.value <= max)
285            .collect();
286
287        let state_id =
288            ElementId::NamedChild(self.id.clone().into(), "__arc-elastic-slider-state".into());
289        let state = window.use_keyed_state(state_id, cx, |_, cx| {
290            ElasticSliderState::new(initial, cx.focus_handle())
291        });
292
293        let snapshot = state.read(cx).clone();
294        let current = self
295            .value
296            .unwrap_or(snapshot.uncontrolled_value)
297            .clamp(min, max);
298        let is_controlled = self.value.is_some();
299
300        // Physical springs matching `elastic-slider.tsx` lines 44-47.
301        let thumb_spring = motion.spring.snappy.as_physical();
302        let snap_back_spring = SpringSpec::visual(0.5, 0.42).as_physical();
303        let bubble_trail_spring = SpringSpec::physics_with_mass(420.0, 30.0, 0.7);
304
305        let rail_width = snapshot
306            .rail_bounds
307            .borrow()
308            .map_or(240.0_f32, |b| f32::from(b.size.width).max(1.0));
309
310        // Target thumb percentage (0..100) and overscroll (px).
311        let target_pct = if snapshot.dragging {
312            snapshot.drag_raw_pct
313        } else {
314            pct_of(current, min, span)
315        };
316        let target_over = if snapshot.dragging && !reduced {
317            snapshot.drag_over_px
318        } else {
319            0.0
320        };
321
322        // Consume one-shot velocity impulses if queued.
323        let pos_impulse = snapshot.pos_impulse;
324        let over_impulse = snapshot.over_impulse;
325        if pos_impulse.is_some() || over_impulse.is_some() {
326            state.update(cx, |s, _| {
327                s.pos_impulse = None;
328                s.over_impulse = None;
329            });
330        }
331
332        let mut pos_opts = SpringOptions::new(thumb_spring)
333            .with_travel(!snapshot.dragging || snapshot.active_detent.is_some())
334            .with_rest_thresholds(0.002, 0.02);
335        if let Some(v) = pos_impulse {
336            pos_opts = pos_opts.with_initial_velocity(v);
337        }
338        let pos_sample =
339            arc_spring_with_options((self.id.clone(), "pos"), target_pct, pos_opts, window, cx);
340        let shown_pct = pos_sample.value.clamp(0.0, 100.0);
341
342        let mut over_opts = SpringOptions::new(snap_back_spring)
343            .with_travel(!snapshot.dragging)
344            .with_rest_thresholds(0.05, 0.5);
345        if let Some(v) = over_impulse {
346            over_opts = over_opts.with_initial_velocity(v);
347        }
348        let over_sample = arc_spring_with_options(
349            (self.id.clone(), "over"),
350            target_over,
351            over_opts,
352            window,
353            cx,
354        );
355        let over_px = if reduced { 0.0 } else { over_sample.value };
356
357        let press = arc_spring(
358            (self.id.clone(), "press"),
359            if snapshot.dragging { 1.0 } else { 0.0 },
360            motion.spring.snappy,
361            window,
362            cx,
363        );
364        let thumb_scale = arc_spring(
365            (self.id.clone(), "thumb-scale"),
366            if snapshot.dragging && !reduced {
367                1.28
368            } else {
369                1.0
370            },
371            motion.spring.snappy,
372            window,
373            cx,
374        );
375
376        let trail_sample = arc_spring_with_options(
377            (self.id.clone(), "bubble-trail"),
378            shown_pct,
379            SpringOptions::new(bubble_trail_spring).with_travel(!reduced),
380            window,
381            cx,
382        );
383        let bubble_at_pct = if reduced {
384            shown_pct
385        } else {
386            trail_sample.value.clamp(0.0, 100.0)
387        };
388        let bubble_rotate_deg = if reduced {
389            0.0
390        } else {
391            ((-trail_sample.velocity / 100.0) * rail_width * 0.009).clamp(-11.0, 11.0)
392        };
393        // Pivot swing offset fallback for mixed text bubble (P0-DECISIONS.md §2).
394        let bubble_swing = Transform2D::IDENTITY
395            .rotate_deg(bubble_rotate_deg)
396            .origin(TransformOrigin::new(0.5, 1.3))
397            .pivot_swing_offset(px(28.0));
398
399        let linger_active = now < snapshot.linger_until_secs;
400        if linger_active {
401            window.request_animation_frame();
402        }
403        let bubble_visible = snapshot.dragging || snapshot.keyed || linger_active;
404        let bubble_presence =
405            ArcPresence::new((self.id.clone(), "bubble-presence"), bubble_visible)
406                .animate_initial(false)
407                .config(ArcPresenceConfig {
408                    enter_duration: motion.duration.fast,
409                    enter_ease: motion.ease.enter,
410                    exit_duration: motion.duration.instant,
411                    exit_ease: motion.ease.standard,
412                    fade_on_reduced_motion: true,
413                })
414                .sample(window, cx);
415        let bubble_blur = BlurFallback::evaluate(
416            px((1.0 - bubble_presence.progress) * f32::from(motion.blur.subtle)),
417            reduced,
418        );
419        let readout_opacity = arc_transition(
420            (self.id.clone(), "readout-opacity"),
421            if bubble_visible { 0.0 } else { 1.0 },
422            motion.duration.fast,
423            motion.ease.standard,
424            window,
425            cx,
426        );
427
428        // Derived track stretch (`scaleX`, `scaleY`, `originX`) & icon shift.
429        let scale_x = 1.0 + over_px.abs() / rail_width;
430        let scale_y = (1.0 + press * 0.45) * (1.0 - (over_px.abs() / STRETCH) * 0.32);
431        let track_origin = if over_px < 0.0 {
432            TransformOrigin::RIGHT_CENTER
433        } else {
434            TransformOrigin::LEFT_CENTER
435        };
436        let start_shift = over_px.min(0.0);
437        let end_shift = over_px.max(0.0);
438
439        let formatted: SharedString = if let Some(fmt) = &self.format {
440            fmt(current)
441        } else {
442            SharedString::from(format!("{current:.decimals$}"))
443        };
444
445        // Shared event closures
446        let disabled = self.disabled;
447        let marks_rc = Rc::new(valid_marks.clone());
448        let on_change_rc = self.on_value_change.clone();
449        let on_commit_rc = self.on_value_commit.clone();
450
451        let state_down = state.clone();
452        let marks_down = marks_rc.clone();
453        let on_change_down = on_change_rc.clone();
454        let focus_down = snapshot.focus_handle.clone();
455
456        let state_move = state.clone();
457        let marks_move = marks_rc.clone();
458        let on_change_move = on_change_rc.clone();
459
460        let state_up = state.clone();
461        let on_change_up = on_change_rc.clone();
462        let on_commit_up = on_commit_rc.clone();
463
464        let state_key = state.clone();
465        let marks_key = marks_rc.clone();
466        let on_change_key = on_change_rc.clone();
467        let on_commit_key = on_commit_rc.clone();
468        let large_step = self
469            .large_step
470            .unwrap_or_else(|| step.max(snap_value(min + span / 10.0, min, max, step) - min));
471
472        // Paint elastic track + clipped fill + ticks in a single `canvas()` for exact stretch geometry.
473        let rail_bounds_ref = snapshot.rail_bounds.clone();
474        let track_color = colors.control_track;
475        let fill_color = colors.control_fill;
476        let tick_off_color = oklab_mix(colors.foreground, Hsla::transparent_black(), 0.32);
477        let tick_on_color = oklab_mix(colors.control_glyph, Hsla::transparent_black(), 0.60);
478        let inner_marks: Vec<f32> = valid_marks
479            .iter()
480            .filter(|m| m.value > min && m.value < max)
481            .map(|m| m.value)
482            .collect();
483        let pulsed_mark = snapshot.pulsed_mark;
484
485        let is_dragging = snapshot.dragging;
486        let track_canvas = canvas(
487            move |rect, _, _| {
488                *rail_bounds_ref.borrow_mut() = Some(rect);
489            },
490            move |rect, _, window, _| {
491                // Window-level pointer capture while dragging so overscroll past track edges
492                // tracks smoothly and always commits on release anywhere in the window.
493                if is_dragging && !disabled {
494                    let st_move = state_move.clone();
495                    let mk_move = marks_move.clone();
496                    let ch_move = on_change_move.clone();
497                    window.on_mouse_event(move |event: &MouseMoveEvent, phase, window, cx| {
498                        if !phase.bubble() || !st_move.read(cx).dragging {
499                            return;
500                        }
501                        let Some(rail_rect) = *st_move.read(cx).rail_bounds.borrow() else {
502                            return;
503                        };
504                        let w = f32::from(rail_rect.size.width).max(1.0);
505                        let now_move = motion_now(cx);
506                        let at_pct =
507                            ((f32::from(event.position.x) - f32::from(rail_rect.origin.x)) / w)
508                                * 100.0;
509                        let prev_detent = st_move.read(cx).active_detent;
510                        let prev_val = if is_controlled {
511                            current
512                        } else {
513                            st_move.read(cx).uncontrolled_value
514                        };
515                        let grab = st_move.read(cx).grab_offset_pct;
516                        let raw = at_pct - grab;
517                        let edge = raw.clamp(0.0, 100.0);
518                        let over = if is_reduced_motion(cx) {
519                            0.0
520                        } else {
521                            rubber_band_signed((raw - edge) / 100.0 * w, STRETCH)
522                        };
523                        let detent = detent_at(edge, min, span, w, &mk_move);
524                        let placed = detent.map_or(edge, |d| pct_of(d, min, span));
525                        let next_val = detent.unwrap_or_else(|| {
526                            snap_value(min + (edge / 100.0) * span, min, max, step)
527                        });
528
529                        st_move.update(cx, |s, _| {
530                            s.drag_raw_pct = placed;
531                            s.drag_over_px = over;
532                            if detent != prev_detent
533                                && let Some(d) = detent
534                            {
535                                s.pulsed_mark = Some((d, now_move));
536                            }
537                            s.active_detent = detent;
538                            s.tracker.update_x(placed, 0.0, now_move, false);
539                            if !is_controlled {
540                                s.uncontrolled_value = next_val;
541                            }
542                        });
543                        if (next_val - prev_val).abs() > f32::EPSILON
544                            && let Some(handler) = &ch_move
545                        {
546                            handler(&next_val, window, cx);
547                        }
548                        window.refresh();
549                    });
550
551                    let st_up = state_up.clone();
552                    let ch_up = on_change_up.clone();
553                    let cm_up = on_commit_up.clone();
554                    window.on_mouse_event(move |event: &MouseUpEvent, phase, window, cx| {
555                        if !phase.bubble()
556                            || event.button != MouseButton::Left
557                            || !st_up.read(cx).dragging
558                        {
559                            return;
560                        }
561                        let now_up = motion_now(cx);
562                        let (next_val, vel) = {
563                            let s = st_up.read(cx);
564                            let v = s.tracker.release_velocity(now_up);
565                            let next = s.active_detent.unwrap_or_else(|| {
566                                snap_value(min + (s.drag_raw_pct / 100.0) * span, min, max, step)
567                            });
568                            (next, v)
569                        };
570                        st_up.update(cx, |s, _| {
571                            s.dragging = false;
572                            s.linger_until_secs = now_up + LINGER_SECS;
573                            s.pos_impulse = Some(vel);
574                            s.drag_over_px = 0.0;
575                            if !is_controlled {
576                                s.uncontrolled_value = next_val;
577                            }
578                        });
579                        if let Some(handler) = &ch_up {
580                            handler(&next_val, window, cx);
581                        }
582                        if let Some(handler) = &cm_up {
583                            handler(&next_val, window, cx);
584                        }
585                        window.refresh();
586                    });
587                }
588
589                let stretched = scaled_bounds(rect, scale_x, scale_y, track_origin);
590                window.paint_quad(quad(
591                    stretched,
592                    Radii::pill_for_size(stretched.size),
593                    track_color,
594                    Edges::default(),
595                    Hsla::transparent_black(),
596                    BorderStyle::Solid,
597                ));
598
599                // Fill clipped to `shown_pct` of stretched track width
600                let fill_w = (f32::from(stretched.size.width) * (shown_pct / 100.0)).max(0.0);
601                if fill_w > 0.5 {
602                    let fill_rect =
603                        bounds(stretched.origin, size(px(fill_w), stretched.size.height));
604                    window.paint_quad(quad(
605                        fill_rect,
606                        Radii::pill_for_size(fill_rect.size),
607                        fill_color,
608                        Edges::default(),
609                        Hsla::transparent_black(),
610                        BorderStyle::Solid,
611                    ));
612                }
613
614                // Detent ticks ride on the unstretched rail
615                let rail_w = f32::from(rect.size.width);
616                let mid_y = f32::from(rect.origin.y) + f32::from(rect.size.height) * 0.5;
617                for &m_val in &inner_marks {
618                    let m_pct = pct_of(m_val, min, span);
619                    let mut tick_scale = 1.0_f32;
620                    if let Some((pm, started)) = pulsed_mark
621                        && !reduced
622                        && (pm - m_val).abs() < 1e-4
623                    {
624                        let dt = (now - started).max(0.0);
625                        if dt < 0.34 {
626                            let u = (dt / 0.34) as f32;
627                            tick_scale = 1.0 + 1.1 * (u * std::f32::consts::PI).sin();
628                            window.request_animation_frame();
629                        }
630                    }
631                    let d = 4.0 * tick_scale;
632                    let cx_pos = f32::from(rect.origin.x) + rail_w * (m_pct / 100.0);
633                    let tick_rect = bounds(
634                        point(px(cx_pos - d * 0.5), px(mid_y - d * 0.5)),
635                        size(px(d), px(d)),
636                    );
637                    let col = if m_val <= current {
638                        tick_on_color
639                    } else {
640                        tick_off_color
641                    };
642                    window.paint_quad(quad(
643                        tick_rect,
644                        Radii::pill_for_size(tick_rect.size),
645                        col,
646                        Edges::default(),
647                        Hsla::transparent_black(),
648                        BorderStyle::Solid,
649                    ));
650                }
651            },
652        )
653        .w_full()
654        .h(px(TRACK_HEIGHT));
655
656        let thumb_px_size = THUMB_SIZE * thumb_scale;
657        let thumb_center_x = (THUMB_SIZE * 0.5) + rail_width * (shown_pct / 100.0) + over_px;
658        let bubble_min_x = 24.0_f32.min((rail_width + THUMB_SIZE) * 0.5);
659        let bubble_max_x = (rail_width + THUMB_SIZE - 24.0).max(bubble_min_x);
660        let bubble_center_x = ((THUMB_SIZE * 0.5) + rail_width * (bubble_at_pct / 100.0) + over_px)
661            .clamp(bubble_min_x, bubble_max_x)
662            + f32::from(bubble_swing.x);
663        let bubble_y_offset =
664            (1.0 - bubble_presence.progress) * 6.0 + f32::from(bubble_blur.offset_y);
665        let bubble_opacity =
666            (bubble_presence.progress * bubble_blur.opacity_multiplier).clamp(0.0, 1.0);
667
668        let labelled_marks: Vec<ElasticSliderMark> = valid_marks
669            .iter()
670            .filter(|m| m.label.is_some())
671            .cloned()
672            .collect();
673
674        let thumb_id = ElementId::NamedChild(self.id.clone().into(), "thumb".into());
675        let control_id = ElementId::NamedChild(self.id.clone().into(), "control".into());
676        let focus_handle = snapshot.focus_handle.clone();
677        let is_focused = focus_handle.is_focused(window);
678        let focus_outline = colors.focus_outline;
679
680        let control_row = div()
681            .id(control_id)
682            .test_support()
683            .relative()
684            .flex_1()
685            .h(ControlHeights::MD)
686            .flex()
687            .items_center()
688            .when(!disabled, |this| {
689                this.cursor(if snapshot.dragging {
690                    gpui_kit::CursorStyle::ClosedHand
691                } else {
692                    gpui_kit::CursorStyle::PointingHand
693                })
694            })
695            .on_mouse_down(MouseButton::Left, move |event, window, cx| {
696                if disabled {
697                    return;
698                }
699                let Some(rect) = *state_down.read(cx).rail_bounds.borrow() else {
700                    return;
701                };
702                let w = f32::from(rect.size.width).max(1.0);
703                let at_pct = ((f32::from(event.position.x) - f32::from(rect.origin.x)) / w) * 100.0;
704                let now_down = motion_now(cx);
705                let current_val = if is_controlled {
706                    current
707                } else {
708                    state_down.read(cx).uncontrolled_value
709                };
710                let from_pct = pct_of(current_val, min, span);
711                let grabbed_thumb = ((at_pct - from_pct) / 100.0 * w).abs() <= THUMB_SIZE * 0.75;
712                let grab = if grabbed_thumb {
713                    at_pct - from_pct
714                } else {
715                    0.0
716                };
717                let raw = at_pct - grab;
718                let edge = raw.clamp(0.0, 100.0);
719                let over = if is_reduced_motion(cx) {
720                    0.0
721                } else {
722                    rubber_band_signed((raw - edge) / 100.0 * w, STRETCH)
723                };
724                let detent = detent_at(edge, min, span, w, &marks_down);
725                let placed = detent.map_or(edge, |d| pct_of(d, min, span));
726                let next_val = detent
727                    .unwrap_or_else(|| snap_value(min + (edge / 100.0) * span, min, max, step));
728
729                state_down.update(cx, |s, _| {
730                    s.dragging = true;
731                    s.keyed = false;
732                    s.linger_until_secs = f64::NEG_INFINITY;
733                    s.grab_offset_pct = grab;
734                    s.drag_raw_pct = placed;
735                    s.drag_over_px = over;
736                    s.active_detent = detent;
737                    s.tracker.begin(placed, 0.0, placed, now_down);
738                    if !is_controlled {
739                        s.uncontrolled_value = next_val;
740                    }
741                });
742                window.focus(&focus_down, cx);
743                if (next_val - current_val).abs() > f32::EPSILON
744                    && let Some(handler) = &on_change_down
745                {
746                    handler(&next_val, window, cx);
747                }
748                window.refresh();
749            })
750            // Rail inset by half a thumb
751            .child(
752                div()
753                    .w_full()
754                    .px(px(THUMB_SIZE * 0.5))
755                    .flex()
756                    .items_center()
757                    .child(track_canvas),
758            )
759            // Floating value bubble above thumb
760            .when(bubble_presence.should_render(), |this| {
761                this.child(
762                    div()
763                        .absolute()
764                        .left(px(bubble_center_x - 24.0))
765                        .bottom(px(ControlHeights::MD.as_f32() * 0.5
766                            + THUMB_SIZE * 0.5
767                            + 10.0
768                            - bubble_y_offset))
769                        .min_w(px(48.0))
770                        .h(px(28.0))
771                        .px(Spacing::S3)
772                        .flex()
773                        .items_center()
774                        .justify_center()
775                        .rounded(Radii::PILL)
776                        .bg(colors.foreground)
777                        .text_color(colors.background)
778                        .text_size(Typography::TEXT_SM)
779                        .shadow(Shadows::raised(theme.mode))
780                        .opacity(bubble_opacity)
781                        .child(formatted.clone()),
782                )
783            })
784            // Interactive focusable ARIA Slider thumb
785            .child(
786                div()
787                    .id(thumb_id)
788                    .test_support()
789                    .track_focus(&focus_handle.tab_stop(!disabled))
790                    .role(Role::Slider)
791                    .aria_label(self.label.clone())
792                    .aria_min_numeric_value(f64::from(min))
793                    .aria_max_numeric_value(f64::from(max))
794                    .aria_numeric_value(f64::from(current))
795                    .aria_numeric_value_step(f64::from(step))
796                    .aria_value(formatted.clone())
797                    .aria_orientation(Orientation::Horizontal)
798                    .absolute()
799                    .left(px(thumb_center_x - thumb_px_size * 0.5))
800                    .top(px((ControlHeights::MD.as_f32() - thumb_px_size) * 0.5))
801                    .w(px(thumb_px_size))
802                    .h(px(thumb_px_size))
803                    .rounded(Radii::PILL)
804                    .bg(colors.control_thumb)
805                    .when(is_focused, |this| {
806                        this.border_2().border_color(focus_outline)
807                    })
808                    .shadow(Shadows::control_thumb(theme.mode))
809                    .on_key_down(move |event: &KeyDownEvent, window, cx| {
810                        if disabled {
811                            return;
812                        }
813                        let now_val = if is_controlled {
814                            current
815                        } else {
816                            state_key.read(cx).uncontrolled_value
817                        };
818                        let shift = event.keystroke.modifiers.shift;
819                        let wanted = match event.keystroke.key.as_str() {
820                            "right" | "up" => now_val + if shift { large_step } else { step },
821                            "left" | "down" => now_val - if shift { large_step } else { step },
822                            "pageup" => now_val + large_step,
823                            "pagedown" => now_val - large_step,
824                            "home" => min,
825                            "end" => max,
826                            _ => return,
827                        };
828                        let now_k = motion_now(cx);
829                        let next = snap_value(wanted, min, max, step);
830                        if (next - now_val).abs() <= f32::EPSILON {
831                            let toward = (wanted - now_val).signum();
832                            if toward != 0.0 && !is_reduced_motion(cx) {
833                                state_key.update(cx, |s, _| {
834                                    s.keyed = true;
835                                    s.linger_until_secs = now_k + LINGER_SECS;
836                                    s.over_impulse = Some(toward * BUMP_PX);
837                                });
838                                window.refresh();
839                            }
840                            return;
841                        }
842                        state_key.update(cx, |s, _| {
843                            s.keyed = true;
844                            s.linger_until_secs = now_k + LINGER_SECS;
845                            if !is_controlled {
846                                s.uncontrolled_value = next;
847                            }
848                            if marks_key.iter().any(|m| (m.value - next).abs() < 1e-4) {
849                                s.pulsed_mark = Some((next, now_k));
850                            }
851                        });
852                        if let Some(handler) = &on_change_key {
853                            handler(&next, window, cx);
854                        }
855                        if let Some(handler) = &on_commit_key {
856                            handler(&next, window, cx);
857                        }
858                        window.refresh();
859                    }),
860            );
861
862        let mut root = div()
863            .id(self.id.clone())
864            .w_full()
865            .flex()
866            .flex_col()
867            .gap(Spacing::S2)
868            .text_size(Typography::TEXT_SM)
869            .text_color(colors.foreground)
870            .when(disabled, |this| this.opacity(0.5))
871            // Header row: label + fading readout
872            .child(
873                div()
874                    .w_full()
875                    .flex()
876                    .items_baseline()
877                    .justify_between()
878                    .gap(Spacing::S4)
879                    .child(self.label.clone())
880                    .when(self.show_value, |this| {
881                        this.child(
882                            div()
883                                .text_color(colors.text_secondary)
884                                .opacity(readout_opacity)
885                                .child(formatted),
886                        )
887                    }),
888            )
889            // Body row: optional start icon + elastic control + optional end icon
890            .child(
891                div()
892                    .w_full()
893                    .flex()
894                    .flex_row()
895                    .items_center()
896                    .when_some(self.start_icon, |this, icon| {
897                        this.child(
898                            div()
899                                .mr(Spacing::S3)
900                                .ml(px(start_shift))
901                                .text_color(colors.text_muted)
902                                .child(icon),
903                        )
904                    })
905                    .child(control_row)
906                    .when_some(self.end_icon, |this, icon| {
907                        this.child(
908                            div()
909                                .ml(px(f32::from(Spacing::S3) + end_shift))
910                                .text_color(colors.text_muted)
911                                .child(icon),
912                        )
913                    }),
914            );
915
916        // Optional clickable detent mark labels beneath the rail
917        if !labelled_marks.is_empty() {
918            let mut marks_row = div()
919                .relative()
920                .w_full()
921                .h(px(20.0))
922                .px(px(THUMB_SIZE * 0.5))
923                .text_size(Typography::TEXT_XS)
924                .text_color(colors.text_muted);
925
926            for (idx, mark) in labelled_marks.into_iter().enumerate() {
927                let m_val = mark.value;
928                let m_label = mark.label.unwrap_or_default();
929                let is_on = (m_val - current).abs() < 1e-4;
930                let m_pct = pct_of(m_val, min, span);
931                let left_px = (THUMB_SIZE * 0.5) + rail_width * (m_pct / 100.0);
932
933                let st_click = state.clone();
934                let ch_click = self.on_value_change.clone();
935                let cm_click = self.on_value_commit.clone();
936                let mark_id = ElementId::NamedChild(
937                    self.id.clone().into(),
938                    SharedString::from(format!("mark-{idx}")),
939                );
940
941                marks_row = marks_row.child(
942                    div()
943                        .id(mark_id)
944                        .test_support()
945                        .absolute()
946                        .top_0()
947                        .left(px((left_px - 16.0).clamp(0.0, rail_width)))
948                        .text_color(if is_on {
949                            colors.foreground
950                        } else {
951                            colors.text_muted
952                        })
953                        .when(!disabled, |this| this.cursor_pointer())
954                        .on_click(move |_, window, cx| {
955                            if disabled {
956                                return;
957                            }
958                            let now_m = motion_now(cx);
959                            st_click.update(cx, |s, _| {
960                                if !is_controlled {
961                                    s.uncontrolled_value = m_val;
962                                }
963                                s.pulsed_mark = Some((m_val, now_m));
964                            });
965                            if let Some(handler) = &ch_click {
966                                handler(&m_val, window, cx);
967                            }
968                            if let Some(handler) = &cm_click {
969                                handler(&m_val, window, cx);
970                            }
971                            window.refresh();
972                        })
973                        .child(m_label),
974                );
975            }
976            root = root.child(marks_row);
977        }
978
979        root
980    }
981}
982
983#[cfg(test)]
984mod tests {
985    use std::{cell::Cell, rc::Rc};
986
987    use arc_motion::{CurveTrace, SpringSolver, max_curve_error_pct, rubber_band_signed};
988    use arc_tokens::{Accent, ThemeMode, install_arc_theme};
989    use gpui_kit::{
990        Context, MouseButton, Render, Role, TestAppContext, div, point, px,
991        test::{TestEventExt as _, TestQueryExt as _, TestWindowExt as _},
992    };
993
994    use super::*;
995
996    struct SliderHost {
997        value: f32,
998        commits: Rc<Cell<usize>>,
999    }
1000
1001    impl Render for SliderHost {
1002        fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1003            let commits = self.commits.clone();
1004            div().w(px(360.0)).p(Spacing::S6).child(
1005                ElasticSlider::new("volume", "Volume")
1006                    .value(self.value)
1007                    .min(0.0)
1008                    .max(100.0)
1009                    .step(5.0)
1010                    .marks([
1011                        ElasticSliderMark::labelled(0.0, "0%"),
1012                        ElasticSliderMark::labelled(50.0, "50%"),
1013                        ElasticSliderMark::labelled(100.0, "100%"),
1014                    ])
1015                    .on_value_change(cx.listener(|this, v: &f32, _, cx| {
1016                        this.value = *v;
1017                        cx.notify();
1018                    }))
1019                    .on_value_commit(cx.listener(move |_, _: &f32, _, _| {
1020                        commits.set(commits.get() + 1);
1021                    })),
1022            )
1023        }
1024    }
1025
1026    #[gpui_kit::test]
1027    fn elastic_slider_drag_keyboard_and_commit_work(cx: &mut TestAppContext) {
1028        cx.update(|cx| {
1029            gpui_kit::init(cx);
1030            install_arc_theme(ThemeMode::Light, Accent::Blue, cx);
1031        });
1032        let commits = Rc::new(Cell::new(0usize));
1033        let (view, cx) = cx.add_window_view(|_, _| SliderHost {
1034            value: 20.0,
1035            commits: commits.clone(),
1036        });
1037
1038        cx.update(|window, cx| {
1039            window.render_frame(cx);
1040            let slider = window.find_by_label("Volume");
1041            assert_eq!(slider.role(), Some(Role::Slider));
1042
1043            // Click/drag near the right end (overscroll past rail edge clamps value to 100)
1044            let control = window.find(ElementId::NamedChild(
1045                ElementId::from("volume").into(),
1046                "control".into(),
1047            ));
1048            let ctrl_bounds = control.bounds();
1049            let mid = point(
1050                ctrl_bounds.left() + ctrl_bounds.size.width * 0.5,
1051                ctrl_bounds.center().y,
1052            );
1053            let far_right = point(ctrl_bounds.right() + px(40.0), ctrl_bounds.center().y);
1054
1055            window.pointer_down(mid, MouseButton::Left, cx);
1056            window.pointer_move(far_right, Some(MouseButton::Left), cx);
1057            window.pointer_up(far_right, MouseButton::Left, cx);
1058
1059            assert_eq!(commits.get(), 1);
1060
1061            // Keyboard Home -> 0, ArrowRight -> 5, End -> 100
1062            window.press("home", cx);
1063            window.press("right", cx);
1064        });
1065
1066        assert_eq!(view.read_with(cx, |v, _| v.value), 5.0);
1067        assert_eq!(commits.get(), 3);
1068    }
1069
1070    #[gpui_kit::test]
1071    fn elastic_slider_painted_track_has_visible_geometry(cx: &mut TestAppContext) {
1072        cx.update(|cx| {
1073            gpui_kit::init(cx);
1074            install_arc_theme(ThemeMode::Light, Accent::Neutral, cx);
1075        });
1076        let (_, cx) = cx.add_window_view(|_, _| SliderHost {
1077            value: 65.0,
1078            commits: Rc::new(Cell::new(0)),
1079        });
1080        for mode in [ThemeMode::Light, ThemeMode::Dark] {
1081            cx.update(|window, cx| {
1082                install_arc_theme(mode, Accent::Neutral, cx);
1083                window.render_frame(cx);
1084                let colors = cx.arc_theme().colors;
1085                let quads = window.painted_quads();
1086                for color in [colors.control_track, colors.control_fill] {
1087                    let painted = quads
1088                        .iter()
1089                        .find(|q| q.background == color.into())
1090                        .expect("轨道及填充必须提交到绘制场景");
1091                    let width = painted.bounds.size.width.as_f32();
1092                    let height = painted.bounds.size.height.as_f32();
1093                    assert!(width > 0.0 && height > 0.0, "轨道不能塌缩");
1094                    assert!(
1095                        painted.corner_radii.top_left.as_f32() <= width.min(height) * 0.5,
1096                        "原生绘制不会像 CSS 自动限制圆角,超大半径会使轨道消失: {painted:?}"
1097                    );
1098                }
1099            });
1100        }
1101    }
1102
1103    #[test]
1104    fn elastic_snap_back_and_rubber_band_match_arc_formula() {
1105        // Rubber band stays strictly inside STRETCH = 26px
1106        assert!(rubber_band_signed(500.0, STRETCH) < STRETCH);
1107        assert!(
1108            (rubber_band_signed(-50.0, STRETCH) + rubber_band_signed(50.0, STRETCH)).abs() < 1e-5
1109        );
1110
1111        // Snap-back spring (`visualDuration: 0.5, bounce: 0.42`) is underdamped and overshoots smoothly
1112        let snap_back = SpringSpec::visual(0.5, 0.42).as_physical();
1113        let solver = SpringSolver::new(snap_back, 26.0, 0.0, 0.0);
1114        let mut actual = CurveTrace::new("elastic-slider", "over_px");
1115        let mut expected = CurveTrace::new("elastic-slider", "over_px");
1116
1117        let phys = snap_back.resolve();
1118        let omega0 = f64::from(phys.stiffness).sqrt();
1119        let zeta = f64::from(phys.damping) / (2.0 * omega0);
1120        let decay = zeta * omega0;
1121        let omega_d = omega0 * (1.0 - zeta * zeta).sqrt();
1122
1123        let mut saw_overshoot = false;
1124        for frame in 0..=60 {
1125            let t_ms = frame as f64 * 16.0;
1126            let t = t_ms / 1000.0;
1127            let env = (-decay * t).exp();
1128            let ref_v =
1129                env * (26.0 * (omega_d * t).cos() + (decay * 26.0 / omega_d) * (omega_d * t).sin());
1130            let s = solver.sample(t);
1131            if s.value < -0.5 {
1132                saw_overshoot = true;
1133            }
1134            expected.push(t_ms, ref_v);
1135            actual.push(t_ms, f64::from(s.value));
1136        }
1137
1138        assert!(
1139            saw_overshoot,
1140            "bounce=0.42 snapBack spring must visibly overshoot"
1141        );
1142        let err = max_curve_error_pct(&actual, &expected);
1143        assert!(
1144            err < 5.0,
1145            "ElasticSlider snapBack curve error {err:.3}% >= 5%"
1146        );
1147    }
1148}