Skip to main content

arc_ui/inputs/
slider.rs

1//! Ported from Arc (MIT) © 2026 Elia Kuratli
2//! Reference: `Arc源码/arc-library/registry/components/slider/slider.tsx` & `.module.css`
3//!
4//! P4 Component #11: `slider`
5//!
6//! - A value or a range on one track:
7//!   - The thumb follows the pointer 1:1 (`with_travel(false)` while dragging), rubber-bands
8//!     `9px` past its limits (`rubber_band_signed`), and settles on the step grid with the
9//!     release velocity; on a coarse grid (step ≥ `12px` on the track) the release momentum may
10//!     carry the thumb exactly one step further (`slider_project_velocity = velocity * 0.099`).
11//!   - Pressing the track springs the nearest thumb over from where it was (a catch-up seed on
12//!     the thumb spring) instead of teleporting.
13//!   - A bubble with odometer digits rides the thumb while it is dragged, keyboard focused, or
14//!     for `700ms` after release; digits roll in the direction the value moved and wrap 9 → 0
15//!     (shared `wheel_offset` / `wheel_step` math with `animated-counter`, upstream formulas
16//!     for glyph y `1.05em`, opacity `1 - |offset|^1.5 * 1.1`, and blur `soft * 0.75 * d`).
17//!   - Range thumbs keep `min_steps_between_thumbs` apart; presses, marks, and keys all route
18//!     through the same settle clamp.
19//!   - Arrows / Shift+arrows / PageUp / PageDown / Home / End work as in a native range input;
20//!     at a limit the thumb strains toward the press (`BUMP_PX = 150` kick velocity).
21//!   - Ticks and labelled marks: a mark label prints under the track, highlights while in
22//!     range, and clicking it moves the nearest thumb there.
23//!
24//! Known deviations from upstream:
25//! - Stacked range thumbs (equal values) resolve a press on the thumb itself to the last
26//!   active thumb instead of waiting for the first movement direction.
27//! - New digit columns in the bubble/readout appear without the width-opening `spring.morph`
28//!   (GPUI has no measured auto-width spring); the wheel glyph fade still applies.
29//! - The web-only `name` hidden form inputs and the `start` / `end` content slots are
30//!   omitted; labelled marks align to the track region.
31
32use std::{cell::RefCell, rc::Rc};
33
34use arc_motion::{
35    BlurFallback, DragTracker, arc_spring, arc_spring_with_options, arc_transition,
36    is_reduced_motion, motion_now, rubber_band_signed, spring::SpringOptions,
37};
38use arc_tokens::{ActiveArcTheme as _, Shadows, Spacing, SpringSpec, Typography, oklab_mix};
39use gpui_kit::{
40    AnyElement, App, Bounds, Corners, Edges, ElementId, FocusHandle, Hsla, IntoElement,
41    KeyDownEvent, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, ParentElement, Pixels,
42    RenderOnce, Role, SharedString, Styled, TestSupportExt as _, Window, base::StyledExt as _,
43    canvas, div, prelude::*, px, quad,
44};
45
46use crate::text::animated_counter::{wheel_offset, wheel_step};
47
48type SliderValueHandler = Rc<dyn Fn(&SliderValue, &mut Window, &mut App)>;
49
50/// Pixels of rubber-band travel past a limit (`STRETCH`).
51pub const SLIDER_STRETCH_PX: f32 = 9.0;
52/// Velocity of a key press at a limit, in px/s (`BUMP_PX`).
53pub const SLIDER_BUMP_PX: f32 = 150.0;
54/// The pixel size of a step that release momentum may choose (`SNAP_PX`).
55pub const SLIDER_SNAP_PX: f32 = 12.0;
56/// How long (`700ms`) the bubble lingers after a release.
57pub const SLIDER_LINGER_SECS: f64 = 0.7;
58
59/// The thumb and bubble springs run as physical springs so a release hands velocity over
60/// (Motion drops velocity on time-defined springs). Rest thresholds sit far below a pixel
61/// because positions are percentages of the track.
62pub const fn slider_thumb_spring() -> SpringSpec {
63    // `spring.snappy` restated physically: visualDuration 0.26s, bounce 0.
64    let root = std::f64::consts::TAU / (0.26 * 1.2);
65    SpringSpec::physics((root * root) as f32, (2.0 * root) as f32)
66}
67
68/// The at-limit kick runs on `spring.morph` restated physically (visual 0.42s, bounce 0).
69pub const fn slider_kick_spring() -> SpringSpec {
70    let root = std::f64::consts::TAU / (0.42 * 1.2);
71    SpringSpec::physics((root * root) as f32, (2.0 * root) as f32)
72}
73
74/// Where a release is heading, from a scroll-like deceleration, in percent per second.
75pub fn slider_project_velocity(velocity_pct_per_sec: f32) -> f32 {
76    velocity_pct_per_sec * 0.099
77}
78
79/// Glyph opacity from its wheel distance (upstream `Glyph` opacity transform).
80pub fn slider_glyph_opacity(offset: f32) -> f32 {
81    (1.0 - offset.abs().powf(1.5) * 1.1).max(0.0)
82}
83
84/// A slider value: one thumb or a pair.
85#[derive(Clone, Copy, Debug, PartialEq)]
86pub enum SliderValue {
87    Single(f32),
88    Range(f32, f32),
89}
90
91impl SliderValue {
92    /// The thumb values, lowest index first.
93    pub fn values(self) -> Vec<f32> {
94        match self {
95            Self::Single(v) => vec![v],
96            Self::Range(a, b) => vec![a, b],
97        }
98    }
99
100    fn from_values(values: &[f32], is_range: bool) -> Self {
101        if is_range {
102            Self::Range(values[0], values.get(1).copied().unwrap_or(values[0]))
103        } else {
104            Self::Single(values[0])
105        }
106    }
107}
108
109/// One tick on the track; a label prints under the track and clicking it moves the nearest
110/// thumb there.
111#[derive(Clone, Debug, PartialEq)]
112pub struct SliderMark {
113    pub value: f32,
114    pub label: Option<SharedString>,
115}
116
117impl From<f32> for SliderMark {
118    fn from(value: f32) -> Self {
119        Self { value, label: None }
120    }
121}
122
123impl SliderMark {
124    pub fn new(value: f32) -> Self {
125        value.into()
126    }
127
128    pub fn with_label(value: f32, label: impl Into<SharedString>) -> Self {
129        Self {
130            value,
131            label: Some(label.into()),
132        }
133    }
134}
135
136#[derive(Clone)]
137struct SliderInternal {
138    uncontrolled: Vec<f32>,
139    dragging: Option<usize>,
140    /// Seed for the pressed-track glide: the shown percentage the spring starts from.
141    press_seed: Option<(usize, f32)>,
142    linger_until_secs: f64,
143    quiet: bool,
144    last_active: usize,
145    kick_impulse: Option<f32>,
146    tracker: DragTracker,
147    grab_offset_pct: f32,
148    drag_raw_pct: f32,
149    drag_over_px: f32,
150    rail_bounds: Rc<RefCell<Option<Bounds<Pixels>>>>,
151    focus_handles: Vec<FocusHandle>,
152}
153
154impl SliderInternal {
155    fn new(initial: Vec<f32>, cx: &mut App) -> Self {
156        let count = initial.len().clamp(1, 2);
157        let last_active = initial.len().saturating_sub(1);
158        let focus_handles = (0..count).map(|_| cx.focus_handle()).collect();
159        Self {
160            uncontrolled: initial,
161            dragging: None,
162            press_seed: None,
163            linger_until_secs: f64::NEG_INFINITY,
164            quiet: false,
165            last_active,
166            kick_impulse: None,
167            tracker: DragTracker::new(0.0),
168            grab_offset_pct: 0.0,
169            drag_raw_pct: 0.0,
170            drag_over_px: 0.0,
171            rail_bounds: Rc::new(RefCell::new(None)),
172            focus_handles,
173        }
174    }
175}
176
177fn decimals_of(value: f32) -> usize {
178    let text = format!("{value}");
179    text.split('.')
180        .nth(1)
181        .map_or(0, |frac| frac.trim_end_matches('0').len())
182}
183
184pub fn slider_snap(input: f32, min: f32, max: f32, step: f32, decimals: usize) -> f32 {
185    let step = if step > 0.0 { step } else { 1.0 };
186    let factor = 10.0_f32.powi(decimals as i32);
187    let snapped = min + ((input - min) / step).round() * step;
188    ((snapped * factor).round() / factor).clamp(min, max)
189}
190
191pub fn slider_pct_of(value: f32, min: f32, span: f32) -> f32 {
192    (((value - min) / span) * 100.0).clamp(0.0, 100.0)
193}
194
195/// Splits a formatted value into digit columns keyed by place and symbols keyed by side, so
196/// `$950` → `$1,000` opens a column and a comma while the rest roll.
197pub fn slider_parts_of(text: &str) -> Vec<(String, Option<u8>)> {
198    let chars: Vec<char> = text.chars().collect();
199    let first = chars.iter().position(|c| c.is_ascii_digit());
200    let last = chars
201        .iter()
202        .rposition(|c| c.is_ascii_digit())
203        .unwrap_or(chars.len());
204    let total_digits = chars.iter().filter(|c| c.is_ascii_digit()).count();
205    let mut place = total_digits;
206    let mut out = Vec::with_capacity(chars.len());
207    for (index, &ch) in chars.iter().enumerate() {
208        if first.is_none_or(|f| index < f) {
209            out.push((format!("p{index}{ch}"), None));
210        } else if index > last {
211            out.push((format!("s{}{ch}", chars.len() - index), None));
212        } else if ch.is_ascii_digit() {
213            place -= 1;
214            out.push((format!("d{place}"), Some(ch as u8 - b'0')));
215        } else {
216            out.push((format!("g{place}{ch}"), None));
217        }
218    }
219    out
220}
221
222/// Formats a value with fixed decimals and `en-US` grouping (upstream's default formatter).
223pub fn slider_format_default(value: f64, decimals: usize) -> String {
224    let rounded = format!("{value:.decimals$}");
225    let (sign, rest) = rounded
226        .strip_prefix('-')
227        .map(|r| ("-", r))
228        .unwrap_or(("", rounded.as_str()));
229    let (whole, frac) = match rest.split_once('.') {
230        Some((w, f)) => (w, Some(f)),
231        None => (rest, None),
232    };
233    let mut grouped = String::new();
234    let len = whole.len();
235    for (idx, ch) in whole.chars().enumerate() {
236        grouped.push(ch);
237        let rem = len - 1 - idx;
238        if rem > 0 && rem % 3 == 0 {
239            grouped.push(',');
240        }
241    }
242    match frac {
243        Some(f) => format!("{sign}{grouped}.{f}"),
244        None => format!("{sign}{grouped}"),
245    }
246}
247
248/// One odometer readout instance ("bubble-0", "readout-0", …).
249#[derive(Clone)]
250pub(crate) struct RollingNumber {
251    pub(crate) where_key: SharedString,
252}
253
254/// Persisted wheel targets for one rolling number (one entry per digit column).
255#[derive(Clone)]
256pub(crate) struct RollingState {
257    pub(crate) wheels: Vec<(SharedString, u8, f32)>,
258    pub(crate) prev_value: f64,
259    pub(crate) direction: i32,
260}
261
262impl Default for RollingState {
263    fn default() -> Self {
264        Self {
265            wheels: Vec::new(),
266            prev_value: f64::NEG_INFINITY,
267            direction: 1,
268        }
269    }
270}
271
272/// Renders one odometer readout whose digits roll in the direction the value moved.
273#[allow(clippy::too_many_arguments)]
274pub(crate) fn render_rolling_number(
275    host_id: &ElementId,
276    rolling: &RollingNumber,
277    value: f64,
278    formatted_text: &str,
279    font_px: f32,
280    color: Hsla,
281    reduced: bool,
282    window: &mut Window,
283    cx: &mut App,
284) -> AnyElement {
285    let rolling_state_id = ElementId::NamedChild(
286        host_id.clone().into(),
287        SharedString::from(format!("roll-{}", rolling.where_key)),
288    );
289    let rolling_state =
290        window.use_keyed_state(rolling_state_id, cx, |_, _| RollingState::default());
291    rolling_state.update(cx, |s, _| {
292        if s.prev_value != value {
293            s.direction = if value > s.prev_value { 1 } else { -1 };
294            s.prev_value = value;
295        }
296    });
297    let parts = slider_parts_of(formatted_text);
298    let spring = slider_thumb_spring();
299    let mut columns: Vec<AnyElement> = Vec::with_capacity(parts.len());
300    for (key, digit_opt) in &parts {
301        match digit_opt {
302            Some(digit) => {
303                let key_id = SharedString::from(key.clone());
304                // Advance the wheel target by the odometer step for this place.
305                let target = rolling_state.update(cx, |s, _| {
306                    match s.wheels.iter_mut().find(|(k, _, _)| *k == key_id) {
307                        Some(entry) => {
308                            let prev = entry.1;
309                            let t = entry.2;
310                            if prev != *digit {
311                                let delta = wheel_step(prev, *digit, s.direction);
312                                entry.1 = *digit;
313                                entry.2 = t + delta;
314                            }
315                            entry.2
316                        }
317                        None => {
318                            s.wheels.push((key_id.clone(), *digit, f32::from(*digit)));
319                            f32::from(*digit)
320                        }
321                    }
322                });
323                let position = if reduced {
324                    target
325                } else {
326                    arc_spring(
327                        (
328                            host_id.clone(),
329                            SharedString::from(format!("{}-wheel-{key}", rolling.where_key)),
330                        ),
331                        target,
332                        spring,
333                        window,
334                        cx,
335                    )
336                };
337                let mut glyphs: Vec<AnyElement> = Vec::with_capacity(4);
338                for d in 0..10_u8 {
339                    let offset = wheel_offset(d, position);
340                    if offset.abs() >= 1.0 {
341                        continue;
342                    }
343                    let opacity = slider_glyph_opacity(offset);
344                    if opacity <= 0.01 {
345                        continue;
346                    }
347                    let blur = BlurFallback::evaluate(px(4.0 * 0.75 * offset.abs()), reduced);
348                    glyphs.push(
349                        div()
350                            .absolute()
351                            .left_0()
352                            .w_full()
353                            .top(px(offset * 1.05 * font_px))
354                            .opacity(opacity * blur.opacity_multiplier)
355                            .child(SharedString::from((b'0' + d) as char))
356                            .into_any_element(),
357                    );
358                }
359                columns.push(
360                    div()
361                        .relative()
362                        .flex_none()
363                        .w(px(font_px * 0.62))
364                        .h(px(font_px * 1.3))
365                        .overflow_hidden()
366                        .children(glyphs)
367                        .into_any_element(),
368                );
369            }
370            None => {
371                // Key format is `p{index}{ch}`, `s{rem}{ch}`, or `g{place}{ch}` — the last char is the symbol.
372                if let Some(ch) = key.chars().last() {
373                    columns.push(
374                        div()
375                            .flex_none()
376                            .child(SharedString::from(ch))
377                            .into_any_element(),
378                    );
379                }
380            }
381        }
382    }
383    div()
384        .flex()
385        .flex_row()
386        .items_center()
387        .whitespace_nowrap()
388        .text_size(px(font_px))
389        .text_color(color)
390        .children(columns)
391        .into_any_element()
392}
393
394/// Arc `Slider` — a value or range on one track with 1:1 drag, rubber limits, velocity settle,
395/// an odometer bubble, keyboard stepping, and clickable marks.
396#[derive(IntoElement)]
397pub struct Slider {
398    id: ElementId,
399    label: SharedString,
400    value: Option<SliderValue>,
401    default_value: Option<SliderValue>,
402    min: f32,
403    max: f32,
404    step: f32,
405    large_step: Option<f32>,
406    marks: Vec<SliderMark>,
407    min_steps_between_thumbs: f32,
408    format: Option<Rc<dyn Fn(f64) -> String>>,
409    show_value: bool,
410    thumb_labels: Option<[SharedString; 2]>,
411    disabled: bool,
412    width: Option<Pixels>,
413    on_value_change: Option<SliderValueHandler>,
414    on_value_commit: Option<SliderValueHandler>,
415}
416
417impl Slider {
418    pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
419        Self {
420            id: id.into(),
421            label: label.into(),
422            value: None,
423            default_value: None,
424            min: 0.0,
425            max: 100.0,
426            step: 1.0,
427            large_step: None,
428            marks: Vec::new(),
429            min_steps_between_thumbs: 0.0,
430            format: None,
431            show_value: true,
432            thumb_labels: None,
433            disabled: false,
434            width: None,
435            on_value_change: None,
436            on_value_commit: None,
437        }
438    }
439
440    pub fn value(mut self, value: SliderValue) -> Self {
441        self.value = Some(value);
442        self
443    }
444
445    pub fn default_value(mut self, value: SliderValue) -> Self {
446        self.default_value = Some(value);
447        self
448    }
449
450    pub fn min(mut self, min: f32) -> Self {
451        self.min = min;
452        self
453    }
454
455    pub fn max(mut self, max: f32) -> Self {
456        self.max = max;
457        self
458    }
459
460    pub fn step(mut self, step: f32) -> Self {
461        self.step = step;
462        self
463    }
464
465    /// PageUp, PageDown, and Shift with an arrow move this far (defaults to a tenth of the range).
466    pub fn large_step(mut self, large_step: f32) -> Self {
467        self.large_step = Some(large_step);
468        self
469    }
470
471    pub fn marks<I, M>(mut self, marks: I) -> Self
472    where
473        I: IntoIterator<Item = M>,
474        M: Into<SliderMark>,
475    {
476        self.marks = marks.into_iter().map(Into::into).collect();
477        self
478    }
479
480    /// The closest two range thumbs may sit, in steps.
481    pub fn min_steps_between_thumbs(mut self, steps: f32) -> Self {
482        self.min_steps_between_thumbs = steps;
483        self
484    }
485
486    pub fn format(mut self, format: impl Fn(f64) -> String + 'static) -> Self {
487        self.format = Some(Rc::new(format));
488        self
489    }
490
491    pub fn show_value(mut self, show: bool) -> Self {
492        self.show_value = show;
493        self
494    }
495
496    /// Accessible names for the two range thumbs.
497    pub fn thumb_labels(mut self, labels: [&str; 2]) -> Self {
498        let arr: [SharedString; 2] = [labels[0].into(), labels[1].into()];
499        self.thumb_labels = Some(arr);
500        self
501    }
502
503    pub fn disabled(mut self, disabled: bool) -> Self {
504        self.disabled = disabled;
505        self
506    }
507
508    pub fn width(mut self, width: impl Into<Pixels>) -> Self {
509        self.width = Some(width.into());
510        self
511    }
512
513    pub fn on_value_change(
514        mut self,
515        handler: impl Fn(&SliderValue, &mut Window, &mut App) + 'static,
516    ) -> Self {
517        self.on_value_change = Some(Rc::new(handler));
518        self
519    }
520
521    /// Runs once a drag is released or a key changes the value.
522    pub fn on_value_commit(
523        mut self,
524        handler: impl Fn(&SliderValue, &mut Window, &mut App) + 'static,
525    ) -> Self {
526        self.on_value_commit = Some(Rc::new(handler));
527        self
528    }
529}
530
531impl RenderOnce for Slider {
532    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
533        let theme = cx.arc_theme().clone();
534        let colors = theme.colors;
535        let motion = theme.motion;
536        let reduced = is_reduced_motion(cx);
537        let now = motion_now(cx);
538
539        let min = self.min;
540        let max = self.max;
541        let span = (max - min).max(1.0);
542        let step = if self.step > 0.0 { self.step } else { 1.0 };
543        let initial_hint = self.value.or(self.default_value);
544        let is_range = matches!(
545            initial_hint.unwrap_or(SliderValue::Single(min)),
546            SliderValue::Range(..)
547        );
548        let count = if is_range { 2 } else { 1 };
549        let gap = if is_range {
550            self.min_steps_between_thumbs * step
551        } else {
552            0.0
553        };
554        let decimals = decimals_of(step).max(decimals_of(min));
555        let format_value: Rc<dyn Fn(f64) -> String> = self
556            .format
557            .clone()
558            .unwrap_or_else(|| Rc::new(move |v| slider_format_default(v, decimals)));
559
560        let state_id = ElementId::NamedChild(self.id.clone().into(), "__arc-slider-state".into());
561        let internal = window.use_keyed_state(state_id, cx, |_, cx| {
562            let initial = match self.value.or(self.default_value) {
563                Some(SliderValue::Single(v)) => vec![v],
564                Some(SliderValue::Range(a, b)) => vec![a, b],
565                None => {
566                    if is_range {
567                        vec![min, max]
568                    } else {
569                        vec![min]
570                    }
571                }
572            };
573            SliderInternal::new(initial, cx)
574        });
575
576        // Controlled external value sync.
577        if let Some(ext) = self.value {
578            let ext_values = ext.values();
579            let cur = internal.read(cx).uncontrolled.clone();
580            if ext_values.as_slice() != cur.as_slice() && ext_values.len() == cur.len() {
581                internal.update(cx, |s, _| s.uncontrolled = ext_values.clone());
582            }
583        }
584
585        let snap_state = internal.read(cx).clone();
586        let mut values = self
587            .value
588            .map_or_else(|| snap_state.uncontrolled.clone(), |v| v.values());
589        if values.len() < count {
590            values.resize(count, min);
591        }
592
593        let low_of = move |index: usize, cur: &[f32]| -> f32 {
594            if index == 1 && is_range {
595                (cur[0] + gap).clamp(min, max)
596            } else {
597                min
598            }
599        };
600        let high_of = move |index: usize, cur: &[f32]| -> f32 {
601            if index == 0 && is_range {
602                (cur[1] - gap).clamp(min, max)
603            } else {
604                max
605            }
606        };
607        let settle = move |index: usize, input: f32, cur: &[f32]| -> f32 {
608            let lo = low_of(index, cur);
609            let hi = high_of(index, cur).max(lo);
610            slider_snap(input.clamp(min, max), min, max, step, decimals).clamp(lo, hi)
611        };
612
613        let large_step = self.large_step.unwrap_or_else(|| {
614            step.max(slider_snap(min + span / 10.0, min, max, step, decimals) - min)
615        });
616
617        // ── Thumb springs ─────────────────────────────────────────────────────────────────────
618        let thumb_spring = slider_thumb_spring();
619        let rail_width = snap_state
620            .rail_bounds
621            .borrow()
622            .map_or(240.0_f32, |b| (f32::from(b.size.width) - 22.0).max(1.0));
623
624        let dragging_index = snap_state.dragging;
625        let kick_impulse = snap_state.kick_impulse;
626        if kick_impulse.is_some() {
627            internal.update(cx, |s, _| s.kick_impulse = None);
628        }
629
630        let mut shown_pcts: Vec<f32> = Vec::with_capacity(count);
631        for (index, value_here) in values.iter().enumerate().take(count) {
632            let _ = value_here;
633            let target_pct = if dragging_index == Some(index) {
634                snap_state.drag_raw_pct
635            } else {
636                slider_pct_of(values[index], min, span)
637            };
638            let mut opts = SpringOptions::new(thumb_spring)
639                .with_travel(dragging_index != Some(index))
640                .with_rest_thresholds(0.002, 0.02);
641            if let Some(seed) = snap_state.press_seed
642                && seed.0 == index
643            {
644                opts = opts.with_initial_value(seed.1);
645                internal.update(cx, |s, _| s.press_seed = None);
646            }
647            if let Some(v) = kick_impulse
648                && dragging_index.is_none()
649            {
650                opts = opts.with_initial_velocity(v);
651            }
652            let sample = arc_spring_with_options(
653                (self.id.clone(), SharedString::from(format!("pos-{index}"))),
654                target_pct,
655                opts,
656                window,
657                cx,
658            );
659            shown_pcts.push(sample.value);
660        }
661
662        let over_target = if dragging_index.is_some() && !reduced {
663            snap_state.drag_over_px
664        } else {
665            0.0
666        };
667        let over_sample = arc_spring_with_options(
668            (self.id.clone(), "over"),
669            over_target,
670            SpringOptions::new(SpringSpec::visual(0.5, 0.42).as_physical())
671                .with_travel(dragging_index.is_none())
672                .with_rest_thresholds(0.05, 0.5),
673            window,
674            cx,
675        );
676        let _ = over_sample;
677
678        let thumb_scale = arc_spring(
679            (self.id.clone(), "thumb-scale"),
680            if dragging_index.is_some() && !reduced {
681                1.16
682            } else {
683                1.0
684            },
685            motion.spring.snappy,
686            window,
687            cx,
688        );
689
690        let linger_active = now < snap_state.linger_until_secs;
691        if linger_active {
692            window.request_animation_frame();
693        }
694        let is_focused: Vec<bool> = (0..count)
695            .map(|i| snap_state.focus_handles[i].is_focused(window))
696            .collect();
697
698        // Bubble visibility per thumb: dragging, keyboard focused (unless pointer-quiet), or lingering.
699        let bubble_visible: Vec<bool> = (0..count)
700            .map(|i| {
701                dragging_index == Some(i)
702                    || (is_focused[i] && !snap_state.quiet)
703                    || (linger_active && snap_state.last_active == i)
704            })
705            .collect();
706
707        // ── Marks ─────────────────────────────────────────────────────────────────────────────
708        let mark_list: Vec<SliderMark> = self
709            .marks
710            .iter()
711            .filter(|m| m.value >= min && m.value <= max)
712            .cloned()
713            .collect();
714        let ticks: Vec<f32> = mark_list
715            .iter()
716            .filter(|m| m.value > min && m.value < max)
717            .map(|m| m.value)
718            .collect();
719        let labelled: Vec<SliderMark> = mark_list
720            .into_iter()
721            .filter(|m| m.label.is_some())
722            .collect();
723        let in_range_values = values.clone();
724        let in_range = move |v: f32| -> bool {
725            if is_range {
726                v >= in_range_values[0] && v <= in_range_values[1]
727            } else {
728                v <= in_range_values[0]
729            }
730        };
731        let names: [SharedString; 2] = self.thumb_labels.clone().unwrap_or([
732            SharedString::from(format!("{}, minimum", self.label)),
733            SharedString::from(format!("{}, maximum", self.label)),
734        ]);
735
736        let is_disabled = self.disabled;
737        let is_controlled = self.value.is_some();
738        let on_change = self.on_value_change.clone();
739        let on_commit = self.on_value_commit.clone();
740
741        // ── Drag plumbing (window-level capture, like elastic-slider) ─────────────────────────
742        let st_down = internal.clone();
743        let focus_down = snap_state.focus_handles.clone();
744        let values_down = values.clone();
745
746        let control = div()
747            .id(ElementId::NamedChild(
748                self.id.clone().into(),
749                "control".into(),
750            ))
751            .test_support()
752            .relative()
753            .flex_1()
754            .min_w_0()
755            .h(px(36.0))
756            .flex()
757            .items_center()
758            .when(!is_disabled, |this| this.cursor_pointer())
759            .on_mouse_down(
760                MouseButton::Left,
761                move |event: &MouseDownEvent, window, cx| {
762                    if is_disabled {
763                        return;
764                    }
765                    let Some(rail) = *st_down.read(cx).rail_bounds.borrow() else {
766                        return;
767                    };
768                    let w = (f32::from(rail.size.width) - 22.0).max(1.0);
769                    let now_d = motion_now(cx);
770                    let at_pct =
771                        ((f32::from(event.position.x) - (f32::from(rail.origin.x) + 11.0)) / w)
772                            * 100.0;
773                    let current: Vec<f32> = if is_controlled {
774                        values_down.clone()
775                    } else {
776                        st_down.read(cx).uncontrolled.clone()
777                    };
778                    // A press on a thumb grabs it 1:1 (grab offset); a press on the track springs
779                    // the nearest thumb over from where it was.
780                    let hit_radius_pct = (16.0 / w) * 100.0;
781                    let mut grabbed: Option<usize> = None;
782                    for (i, v) in current.iter().enumerate().take(count) {
783                        let dist = (at_pct - slider_pct_of(*v, min, span)).abs();
784                        if dist <= hit_radius_pct
785                            && grabbed.is_none_or(|g| {
786                                dist < (at_pct - slider_pct_of(current[g], min, span)).abs()
787                            })
788                        {
789                            grabbed = Some(i);
790                        }
791                    }
792                    let index = if is_range {
793                        let low = (at_pct - slider_pct_of(current[0], min, span)).abs();
794                        let high = (at_pct - slider_pct_of(current[1], min, span)).abs();
795                        if low == high {
796                            if at_pct < slider_pct_of(current[0], min, span) {
797                                0
798                            } else {
799                                1
800                            }
801                        } else if low < high {
802                            0
803                        } else {
804                            1
805                        }
806                    } else {
807                        0
808                    };
809                    let from_pct = slider_pct_of(current[index], min, span);
810                    st_down.update(cx, |s, _| {
811                        s.dragging = Some(index);
812                        s.last_active = index;
813                        s.quiet = true;
814                        s.linger_until_secs = f64::NEG_INFINITY;
815                        s.tracker = DragTracker::new(at_pct);
816                        s.tracker.update_x(at_pct, 0.0, now_d, true);
817                        if let Some(g) = grabbed {
818                            s.grab_offset_pct = at_pct - slider_pct_of(current[g], min, span);
819                            s.press_seed = None;
820                        } else {
821                            s.grab_offset_pct = 0.0;
822                            s.press_seed = Some((index, from_pct));
823                        }
824                        s.drag_raw_pct = at_pct - s.grab_offset_pct;
825                    });
826                    window.focus(&focus_down[index], cx);
827                    window.refresh();
828                },
829            )
830            .child(
831                canvas(
832                    {
833                        let rail_ref = snap_state.rail_bounds.clone();
834                        move |rect, _, _| {
835                            *rail_ref.borrow_mut() = Some(rect);
836                        }
837                    },
838                    {
839                        let st = internal.clone();
840                        let ch_move = on_change.clone();
841                        let cm_move = on_commit.clone();
842                        let values_move = values.clone();
843                        let values_up = values.clone();
844                        move |_, _, window, cx| {
845                            // Release handling registers every paint so a click (down + up within one
846                            // frame) always clears the drag state.
847                            if !is_disabled {
848                                let st_up = st.clone();
849                                let values_up = values_up.clone();
850                                let ch_up = ch_move.clone();
851                                let cm_up = cm_move.clone();
852                                window.on_mouse_event(
853                                    move |event: &MouseUpEvent, phase, window, cx| {
854                                        if !phase.bubble()
855                                            || event.button != MouseButton::Left
856                                            || st_up.read(cx).dragging.is_none()
857                                        {
858                                            return;
859                                        }
860                                        let now_u = motion_now(cx);
861                                        let index = st_up.read(cx).dragging.unwrap_or(0);
862                                        let cur: Vec<f32> = if is_controlled {
863                                            values_up.clone()
864                                        } else {
865                                            st_up.read(cx).uncontrolled.clone()
866                                        };
867                                        let vel = st_up.read(cx).tracker.release_velocity(now_u);
868                                        let raw = st_up.read(cx).drag_raw_pct;
869                                        let step_pct = (step / span) * 100.0;
870                                        let step_px = (step_pct / 100.0) * rail_width;
871                                        let carry = if step_px >= SLIDER_SNAP_PX {
872                                            slider_project_velocity(vel).clamp(-step_pct, step_pct)
873                                        } else {
874                                            0.0
875                                        };
876                                        let next_val = settle(
877                                            index,
878                                            min + ((raw + carry) / 100.0) * span,
879                                            &cur,
880                                        );
881                                        st_up.update(cx, |s, _| {
882                                            s.dragging = None;
883                                            s.linger_until_secs = now_u + SLIDER_LINGER_SECS;
884                                            s.kick_impulse = Some(vel);
885                                            s.drag_over_px = 0.0;
886                                            if !is_controlled {
887                                                s.uncontrolled[index] = next_val;
888                                            }
889                                        });
890                                        if (next_val - cur[index]).abs() > f32::EPSILON
891                                            && let Some(handler) = &ch_up
892                                        {
893                                            let mut updated = cur.clone();
894                                            updated[index] = next_val;
895                                            let v = SliderValue::from_values(&updated, is_range);
896                                            handler(&v, window, cx);
897                                        }
898                                        if let Some(handler) = &cm_up {
899                                            let final_cur: Vec<f32> = if is_controlled {
900                                                values_up.clone()
901                                            } else {
902                                                st_up.read(cx).uncontrolled.clone()
903                                            };
904                                            let v = SliderValue::from_values(&final_cur, is_range);
905                                            handler(&v, window, cx);
906                                        }
907                                        window.refresh();
908                                    },
909                                );
910                            }
911                            if st.read(cx).dragging.is_none() || is_disabled {
912                                return;
913                            }
914                            // Track pointer moves while dragging (window capture).
915                            let st_move = st.clone();
916                            let values_move = values_move.clone();
917                            let ch_m = ch_move.clone();
918                            window.on_mouse_event(
919                                move |event: &MouseMoveEvent, phase, window, cx| {
920                                    if !phase.bubble() || st_move.read(cx).dragging.is_none() {
921                                        return;
922                                    }
923                                    let Some(rail) = *st_move.read(cx).rail_bounds.borrow() else {
924                                        return;
925                                    };
926                                    let w = (f32::from(rail.size.width) - 22.0).max(1.0);
927                                    let now_m = motion_now(cx);
928                                    let index = st_move.read(cx).dragging.unwrap_or(0);
929                                    let cur: Vec<f32> = if is_controlled {
930                                        values_move.clone()
931                                    } else {
932                                        st_move.read(cx).uncontrolled.clone()
933                                    };
934                                    let grab = st_move.read(cx).grab_offset_pct;
935                                    let at_pct = ((f32::from(event.position.x)
936                                        - (f32::from(rail.origin.x) + 11.0))
937                                        / w)
938                                        * 100.0;
939                                    let raw = at_pct - grab;
940                                    let low_pct = slider_pct_of(low_of(index, &cur), min, span);
941                                    let high_pct =
942                                        slider_pct_of(high_of(index, &cur), min, span).max(low_pct);
943                                    let edge = raw.clamp(low_pct, high_pct);
944                                    let over = if reduced {
945                                        0.0
946                                    } else {
947                                        rubber_band_signed(
948                                            (raw - edge) / 100.0 * w,
949                                            SLIDER_STRETCH_PX,
950                                        ) / w
951                                            * 100.0
952                                    };
953                                    let placed = edge + over;
954                                    let next_val = settle(index, min + (edge / 100.0) * span, &cur);
955                                    st_move.update(cx, |s, _| {
956                                        s.drag_raw_pct = placed;
957                                        s.drag_over_px = (raw - edge) / 100.0 * w;
958                                        s.tracker.update_x(placed, 0.0, now_m, false);
959                                        if !is_controlled {
960                                            s.uncontrolled[index] = next_val;
961                                        }
962                                    });
963                                    if (next_val - cur[index]).abs() > f32::EPSILON
964                                        && let Some(handler) = &ch_m
965                                    {
966                                        let mut updated = cur.clone();
967                                        updated[index] = next_val;
968                                        let v = SliderValue::from_values(&updated, is_range);
969                                        handler(&v, window, cx);
970                                    }
971                                    window.refresh();
972                                },
973                            );
974                        }
975                    },
976                )
977                .absolute()
978                .inset_0(),
979            )
980            // ── Track + fill + ticks (canvas paint) ───────────────────────────────────────────
981            .child(
982                canvas(|_, _, _| {}, {
983                    let shown_pcts = shown_pcts.clone();
984                    let values = values.clone();
985                    move |rect, _, window, _| {
986                        let track_color = colors.control_track;
987                        let fill_color = colors.control_fill;
988                        let tick_off =
989                            oklab_mix(colors.foreground, Hsla::transparent_black(), 0.32);
990                        let tick_on =
991                            oklab_mix(colors.control_glyph, Hsla::transparent_black(), 0.60);
992                        let w = f32::from(rect.size.width);
993                        let track_y = rect.origin.y + px((f32::from(rect.size.height) - 6.0) / 2.0);
994                        let track_bounds = Bounds {
995                            origin: gpui_kit::point(rect.origin.x, track_y),
996                            size: gpui_kit::size(rect.size.width, px(6.0)),
997                        };
998                        window.paint_quad(quad(
999                            track_bounds,
1000                            Corners::all(px(3.0)),
1001                            track_color,
1002                            Edges::default(),
1003                            Hsla::transparent_black(),
1004                            gpui_kit::BorderStyle::Solid,
1005                        ));
1006                        // Fill clipped between the shown thumbs (single value: from the left edge).
1007                        let from_pct = if is_range {
1008                            shown_pcts[0].clamp(0.0, 100.0)
1009                        } else {
1010                            0.0
1011                        };
1012                        let to_pct = if is_range {
1013                            shown_pcts[1].clamp(0.0, 100.0)
1014                        } else {
1015                            shown_pcts[0].clamp(0.0, 100.0)
1016                        };
1017                        let fill_x = track_bounds.origin.x + px(from_pct / 100.0 * w);
1018                        let fill_w = ((to_pct - from_pct) / 100.0 * w).max(0.0);
1019                        if fill_w > 0.0 {
1020                            window.paint_quad(quad(
1021                                Bounds {
1022                                    origin: gpui_kit::point(fill_x, track_y),
1023                                    size: gpui_kit::size(px(fill_w), px(6.0)),
1024                                },
1025                                Corners::all(px(3.0)),
1026                                fill_color,
1027                                Edges::default(),
1028                                Hsla::transparent_black(),
1029                                gpui_kit::BorderStyle::Solid,
1030                            ));
1031                        }
1032                        // Ticks (4x4 dots drawn on both track and fill, matching upstream `.tick`).
1033                        for tick in &ticks {
1034                            let tx = track_bounds.origin.x
1035                                + px(slider_pct_of(*tick, min, span) / 100.0 * w);
1036                            let on = if is_range {
1037                                *tick >= values[0] && *tick <= values[1]
1038                            } else {
1039                                *tick <= values[0]
1040                            };
1041                            window.paint_quad(quad(
1042                                Bounds {
1043                                    origin: gpui_kit::point(tx - px(2.0), track_y + px(1.0)),
1044                                    size: gpui_kit::size(px(4.0), px(4.0)),
1045                                },
1046                                Corners::all(px(2.0)),
1047                                if on { tick_on } else { tick_off },
1048                                Edges::default(),
1049                                Hsla::transparent_black(),
1050                                gpui_kit::BorderStyle::Solid,
1051                            ));
1052                        }
1053                    }
1054                })
1055                .absolute()
1056                .top_0()
1057                .bottom_0()
1058                .left(px(11.0))
1059                .right(px(11.0)),
1060            )
1061            // ── Thumbs + bubbles ──────────────────────────────────────────────────────────────
1062            .children((0..count).map(|index| {
1063                let shown = shown_pcts[index];
1064                let value_here = values[index];
1065                let text_here = format_value(f64::from(value_here));
1066                let bubble_on = bubble_visible[index];
1067                let bubble_op = arc_transition(
1068                    (
1069                        self.id.clone(),
1070                        SharedString::from(format!("bubble-op-{index}")),
1071                    ),
1072                    if bubble_on { 1.0 } else { 0.0 },
1073                    if reduced {
1074                        std::time::Duration::ZERO
1075                    } else {
1076                        motion.duration.instant
1077                    },
1078                    motion.ease.standard,
1079                    window,
1080                    cx,
1081                );
1082                let bubble_y = arc_spring(
1083                    (
1084                        self.id.clone(),
1085                        SharedString::from(format!("bubble-y-{index}")),
1086                    ),
1087                    if bubble_on { 0.0 } else { 6.0 },
1088                    motion.spring.snappy,
1089                    window,
1090                    cx,
1091                );
1092                let font_px = f32::from(Typography::TEXT_SM);
1093                let bubble_digits = render_rolling_number(
1094                    &self.id,
1095                    &RollingNumber {
1096                        where_key: SharedString::from(format!("bubble-{index}")),
1097                    },
1098                    f64::from(value_here),
1099                    &text_here,
1100                    font_px,
1101                    colors.background,
1102                    reduced,
1103                    window,
1104                    cx,
1105                );
1106                let thumb_id = ElementId::NamedChild(
1107                    self.id.clone().into(),
1108                    SharedString::from(format!("thumb-{index}")),
1109                );
1110                let focus_here = snap_state.focus_handles[index].clone();
1111                let st_key = internal.clone();
1112                let ch_key = on_change.clone();
1113                let cm_key = on_commit.clone();
1114                let values_key = values.clone();
1115                let quiet_clear = internal.clone();
1116                let inner_rail_w = rail_width;
1117                div()
1118                    .id(thumb_id)
1119                    .test_support()
1120                    .role(Role::Slider)
1121                    .aria_label(if is_range {
1122                        names[index].clone()
1123                    } else {
1124                        self.label.clone()
1125                    })
1126                    .aria_value(text_here.clone())
1127                    .track_focus(&focus_here)
1128                    .on_click({
1129                        let int_q = quiet_clear.clone();
1130                        move |_, window, cx| {
1131                            int_q.update(cx, |s, _| s.quiet = true);
1132                            window.refresh();
1133                        }
1134                    })
1135                    .on_key_down(move |event: &KeyDownEvent, window, cx| {
1136                        if is_disabled {
1137                            return;
1138                        }
1139                        // A key press un-quiets the thumb: the bubble returns.
1140                        quiet_clear.update(cx, |s, _| s.quiet = false);
1141                        let cur: Vec<f32> = if is_controlled {
1142                            values_key.clone()
1143                        } else {
1144                            st_key.read(cx).uncontrolled.clone()
1145                        };
1146                        let now_v = cur[index];
1147                        let key = event.keystroke.key.as_str();
1148                        let shift = event.keystroke.modifiers.shift;
1149                        let is_arrow = matches!(
1150                            key,
1151                            "right"
1152                                | "arrowright"
1153                                | "up"
1154                                | "arrowup"
1155                                | "left"
1156                                | "arrowleft"
1157                                | "down"
1158                                | "arrowdown"
1159                        );
1160                        let large_now =
1161                            if (shift && is_arrow) || matches!(key, "pageup" | "pagedown") {
1162                                large_step
1163                            } else {
1164                                step
1165                            };
1166                        let wanted: f32 = match key {
1167                            "right" | "arrowright" | "up" | "arrowup" => now_v + large_now,
1168                            "left" | "arrowleft" | "down" | "arrowdown" => now_v - large_now,
1169                            "pageup" => now_v + large_step,
1170                            "pagedown" => now_v - large_step,
1171                            "home" => low_of(index, &cur),
1172                            "end" => high_of(index, &cur),
1173                            _ => return,
1174                        };
1175                        let next_v = settle(index, wanted, &cur);
1176                        st_key.update(cx, |s, _| s.last_active = index);
1177                        if (next_v - now_v).abs() <= f32::EPSILON {
1178                            // At a limit the thumb strains toward the press and springs home.
1179                            let toward = (wanted - now_v).signum();
1180                            if toward != 0.0 && !reduced {
1181                                let bump = (SLIDER_BUMP_PX / rail_width) * 100.0;
1182                                st_key.update(cx, |s, _| s.kick_impulse = Some(toward * bump));
1183                                window.refresh();
1184                            }
1185                            return;
1186                        }
1187                        let mut updated = cur.clone();
1188                        updated[index] = next_v;
1189                        st_key.update(cx, |s, _| {
1190                            if !is_controlled {
1191                                s.uncontrolled = updated.clone();
1192                            }
1193                        });
1194                        let v = SliderValue::from_values(&updated, is_range);
1195                        if let Some(handler) = &ch_key {
1196                            handler(&v, window, cx);
1197                        }
1198                        if let Some(handler) = &cm_key {
1199                            handler(&v, window, cx);
1200                        }
1201                        window.refresh();
1202                    })
1203                    .absolute()
1204                    .left(px(11.0 + shown / 100.0 * inner_rail_w))
1205                    .top(px(7.0 - (thumb_scale - 1.0) * 11.0))
1206                    .ml(px(-11.0 * thumb_scale))
1207                    .size(px(22.0 * thumb_scale))
1208                    .rounded_full()
1209                    .bg(colors.surface)
1210                    .border_1()
1211                    .border_color(colors.control_fill)
1212                    .shadow(Shadows::control_thumb(theme.mode))
1213                    .when(is_disabled, |this| this.opacity(0.5))
1214                    .child(
1215                        div()
1216                            .absolute()
1217                            .bottom_full()
1218                            .left(px(11.0 * thumb_scale - 60.0))
1219                            .w(px(120.0))
1220                            .mb(px(10.0))
1221                            .flex()
1222                            .justify_center()
1223                            .opacity(bubble_op)
1224                            .mt(px(bubble_y))
1225                            .child(
1226                                div()
1227                                    .flex()
1228                                    .items_center()
1229                                    .justify_center()
1230                                    .px(px(12.0))
1231                                    .h(px(28.0))
1232                                    .rounded_full()
1233                                    .bg(colors.foreground)
1234                                    .shadow(Shadows::raised(theme.mode))
1235                                    .text_size(Typography::TEXT_SM)
1236                                    .font_medium()
1237                                    .text_color(colors.background)
1238                                    .child(bubble_digits),
1239                            ),
1240                    )
1241                    .into_any_element()
1242            }));
1243
1244        // ── Marks row aligned under the track (second row below `control`) ────────────────────
1245        let inner_rail_w = rail_width;
1246        let marks_row = (!labelled.is_empty()).then(|| {
1247            div()
1248                .relative()
1249                .w_full()
1250                .h(px(20.0))
1251                .mt(px(-4.0))
1252                .children(labelled.iter().map(|mark| {
1253                    let pct = slider_pct_of(mark.value, min, span);
1254                    let on = in_range(mark.value);
1255                    let is_start = (mark.value - min).abs() <= f32::EPSILON;
1256                    let is_end = (mark.value - max).abs() <= f32::EPSILON && !is_start;
1257                    let int_jump = internal.clone();
1258                    let ch_jump = on_change.clone();
1259                    let cm_jump = on_commit.clone();
1260                    let values_m = values.clone();
1261                    let label_m = mark.label.clone().unwrap_or_default();
1262                    let value_m = mark.value;
1263                    let x_pos = 11.0 + (pct / 100.0) * inner_rail_w;
1264                    let box_w = 80.0_f32;
1265                    let left_px = if is_start {
1266                        x_pos - 4.0
1267                    } else if is_end {
1268                        x_pos - box_w + 4.0
1269                    } else {
1270                        x_pos - box_w * 0.5
1271                    };
1272                    div()
1273                        .id(ElementId::NamedChild(
1274                            self.id.clone().into(),
1275                            SharedString::from(format!(
1276                                "mark-{}",
1277                                mark.value.to_string().replace('.', "_")
1278                            )),
1279                        ))
1280                        .test_support()
1281                        .absolute()
1282                        .top_0()
1283                        .left(px(left_px))
1284                        .w(px(box_w))
1285                        .h(px(20.0))
1286                        .flex()
1287                        .flex_row()
1288                        .items_center()
1289                        .when(is_start, |this| this.justify_start())
1290                        .when(is_end, |this| this.justify_end())
1291                        .when(!is_start && !is_end, |this| this.justify_center())
1292                        .whitespace_nowrap()
1293                        .text_size(Typography::TEXT_XS)
1294                        .cursor_pointer()
1295                        .text_color(if on {
1296                            colors.text_secondary
1297                        } else {
1298                            colors.text_muted
1299                        })
1300                        .hover(|s| s.text_color(colors.foreground))
1301                        .on_click(move |_, window, cx| {
1302                            if is_disabled {
1303                                return;
1304                            }
1305                            let cur: Vec<f32> = if is_controlled {
1306                                values_m.clone()
1307                            } else {
1308                                int_jump.read(cx).uncontrolled.clone()
1309                            };
1310                            let index = if is_range {
1311                                let low = (slider_pct_of(value_m, min, span)
1312                                    - slider_pct_of(cur[0], min, span))
1313                                .abs();
1314                                let high = (slider_pct_of(value_m, min, span)
1315                                    - slider_pct_of(cur[1], min, span))
1316                                .abs();
1317                                if low <= high { 0 } else { 1 }
1318                            } else {
1319                                0
1320                            };
1321                            let next_v = settle(index, value_m, &cur);
1322                            if (next_v - cur[index]).abs() <= f32::EPSILON {
1323                                return;
1324                            }
1325                            let mut updated = cur.clone();
1326                            updated[index] = next_v;
1327                            int_jump.update(cx, |s, _| {
1328                                s.last_active = index;
1329                                s.quiet = false;
1330                                if !is_controlled {
1331                                    s.uncontrolled = updated.clone();
1332                                }
1333                            });
1334                            let v = SliderValue::from_values(&updated, is_range);
1335                            if let Some(handler) = &ch_jump {
1336                                handler(&v, window, cx);
1337                            }
1338                            if let Some(handler) = &cm_jump {
1339                                handler(&v, window, cx);
1340                            }
1341                            window.refresh();
1342                        })
1343                        .child(div().px(px(4.0)).child(label_m))
1344                        .into_any_element()
1345                }))
1346        });
1347
1348        // ── Header: label + rolling readout ───────────────────────────────────────────────────
1349        let header = div()
1350            .flex()
1351            .flex_row()
1352            .items_center()
1353            .justify_between()
1354            .mb(Spacing::S2)
1355            .child(
1356                div()
1357                    .text_size(Typography::TEXT_SM)
1358                    .font_medium()
1359                    .text_color(colors.foreground)
1360                    .child(self.label.clone()),
1361            )
1362            .when(self.show_value, |this| {
1363                let readout_color = colors.text_secondary;
1364                let font_px = f32::from(Typography::TEXT_SM);
1365                let text0 = format_value(f64::from(values[0]));
1366                let readout0 = render_rolling_number(
1367                    &self.id,
1368                    &RollingNumber {
1369                        where_key: "readout-0".into(),
1370                    },
1371                    f64::from(values[0]),
1372                    &text0,
1373                    font_px,
1374                    readout_color,
1375                    reduced,
1376                    window,
1377                    cx,
1378                );
1379                this.child(
1380                    div()
1381                        .flex()
1382                        .flex_row()
1383                        .items_center()
1384                        .gap(px(4.0))
1385                        .child(readout0)
1386                        .when(is_range, |this| {
1387                            let text1 = format_value(f64::from(values[1]));
1388                            let readout1 = render_rolling_number(
1389                                &self.id,
1390                                &RollingNumber {
1391                                    where_key: "readout-1".into(),
1392                                },
1393                                f64::from(values[1]),
1394                                &text1,
1395                                font_px,
1396                                readout_color,
1397                                reduced,
1398                                window,
1399                                cx,
1400                            );
1401                            this.child(
1402                                div()
1403                                    .text_color(colors.text_muted)
1404                                    .child(SharedString::from("–")),
1405                            )
1406                            .child(readout1)
1407                        }),
1408                )
1409            });
1410
1411        div()
1412            .id(self.id)
1413            .test_support()
1414            .when_some(self.width, |this, w| this.w(w))
1415            .when(self.width.is_none(), |this| this.w_full())
1416            .flex()
1417            .flex_col()
1418            .when(is_disabled, |this| this.opacity(0.5))
1419            .child(header)
1420            .child(
1421                div()
1422                    .flex()
1423                    .flex_row()
1424                    .items_center()
1425                    .gap(Spacing::S3)
1426                    .child(control),
1427            )
1428            .when_some(marks_row, |this, row| this.child(row))
1429    }
1430}
1431
1432#[cfg(test)]
1433mod tests {
1434    use arc_tokens::{Accent, ThemeMode, install_arc_theme};
1435    use gpui_kit::{Context, Render, TestAppContext, test::TestWindowExt as _};
1436
1437    use super::*;
1438
1439    #[test]
1440    fn slider_parts_of_keys_digits_by_place_and_symbols_by_side() {
1441        let parts = slider_parts_of("$950");
1442        assert_eq!(
1443            parts,
1444            vec![
1445                ("p0$".to_string(), None),
1446                ("d2".to_string(), Some(9)),
1447                ("d1".to_string(), Some(5)),
1448                ("d0".to_string(), Some(0)),
1449            ]
1450        );
1451        let grown = slider_parts_of("$1,000");
1452        assert_eq!(
1453            grown,
1454            vec![
1455                ("p0$".to_string(), None),
1456                ("d3".to_string(), Some(1)),
1457                ("g3,".to_string(), None),
1458                ("d2".to_string(), Some(0)),
1459                ("d1".to_string(), Some(0)),
1460                ("d0".to_string(), Some(0)),
1461            ]
1462        );
1463    }
1464
1465    #[test]
1466    fn slider_snap_settles_on_grid_and_respects_range_gap() {
1467        assert!((slider_snap(52.3, 0.0, 100.0, 1.0, 0) - 52.0).abs() < 1e-4);
1468        assert!((slider_snap(2.34, 0.0, 10.0, 0.25, 2) - 2.25).abs() < 1e-4);
1469
1470        // Range gap: thumb 1 cannot cross below thumb 0 + gap, thumb 0 not above thumb 1 - gap.
1471        let settle = move |index: usize, input: f32, cur: &[f32]| -> f32 {
1472            let (low, high) = if index == 1 {
1473                (cur[0] + 10.0, 100.0)
1474            } else {
1475                (0.0, cur[1] - 10.0)
1476            };
1477            slider_snap(input, 0.0, 100.0, 1.0, 0).clamp(low, high)
1478        };
1479        assert!((settle(1, 5.0, &[20.0, 80.0]) - 30.0).abs() < 1e-4);
1480        assert!((settle(0, 90.0, &[20.0, 80.0]) - 70.0).abs() < 1e-4);
1481    }
1482
1483    #[test]
1484    fn slider_release_momentum_carries_at_most_one_coarse_step() {
1485        // velocity 600 pct/s projects to 59.4 pct; a 50-pct step clamps it to one step.
1486        assert!((slider_project_velocity(600.0) - 59.4).abs() < 1e-3);
1487        let step_pct = 50.0_f32;
1488        let carry = slider_project_velocity(600.0).clamp(-step_pct, step_pct);
1489        assert!((carry - 50.0).abs() < 1e-4);
1490    }
1491
1492    #[test]
1493    fn slider_glyph_opacity_fades_by_wheel_distance() {
1494        assert!((slider_glyph_opacity(0.0) - 1.0).abs() < 1e-5);
1495        assert!(slider_glyph_opacity(0.5) > 0.5);
1496        assert_eq!(slider_glyph_opacity(1.0), 0.0);
1497    }
1498
1499    #[test]
1500    fn slider_format_default_groups_thousands() {
1501        assert_eq!(slider_format_default(1000.0, 0), "1,000");
1502        assert_eq!(slider_format_default(1234567.0, 0), "1,234,567");
1503        assert_eq!(slider_format_default(12.5, 2), "12.50");
1504        assert_eq!(slider_format_default(-500.0, 0), "-500");
1505    }
1506
1507    struct SliderHost {
1508        value: SliderValue,
1509        events: Rc<RefCell<Vec<String>>>,
1510        commits: Rc<RefCell<Vec<String>>>,
1511        disabled: bool,
1512    }
1513
1514    impl Render for SliderHost {
1515        fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1516            let events = self.events.clone();
1517            let commits = self.commits.clone();
1518            div().w(px(480.0)).p(px(16.0)).child(
1519                Slider::new("slider-test", "Volume")
1520                    .min(0.0)
1521                    .max(100.0)
1522                    .step(10.0)
1523                    .value(self.value)
1524                    .marks([
1525                        SliderMark::with_label(10.0, "10"),
1526                        SliderMark::with_label(50.0, "50"),
1527                        SliderMark::with_label(90.0, "90"),
1528                    ])
1529                    .disabled(self.disabled)
1530                    .on_value_change(cx.listener({
1531                        let events = events.clone();
1532                        move |this, v: &SliderValue, _, cx| {
1533                            if let SliderValue::Single(x) = v {
1534                                events.borrow_mut().push(format!("{x}"));
1535                                this.value = SliderValue::Single(*x);
1536                                cx.notify();
1537                            }
1538                        }
1539                    }))
1540                    .on_value_commit(cx.listener({
1541                        let commits = commits.clone();
1542                        move |this, v: &SliderValue, _, cx| {
1543                            if let SliderValue::Single(x) = v {
1544                                commits.borrow_mut().push(format!("{x}"));
1545                                this.value = SliderValue::Single(*x);
1546                                cx.notify();
1547                            }
1548                        }
1549                    })),
1550            )
1551        }
1552    }
1553
1554    fn slider_element(name: &str) -> ElementId {
1555        ElementId::NamedChild(ElementId::Name("slider-test".into()).into(), name.into())
1556    }
1557
1558    #[gpui_kit::test]
1559    fn slider_keyboard_steps_commits_and_marks_jump(cx: &mut TestAppContext) {
1560        cx.update(|cx| {
1561            gpui_kit::init(cx);
1562            install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
1563        });
1564
1565        let host = SliderHost {
1566            value: SliderValue::Single(50.0),
1567            events: Rc::new(RefCell::new(Vec::new())),
1568            commits: Rc::new(RefCell::new(Vec::new())),
1569            disabled: false,
1570        };
1571        let events = host.events.clone();
1572        let commits = host.commits.clone();
1573        let (view, cx) = cx.add_window_view(|_, _| host);
1574
1575        cx.update(|window, cx| {
1576            window.render_frame(cx);
1577            let thumb = window.find(slider_element("thumb-0"));
1578            assert_eq!(thumb.role(), Some(Role::Slider));
1579
1580            // Focus the thumb, then ArrowUp steps by the grid; a commit fires too.
1581            window.click(slider_element("thumb-0"), cx);
1582            window.press("up", cx);
1583        });
1584        assert_eq!(events.borrow().last().map(String::as_str), Some("60"));
1585        assert_eq!(commits.borrow().last().map(String::as_str), Some("60"));
1586
1587        cx.update(|window, cx| {
1588            // Shift+ArrowUp takes the large step (default = a tenth of the range = 10, but the
1589            // grid step is 10 here, so this lands two steps up: 60 + 10 = 70? No — large = 10).
1590            window.press("shift-up", cx);
1591        });
1592        assert_eq!(events.borrow().last().map(String::as_str), Some("70"));
1593
1594        cx.update(|window, cx| {
1595            // PageDown takes the large step down.
1596            window.press("pagedown", cx);
1597        });
1598        assert_eq!(events.borrow().last().map(String::as_str), Some("60"));
1599
1600        // Clicking a mark label jumps the nearest thumb there.
1601        cx.update(|window, cx| {
1602            window.click(slider_element("mark-90"), cx);
1603        });
1604        assert_eq!(events.borrow().last().map(String::as_str), Some("90"));
1605
1606        // Disabled swallows keys.
1607        view.update(cx, |host, cx| {
1608            host.disabled = true;
1609            cx.notify();
1610        });
1611        cx.update(|window, cx| {
1612            window.render_frame(cx);
1613            window.press("up", cx);
1614        });
1615        assert_eq!(events.borrow().last().map(String::as_str), Some("90"));
1616    }
1617
1618    #[gpui_kit::test]
1619    fn slider_reduced_motion_steps_instantly(cx: &mut TestAppContext) {
1620        cx.update(|cx| {
1621            gpui_kit::init(cx);
1622            install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
1623            arc_motion::set_reduced_motion(arc_motion::ReducedMotionChoice::Reduce, cx);
1624        });
1625
1626        let host = SliderHost {
1627            value: SliderValue::Single(20.0),
1628            events: Rc::new(RefCell::new(Vec::new())),
1629            commits: Rc::new(RefCell::new(Vec::new())),
1630            disabled: false,
1631        };
1632        let events = host.events.clone();
1633        let (_view, cx) = cx.add_window_view(|_, _| host);
1634
1635        cx.update(|window, cx| {
1636            window.render_frame(cx);
1637            window.click(slider_element("thumb-0"), cx);
1638            window.press("up", cx);
1639        });
1640        assert_eq!(events.borrow().last().map(String::as_str), Some("30"));
1641    }
1642}