Skip to main content

gpui_base/
slider.rs

1use crate::TestSupportExt as _;
2use crate::ValueMapping;
3use std::ops::Range;
4
5use gpui::{
6    AccessibleAction, Along, AnyElement, App, AppContext as _, Axis, Bounds, Context, Div,
7    DragMoveEvent, Empty, Entity, EntityId, EventEmitter, FocusHandle, HitboxBehavior,
8    InteractiveElement, IntoElement, KeyDownEvent, Keystroke, MouseButton, MouseDownEvent,
9    Orientation, ParentElement, Pixels, Point, Render, RenderOnce, Role, SharedString,
10    StatefulInteractiveElement, StyleRefinement, Styled, TouchDragEvent, TouchPhase, Window,
11    accesskit::ActionData, div, prelude::FluentBuilder as _, px,
12};
13
14use crate::{
15    LayoutDirection, a11y_disabled::A11yDisabledExt as _, element_ext::ElementExt,
16    geometry::AxisExt,
17};
18
19/// Events emitted by the [`SliderState`].
20pub enum SliderEvent {
21    /// Emitted continuously while the slider value is being changed by the user.
22    Change(SliderValue),
23    /// Emitted once when the user releases the slider after a drag or click, and after
24    /// each step from the keyboard or an assistive technology.
25    Release(SliderValue),
26}
27
28/// The value of the slider, can be a single value or a range of values.
29///
30/// - Can from a f32 value, which will be treated as a single value.
31/// - Or from a (f32, f32) tuple, which will be treated as a range of values.
32///
33/// The default value is `SliderValue::Single(0.0)`.
34#[derive(Clone, Copy, Debug, PartialEq)]
35pub enum SliderValue {
36    Single(f32),
37    Range(f32, f32),
38}
39
40impl std::fmt::Display for SliderValue {
41    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
42        match self {
43            SliderValue::Single(value) => write!(f, "{}", value),
44            SliderValue::Range(start, end) => write!(f, "{}..{}", start, end),
45        }
46    }
47}
48
49impl From<f32> for SliderValue {
50    fn from(value: f32) -> Self {
51        SliderValue::Single(value)
52    }
53}
54
55impl From<(f32, f32)> for SliderValue {
56    fn from(value: (f32, f32)) -> Self {
57        SliderValue::Range(value.0, value.1)
58    }
59}
60
61impl From<Range<f32>> for SliderValue {
62    fn from(value: Range<f32>) -> Self {
63        SliderValue::Range(value.start, value.end)
64    }
65}
66
67impl Default for SliderValue {
68    fn default() -> Self {
69        SliderValue::Single(0.)
70    }
71}
72
73impl SliderValue {
74    /// Clamp the value to the given range.
75    pub fn clamp(self, min: f32, max: f32) -> Self {
76        match self {
77            SliderValue::Single(value) => SliderValue::Single(value.clamp(min, max)),
78            SliderValue::Range(start, end) => {
79                SliderValue::Range(start.clamp(min, max), end.clamp(min, max))
80            }
81        }
82    }
83
84    /// Check if the value is a single value.
85    #[inline]
86    pub fn is_single(&self) -> bool {
87        matches!(self, SliderValue::Single(_))
88    }
89
90    /// Check if the value is a range of values.
91    #[inline]
92    pub fn is_range(&self) -> bool {
93        matches!(self, SliderValue::Range(_, _))
94    }
95
96    /// Get the start value.
97    pub fn start(&self) -> f32 {
98        match self {
99            SliderValue::Single(value) => *value,
100            SliderValue::Range(start, _) => *start,
101        }
102    }
103
104    /// Get the end value.
105    pub fn end(&self) -> f32 {
106        match self {
107            SliderValue::Single(value) => *value,
108            SliderValue::Range(_, end) => *end,
109        }
110    }
111
112    fn set_start(&mut self, value: f32) {
113        if let SliderValue::Range(_, end) = self {
114            *self = SliderValue::Range(value.min(*end), *end);
115        } else {
116            *self = SliderValue::Single(value);
117        }
118    }
119
120    fn set_end(&mut self, value: f32) {
121        if let SliderValue::Range(start, _) = self {
122            *self = SliderValue::Range(*start, value.max(*start));
123        } else {
124            *self = SliderValue::Single(value);
125        }
126    }
127}
128
129/// Deprecated: use [`ValueMapping`] and [`SliderState::mapping`] instead.
130#[deprecated(note = "use `ValueMapping` with `SliderState::mapping`")]
131#[allow(deprecated)]
132#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
133pub enum SliderScale {
134    #[default]
135    Linear,
136    Logarithmic,
137}
138
139#[allow(deprecated)]
140impl SliderScale {
141    #[inline]
142    pub fn is_linear(&self) -> bool {
143        matches!(self, SliderScale::Linear)
144    }
145
146    #[inline]
147    pub fn is_logarithmic(&self) -> bool {
148        matches!(self, SliderScale::Logarithmic)
149    }
150}
151
152#[allow(deprecated)]
153impl From<SliderScale> for ValueMapping {
154    fn from(scale: SliderScale) -> Self {
155        match scale {
156            SliderScale::Linear => Self::Linear,
157            SliderScale::Logarithmic => Self::Logarithmic,
158        }
159    }
160}
161
162/// State of the [`Slider`].
163pub struct SliderState {
164    min: f32,
165    max: f32,
166    step: f32,
167    value: SliderValue,
168    /// When is single value mode, only `end` is used, the start is always 0.0.
169    percentage: Range<f32>,
170    /// The bounds of the slider after rendered.
171    bounds: Bounds<Pixels>,
172    mapping: ValueMapping,
173    /// Tracks whether the user is currently interacting with the slider so we
174    /// only emit [`SliderEvent::Release`] after a real press/drag.
175    dragging: bool,
176    /// The touch drag this slider claimed, while one is live.
177    touch_drag: Option<TouchDrag>,
178}
179
180/// A touch drag claimed by a slider.
181#[derive(Clone, Copy)]
182struct TouchDrag {
183    /// Identifies the gesture: every event of one drag carries the same start.
184    start_position: Point<Pixels>,
185    /// Whether it moves the range start thumb.
186    is_start: bool,
187}
188
189impl SliderState {
190    /// Create a new [`SliderState`].
191    pub fn new() -> Self {
192        Self {
193            min: 0.0,
194            max: 100.0,
195            step: 1.0,
196            value: SliderValue::default(),
197            percentage: (0.0..0.0),
198            bounds: Bounds::default(),
199            mapping: ValueMapping::default(),
200            dragging: false,
201            touch_drag: None,
202        }
203    }
204
205    /// Set the minimum value of the slider, default: 0.0
206    pub fn min(mut self, min: f32) -> Self {
207        if self.mapping.is_logarithmic() {
208            assert!(
209                min > 0.0,
210                "`min` must be greater than 0 for a logarithmic mapping"
211            );
212            assert!(
213                min < self.max,
214                "`min` must be less than `max` for a logarithmic mapping"
215            );
216        }
217        self.min = min;
218        self.update_thumb_pos();
219        self
220    }
221
222    /// Set the maximum value of the slider, default: 100.0
223    pub fn max(mut self, max: f32) -> Self {
224        if self.mapping.is_logarithmic() {
225            assert!(
226                max > self.min,
227                "`max` must be greater than `min` for a logarithmic mapping"
228            );
229        }
230        self.max = max;
231        self.update_thumb_pos();
232        self
233    }
234
235    /// Set the step value of the slider, default: 1.0
236    pub fn step(mut self, step: f32) -> Self {
237        self.step = step;
238        self
239    }
240
241    /// Set how the slider maps its position to a value, default:
242    /// [`ValueMapping::Linear`].
243    ///
244    /// A logarithmic mapping asserts that `min` is greater than zero and below
245    /// `max`.
246    ///
247    /// # Example
248    ///
249    /// A frequency slider over 20 Hz to 20 kHz, even across three decades:
250    ///
251    /// ```
252    /// use gpui_base::{ValueMapping, slider::SliderState};
253    ///
254    /// let slider = SliderState::new()
255    ///     .min(20.0)
256    ///     .max(20_000.0)
257    ///     .mapping(ValueMapping::custom(
258    ///         |hz| (hz / 20.0).log(1000.0),
259    ///         |percentage| 20.0 * 1000.0_f32.powf(percentage),
260    ///     ));
261    /// ```
262    pub fn mapping(mut self, mapping: impl Into<ValueMapping>) -> Self {
263        let mapping = mapping.into();
264        if mapping.is_logarithmic() {
265            assert!(
266                self.min > 0.0,
267                "`min` must be greater than 0 for a logarithmic mapping"
268            );
269            assert!(
270                self.max > self.min,
271                "`max` must be greater than `min` for a logarithmic mapping"
272            );
273        }
274        self.mapping = mapping;
275        self.update_thumb_pos();
276        self
277    }
278
279    /// Deprecated: use [`mapping`](Self::mapping) with [`ValueMapping`].
280    #[deprecated(note = "use `mapping` with `ValueMapping`")]
281    #[allow(deprecated)]
282    pub fn scale(self, scale: SliderScale) -> Self {
283        self.mapping(scale)
284    }
285
286    /// Set the default value of the slider, default: 0.0
287    pub fn default_value(mut self, value: impl Into<SliderValue>) -> Self {
288        self.value = value.into();
289        self.update_thumb_pos();
290        self
291    }
292
293    /// Set the value of the slider.
294    pub fn set_value(
295        &mut self,
296        value: impl Into<SliderValue>,
297        _: &mut Window,
298        cx: &mut Context<Self>,
299    ) {
300        self.value = value.into();
301        self.update_thumb_pos();
302        cx.notify();
303    }
304
305    /// Get the value of the slider.
306    pub fn value(&self) -> SliderValue {
307        self.value
308    }
309
310    /// Get the minimum value.
311    pub fn min_value(&self) -> f32 {
312        self.min
313    }
314
315    /// Get the maximum value.
316    pub fn max_value(&self) -> f32 {
317        self.max
318    }
319
320    /// Get the step value.
321    pub fn step_value(&self) -> f32 {
322        self.step
323    }
324
325    /// The amount an assistive technology's Increment and Decrement move a thumb, and the
326    /// step reported to it: the step, or a hundredth of the range for a step that is not a
327    /// positive finite number (a continuous slider).
328    pub fn accessibility_step(&self) -> f32 {
329        if is_step(self.step) {
330            self.step
331        } else {
332            (self.max - self.min) / 100.
333        }
334    }
335
336    /// Converts a value between 0.0 and 1.0 to a value between the minimum and maximum value,
337    /// depending on the chosen mapping.
338    fn percentage_to_value(&self, percentage: f32) -> f32 {
339        match &self.mapping {
340            ValueMapping::Linear => self.min + (self.max - self.min) * percentage,
341            ValueMapping::Logarithmic => {
342                // when percentage is 0, this simplifies to (max/min)^0 * min = 1 * min = min
343                // when percentage is 1, this simplifies to (max/min)^1 * min = (max*min)/min = max
344                // we clamp just to make sure we don't have issue with floating point precision
345                let base = self.max / self.min;
346                (base.powf(percentage) * self.min).clamp(self.min, self.max)
347            }
348            ValueMapping::Custom {
349                from_normalized, ..
350            } => {
351                let percentage = if percentage.is_finite() {
352                    percentage.clamp(0.0, 1.0)
353                } else {
354                    0.0
355                };
356                let value = from_normalized(percentage);
357                if value.is_finite() {
358                    // Not `clamp`: while a builder is between its `min` and `max`,
359                    // `min` can stand above `max`.
360                    value.min(self.max).max(self.min)
361                } else {
362                    self.min
363                }
364            }
365        }
366    }
367
368    /// Converts a value between the minimum and maximum value to a value between 0.0 and 1.0,
369    /// depending on the chosen mapping.
370    fn value_to_percentage(&self, value: f32) -> f32 {
371        match &self.mapping {
372            ValueMapping::Linear => {
373                let range = self.max - self.min;
374                if range <= 0.0 {
375                    0.0
376                } else {
377                    (value - self.min) / range
378                }
379            }
380            ValueMapping::Logarithmic => {
381                let base = self.max / self.min;
382                (value / self.min).log(base).clamp(0.0, 1.0)
383            }
384            ValueMapping::Custom { to_normalized, .. } => {
385                // Not `clamp`: while a builder is between its `min` and `max`,
386                // `min` can stand above `max`.
387                let value = if value.is_finite() {
388                    value.min(self.max).max(self.min)
389                } else {
390                    self.min
391                };
392                let percentage = to_normalized(value);
393                if percentage.is_finite() {
394                    percentage.clamp(0.0, 1.0)
395                } else {
396                    0.0
397                }
398            }
399        }
400    }
401
402    fn update_thumb_pos(&mut self) {
403        match self.value {
404            SliderValue::Single(value) => {
405                let percentage = self.value_to_percentage(value.min(self.max).max(self.min));
406                self.percentage = 0.0..percentage;
407            }
408            SliderValue::Range(start, end) => {
409                // Not `clamp`: while a builder is between its `min` and `max`, `min`
410                // can stand above `max`.
411                let clamped_start = start.min(self.max).max(self.min);
412                let clamped_end = end.min(self.max).max(self.min);
413                self.percentage =
414                    self.value_to_percentage(clamped_start)..self.value_to_percentage(clamped_end);
415            }
416        }
417    }
418
419    /// Update value by mouse position
420    #[doc(hidden)]
421    pub fn update_value_by_position(
422        &mut self,
423        axis: Axis,
424        position: Point<Pixels>,
425        is_start: bool,
426        _: &mut Window,
427        cx: &mut Context<Self>,
428    ) {
429        self.dragging = true;
430        let bounds = self.bounds;
431        let step = self.step;
432
433        let inner_pos = self.offset_along(axis, position, cx);
434        let total_size = bounds.size.along(axis);
435        let percentage = inner_pos.clamp(px(0.), total_size) / total_size;
436
437        let percentage = if is_start {
438            percentage.clamp(0.0, self.percentage.end)
439        } else {
440            percentage.clamp(self.percentage.start, 1.0)
441        };
442
443        let value = self.percentage_to_value(percentage);
444        let value = snap_to_step(value, self.min, self.max, step);
445
446        if is_start {
447            self.value.set_start(value);
448        } else {
449            self.value.set_end(value);
450        }
451        // The thumb stands at the value, on its step, not at the pointer.
452        self.update_thumb_pos();
453        cx.emit(SliderEvent::Change(self.value));
454        cx.notify();
455    }
456
457    /// Moves the end thumb or, with `start`, a range's start thumb by `delta`, as a key and
458    /// an assistive technology's Increment and Decrement do, and emits
459    /// [`SliderEvent::Change`] then [`SliderEvent::Release`] if it moved. The thumb lands
460    /// on the step grid counted from `min` and stops at the other thumb and at the
461    /// slider's ends.
462    #[doc(hidden)]
463    pub fn step_thumb(
464        &mut self,
465        start: bool,
466        delta: f32,
467        window: &mut Window,
468        cx: &mut Context<Self>,
469    ) {
470        // A NaN never equals itself, so it would read as a change below.
471        if !steppable(self.value, self.min, self.max) {
472            return;
473        }
474        let value = step_thumb(self.value, start, delta, self.min, self.max, self.step);
475        self.commit_thumb_value(value, window, cx);
476    }
477
478    fn handle_accessibility_set_value(
479        &mut self,
480        data: Option<&ActionData>,
481        window: &mut Window,
482        cx: &mut Context<Self>,
483    ) {
484        let Some(ActionData::NumericValue(target)) = data else {
485            return;
486        };
487        if !target.is_finite() || !steppable(self.value, self.min, self.max) {
488            return;
489        }
490        let value = thumb_value_at(
491            self.value,
492            false,
493            *target as f32,
494            self.min,
495            self.max,
496            self.step,
497        );
498        self.commit_thumb_value(value, window, cx);
499    }
500
501    fn commit_thumb_value(
502        &mut self,
503        value: SliderValue,
504        window: &mut Window,
505        cx: &mut Context<Self>,
506    ) {
507        if value != self.value {
508            self.set_value(value, window, cx);
509            cx.emit(SliderEvent::Change(value));
510            // A keyboard or accessibility adjustment is a complete gesture.
511            cx.emit(SliderEvent::Release(value));
512        }
513    }
514
515    /// Whether `position` is closer to the range start thumb than to the end thumb.
516    fn is_nearer_start(&self, axis: Axis, position: Point<Pixels>, cx: &App) -> bool {
517        let size = self.bounds.size.along(axis);
518        let along = self.offset_along(axis, position, cx);
519        let center =
520            ((self.percentage.end - self.percentage.start) / 2. + self.percentage.start) * size;
521        along < center
522    }
523
524    /// How far `position` is from the minimum end: the start edge of a
525    /// horizontal slider (the right in RTL) or the bottom of a vertical one.
526    fn offset_along(&self, axis: Axis, position: Point<Pixels>, cx: &App) -> Pixels {
527        if axis.is_vertical() {
528            self.bounds.bottom() - position.y
529        } else if LayoutDirection::global(cx).is_rtl() {
530            self.bounds.right() - position.x
531        } else {
532            position.x - self.bounds.left()
533        }
534    }
535
536    /// Emit [`SliderEvent::Release`] if the user was actively interacting
537    /// with the slider. Called on mouse-up both inside and outside the slider.
538    #[doc(hidden)]
539    pub fn handle_release(&mut self, cx: &mut Context<Self>) {
540        if !self.dragging {
541            return;
542        }
543        self.dragging = false;
544        cx.emit(SliderEvent::Release(self.value));
545    }
546}
547
548/// Steps Page Up and Page Down move the thumb.
549const PAGE_STEPS: f32 = 10.;
550
551/// How far a key moves the thumb: an arrow `step`, Page Up and Page Down ten of them, Home
552/// and End the whole `range`. `None` for any other key and for a key held with a modifier.
553fn key_delta(keystroke: &Keystroke, axis: Axis, rtl: bool, step: f32, range: f32) -> Option<f32> {
554    if keystroke.modifiers.modified() {
555        return None;
556    }
557    // A horizontal slider grows to the left in a right-to-left layout.
558    let toward_end = if axis.is_horizontal() && rtl {
559        -step
560    } else {
561        step
562    };
563    match keystroke.key.as_str() {
564        "right" => Some(toward_end),
565        "left" => Some(-toward_end),
566        "up" => Some(step),
567        "down" => Some(-step),
568        "pageup" => Some(step * PAGE_STEPS),
569        "pagedown" => Some(-step * PAGE_STEPS),
570        "home" => Some(-range),
571        "end" => Some(range),
572        _ => None,
573    }
574}
575
576/// Whether `step` divides the range into steps: a positive finite number.
577fn is_step(step: f32) -> bool {
578    step > 0. && step.is_finite()
579}
580
581/// `value` on the nearest step counted from `min`, kept inside the range. A step that is
582/// not a positive finite number leaves the value continuous.
583fn snap_to_step(value: f32, min: f32, max: f32, step: f32) -> f32 {
584    if !is_step(step) {
585        return value;
586    }
587    (min + ((value - min) / step).round() * step)
588        .min(max)
589        .max(min)
590}
591
592/// Whether `value` can be stepped inside `min..=max`: not for a NaN value or bound, a
593/// `min` above `max`, or a range whose start is past its end.
594fn steppable(value: SliderValue, min: f32, max: f32) -> bool {
595    let (start, end) = (value.start(), value.end());
596    min <= max && !start.is_nan() && !end.is_nan() && (!value.is_range() || start <= end)
597}
598
599/// `value` with its end, or with `start` a range's start, moved by `delta` and snapped to
600/// `step` counted from `min`, inside `min..=max` and without passing the other thumb. A
601/// value that is not [`steppable`] comes back unchanged.
602fn step_thumb(
603    value: SliderValue,
604    start: bool,
605    delta: f32,
606    min: f32,
607    max: f32,
608    step: f32,
609) -> SliderValue {
610    if !steppable(value, min, max) {
611        return value;
612    }
613    let current = if start && value.is_range() {
614        value.start()
615    } else {
616        value.end()
617    };
618    thumb_value_at(value, start, current + delta, min, max, step)
619}
620
621fn thumb_value_at(
622    mut value: SliderValue,
623    start: bool,
624    target: f32,
625    min: f32,
626    max: f32,
627    step: f32,
628) -> SliderValue {
629    let next = snap_to_step(target, min, max, step).min(max).max(min);
630    if start && value.is_range() {
631        value.set_start(next);
632    } else {
633        value.set_end(next);
634    }
635    value
636}
637
638#[derive(Clone)]
639struct DragThumb((EntityId, bool));
640
641impl Render for DragThumb {
642    fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
643        Empty
644    }
645}
646
647#[derive(Clone)]
648struct DragSlider(EntityId);
649
650impl Render for DragSlider {
651    fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
652        Empty
653    }
654}
655
656/// An unstyled slider behavior root.
657///
658/// Applications provide the track, range, and thumb presentation as children.
659#[derive(IntoElement)]
660pub struct Slider {
661    state: Entity<SliderState>,
662    axis: Axis,
663    disabled: bool,
664    accessibility_label: Option<SharedString>,
665    focus: Option<FocusHandle>,
666    base: Div,
667    children: Vec<AnyElement>,
668}
669
670impl Slider {
671    pub fn new(state: &Entity<SliderState>) -> Self {
672        Self {
673            state: state.clone(),
674            axis: Axis::Horizontal,
675            disabled: false,
676            accessibility_label: None,
677            focus: None,
678            base: div(),
679            children: Vec::new(),
680        }
681    }
682
683    pub fn horizontal(mut self) -> Self {
684        self.axis = Axis::Horizontal;
685        self
686    }
687
688    pub fn vertical(mut self) -> Self {
689        self.axis = Axis::Vertical;
690        self
691    }
692
693    pub fn axis(mut self, axis: Axis) -> Self {
694        self.axis = axis;
695        self
696    }
697
698    pub fn disabled(mut self, disabled: bool) -> Self {
699        self.disabled = disabled;
700        self
701    }
702
703    /// Sets the label exposed to accessibility clients.
704    pub fn accessibility_label(mut self, label: impl Into<SharedString>) -> Self {
705        self.accessibility_label = Some(label.into());
706        self
707    }
708
709    /// Makes the slider's accessibility node itself focusable with `focus`,
710    /// so keyboard focus and assistive technology land on the slider. While
711    /// it has focus, the arrow keys move the end thumb a step, Page Up and
712    /// Page Down ten steps, and Home and End to the slider's ends.
713    pub fn track_focus(mut self, focus: &FocusHandle) -> Self {
714        self.focus = Some(focus.clone());
715        self
716    }
717}
718
719impl ParentElement for Slider {
720    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
721        self.children.extend(elements);
722    }
723}
724
725impl Styled for Slider {
726    fn style(&mut self) -> &mut StyleRefinement {
727        self.base.style()
728    }
729}
730
731impl RenderOnce for Slider {
732    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
733        let axis = self.axis;
734        let entity_id = self.state.entity_id();
735        let state = self.state.read(cx);
736        let slider_state = self.state.clone();
737
738        self.base
739            .id(("slider", entity_id))
740            .test_support()
741            .when_some(self.focus, |this, focus| this.track_focus(&focus))
742            .role(Role::Slider)
743            .when_some(self.accessibility_label, |this, label| {
744                this.aria_label(label)
745            })
746            .aria_numeric_value(state.value().end() as f64)
747            .aria_min_numeric_value(state.min_value() as f64)
748            .aria_max_numeric_value(state.max_value() as f64)
749            .aria_numeric_value_step(state.accessibility_step() as f64)
750            .aria_orientation(if axis.is_vertical() {
751                Orientation::Vertical
752            } else {
753                Orientation::Horizontal
754            })
755            // A disabled slider takes no value, from the pointer or from
756            // assistive technology.
757            .when(!self.disabled, |this| {
758                this.on_a11y_action(AccessibleAction::Increment, {
759                    let state = slider_state.clone();
760                    move |_, window, cx| {
761                        state.update(cx, |state, cx| {
762                            state.step_thumb(false, state.accessibility_step(), window, cx);
763                        });
764                    }
765                })
766                .on_a11y_action(AccessibleAction::Decrement, {
767                    let state = slider_state.clone();
768                    move |_, window, cx| {
769                        state.update(cx, |state, cx| {
770                            state.step_thumb(false, -state.accessibility_step(), window, cx);
771                        });
772                    }
773                })
774                .on_a11y_action(AccessibleAction::SetValue, {
775                    let state = slider_state.clone();
776                    move |data, window, cx| {
777                        state.update(cx, |state, cx| {
778                            state.handle_accessibility_set_value(data, window, cx);
779                        });
780                    }
781                })
782                // Keys reach the slider only while its `track_focus` handle has focus.
783                .on_key_down({
784                    let state = slider_state.clone();
785                    move |event: &KeyDownEvent, window, cx| {
786                        let rtl = LayoutDirection::global(cx).is_rtl();
787                        state.update(cx, |state, cx| {
788                            let step = state.accessibility_step();
789                            let range = state.max - state.min;
790                            let Some(delta) = key_delta(&event.keystroke, axis, rtl, step, range)
791                            else {
792                                return;
793                            };
794                            state.step_thumb(false, delta, window, cx);
795                            cx.stop_propagation();
796                        });
797                    }
798                })
799                .on_mouse_up(
800                    MouseButton::Left,
801                    window.listener_for(&self.state, |state, _, _, cx| state.handle_release(cx)),
802                )
803                .on_mouse_up_out(
804                    MouseButton::Left,
805                    window.listener_for(&self.state, |state, _, _, cx| state.handle_release(cx)),
806                )
807            })
808            .children(self.children)
809            .a11y_disabled(self.disabled)
810    }
811}
812
813/// An unstyled track that records the geometry used to map pointer positions.
814#[derive(IntoElement)]
815pub struct SliderTrack {
816    state: Entity<SliderState>,
817    axis: Axis,
818    disabled: bool,
819    base: Div,
820    children: Vec<AnyElement>,
821}
822
823impl SliderTrack {
824    pub fn new(state: &Entity<SliderState>) -> Self {
825        Self {
826            state: state.clone(),
827            axis: Axis::Horizontal,
828            disabled: false,
829            base: div(),
830            children: Vec::new(),
831        }
832    }
833
834    pub fn axis(mut self, axis: Axis) -> Self {
835        self.axis = axis;
836        self
837    }
838    pub fn disabled(mut self, disabled: bool) -> Self {
839        self.disabled = disabled;
840        self
841    }
842}
843
844impl ParentElement for SliderTrack {
845    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
846        self.children.extend(elements);
847    }
848}
849
850impl Styled for SliderTrack {
851    fn style(&mut self) -> &mut StyleRefinement {
852        self.base.style()
853    }
854}
855
856impl InteractiveElement for SliderTrack {
857    fn interactivity(&mut self) -> &mut gpui::Interactivity {
858        self.base.interactivity()
859    }
860}
861
862impl RenderOnce for SliderTrack {
863    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
864        let axis = self.axis;
865        let entity_id = self.state.entity_id();
866        let state = self.state.read(cx);
867        let is_range = state.value().is_range();
868        // Touch: GPUI routes a finger drag to `TouchDragEvent` (claimed with
869        // `prevent_default`) or to scrolling; `on_drag` below is mouse-only. Claim
870        // drags that start on the track, as the scrollbar thumb does.
871        let touch_layer = (!self.disabled).then(|| {
872            let slider_state = self.state.clone();
873            gpui::canvas(
874                |bounds, window, _| window.insert_hitbox(bounds, HitboxBehavior::Normal),
875                move |_, hitbox, window, _| {
876                    let slider_state = slider_state.clone();
877                    window.on_mouse_event(move |event: &TouchDragEvent, phase, window, cx| {
878                        if !phase.bubble() {
879                            return;
880                        }
881                        slider_state.update(cx, |state, cx| {
882                            if event.phase == TouchPhase::Started {
883                                // A drag whose end never arrived (the slider was
884                                // disabled or not painted) ends when another begins.
885                                if state.touch_drag.take().is_some() {
886                                    state.handle_release(cx);
887                                }
888                                // The hitbox, not the bounds, so a layer covering
889                                // the track keeps its own drags.
890                                if window.default_prevented() || !hitbox.is_hovered(window) {
891                                    return;
892                                }
893                                window.prevent_default();
894                                let is_start = is_range
895                                    && state.is_nearer_start(axis, event.start_position, cx);
896                                state.touch_drag = Some(TouchDrag {
897                                    start_position: event.start_position,
898                                    is_start,
899                                });
900                            }
901                            let Some(drag) = state.touch_drag else {
902                                return;
903                            };
904                            if drag.start_position != event.start_position {
905                                return;
906                            }
907                            cx.stop_propagation();
908                            match event.phase {
909                                TouchPhase::Started | TouchPhase::Moved => {
910                                    state.update_value_by_position(
911                                        axis,
912                                        event.position,
913                                        drag.is_start,
914                                        window,
915                                        cx,
916                                    );
917                                }
918                                TouchPhase::Ended | TouchPhase::Cancelled => {
919                                    state.touch_drag = None;
920                                    state.handle_release(cx);
921                                }
922                            }
923                        });
924                    });
925                },
926            )
927            .absolute()
928            .size_full()
929        });
930        self.base
931            .id("slider-bar-container")
932            .test_support()
933            .children(self.children)
934            .children(touch_layer)
935            .when(!self.disabled, |this| {
936                this.on_mouse_down(
937                    MouseButton::Left,
938                    window.listener_for(
939                        &self.state,
940                        move |state, event: &MouseDownEvent, window, cx| {
941                            let is_start =
942                                is_range && state.is_nearer_start(axis, event.position, cx);
943                            state.update_value_by_position(
944                                axis,
945                                event.position,
946                                is_start,
947                                window,
948                                cx,
949                            );
950                        },
951                    ),
952                )
953                .when(!is_range, |this| {
954                    this.on_drag(DragSlider(entity_id), |drag, _, _, cx| {
955                        cx.stop_propagation();
956                        cx.new(|_| drag.clone())
957                    })
958                    .on_drag_move(window.listener_for(
959                        &self.state,
960                        move |state, event: &DragMoveEvent<DragSlider>, window, cx| {
961                            let DragSlider(id) = event.drag(cx);
962                            if *id == entity_id {
963                                state.update_value_by_position(
964                                    axis,
965                                    event.event.position,
966                                    false,
967                                    window,
968                                    cx,
969                                );
970                            }
971                        },
972                    ))
973                })
974            })
975    }
976}
977
978/// An unstyled slider indicator that records the value-mapping bounds.
979#[derive(IntoElement)]
980pub struct SliderIndicator {
981    state: Entity<SliderState>,
982    base: Div,
983    children: Vec<AnyElement>,
984}
985
986impl SliderIndicator {
987    pub fn new(state: &Entity<SliderState>) -> Self {
988        Self {
989            state: state.clone(),
990            base: div(),
991            children: Vec::new(),
992        }
993    }
994}
995
996impl ParentElement for SliderIndicator {
997    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
998        self.children.extend(elements);
999    }
1000}
1001
1002impl Styled for SliderIndicator {
1003    fn style(&mut self) -> &mut StyleRefinement {
1004        self.base.style()
1005    }
1006}
1007
1008impl InteractiveElement for SliderIndicator {
1009    fn interactivity(&mut self) -> &mut gpui::Interactivity {
1010        self.base.interactivity()
1011    }
1012}
1013
1014impl StatefulInteractiveElement for SliderIndicator {}
1015
1016impl RenderOnce for SliderIndicator {
1017    fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
1018        self.base
1019            .id("slider-bar")
1020            .children(self.children)
1021            .on_prepaint({
1022                let state = self.state;
1023                // Only when they moved: with retained views, an update while
1024                // the window draws renders every view that reads the state
1025                // again.
1026                move |bounds, _, cx| {
1027                    if state.read(cx).bounds != bounds {
1028                        state.update(cx, |state, _| state.set_bounds(bounds));
1029                    }
1030                }
1031            })
1032    }
1033}
1034
1035/// An unstyled draggable slider thumb.
1036#[derive(IntoElement)]
1037pub struct SliderThumb {
1038    state: Entity<SliderState>,
1039    axis: Axis,
1040    start: bool,
1041    disabled: bool,
1042    base: Div,
1043    children: Vec<AnyElement>,
1044}
1045
1046impl SliderThumb {
1047    pub fn new(state: &Entity<SliderState>) -> Self {
1048        Self {
1049            state: state.clone(),
1050            axis: Axis::Horizontal,
1051            start: false,
1052            disabled: false,
1053            base: div(),
1054            children: Vec::new(),
1055        }
1056    }
1057
1058    pub fn axis(mut self, axis: Axis) -> Self {
1059        self.axis = axis;
1060        self
1061    }
1062    pub fn start(mut self, start: bool) -> Self {
1063        self.start = start;
1064        self
1065    }
1066    pub fn disabled(mut self, disabled: bool) -> Self {
1067        self.disabled = disabled;
1068        self
1069    }
1070}
1071
1072impl ParentElement for SliderThumb {
1073    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
1074        self.children.extend(elements);
1075    }
1076}
1077
1078impl Styled for SliderThumb {
1079    fn style(&mut self) -> &mut StyleRefinement {
1080        self.base.style()
1081    }
1082}
1083
1084impl InteractiveElement for SliderThumb {
1085    fn interactivity(&mut self) -> &mut gpui::Interactivity {
1086        self.base.interactivity()
1087    }
1088}
1089
1090impl StatefulInteractiveElement for SliderThumb {}
1091
1092impl RenderOnce for SliderThumb {
1093    fn render(self, window: &mut Window, _: &mut App) -> impl IntoElement {
1094        let entity_id = self.state.entity_id();
1095        let axis = self.axis;
1096        let start = self.start;
1097        self.base
1098            .id(("slider-thumb", start as u32))
1099            .test_support()
1100            .children(self.children)
1101            .when(!self.disabled, |this| {
1102                this.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
1103                    .on_drag(DragThumb((entity_id, start)), |drag, _, _, cx| {
1104                        cx.stop_propagation();
1105                        cx.new(|_| drag.clone())
1106                    })
1107                    .on_drag_move(window.listener_for(
1108                        &self.state,
1109                        move |state, event: &DragMoveEvent<DragThumb>, window, cx| {
1110                            let DragThumb((id, start)) = event.drag(cx);
1111                            if *id == entity_id {
1112                                state.update_value_by_position(
1113                                    axis,
1114                                    event.event.position,
1115                                    *start,
1116                                    window,
1117                                    cx,
1118                                );
1119                            }
1120                        },
1121                    ))
1122            })
1123            // A caller can give a thumb a role of its own, as for a range's thumbs.
1124            .a11y_disabled(self.disabled)
1125    }
1126}
1127
1128impl EventEmitter<SliderEvent> for SliderState {}
1129
1130impl SliderState {
1131    #[doc(hidden)]
1132    pub fn percentage(&self) -> Range<f32> {
1133        self.percentage.clone()
1134    }
1135
1136    #[doc(hidden)]
1137    pub fn bounds(&self) -> Bounds<Pixels> {
1138        self.bounds
1139    }
1140
1141    #[doc(hidden)]
1142    pub fn set_bounds(&mut self, bounds: Bounds<Pixels>) {
1143        self.bounds = bounds;
1144    }
1145}
1146
1147#[cfg(test)]
1148mod tests {
1149    use super::*;
1150
1151    #[test]
1152    fn legacy_value_conversions_and_clamping_are_preserved() {
1153        assert_eq!(SliderValue::from(5.), SliderValue::Single(5.));
1154        assert_eq!(SliderValue::from((2., 8.)), SliderValue::Range(2., 8.));
1155        assert_eq!(SliderValue::from(2.0..8.0), SliderValue::Range(2., 8.));
1156        assert_eq!(
1157            SliderValue::Range(-1., 12.).clamp(0., 10.),
1158            SliderValue::Range(0., 10.)
1159        );
1160    }
1161
1162    #[test]
1163    fn legacy_linear_state_keeps_percentage_and_range_ordering() {
1164        let state = SliderState::new()
1165            .min(0.)
1166            .max(200.)
1167            .default_value((50., 150.));
1168        assert_eq!(state.value(), SliderValue::Range(50., 150.));
1169        assert_eq!(state.percentage(), 0.25..0.75);
1170    }
1171
1172    #[test]
1173    #[allow(deprecated)]
1174    fn legacy_logarithmic_state_keeps_mapping() {
1175        let state = SliderState::new()
1176            .min(1.)
1177            .max(1000.)
1178            .scale(SliderScale::Logarithmic)
1179            .default_value(10.);
1180        let percentage = state.percentage().end;
1181        assert!((percentage - (1. / 3.)).abs() < 0.0001);
1182    }
1183
1184    #[test]
1185    #[allow(deprecated)]
1186    fn scale_and_mapping_set_the_same_value_mapping() {
1187        let by_scale = SliderState::new()
1188            .min(1.)
1189            .max(1000.)
1190            .scale(SliderScale::Logarithmic)
1191            .default_value(10.);
1192        let by_mapping = SliderState::new()
1193            .min(1.)
1194            .max(1000.)
1195            .mapping(ValueMapping::Logarithmic)
1196            .default_value(10.);
1197
1198        assert_eq!(by_scale.percentage(), by_mapping.percentage());
1199        assert!((by_mapping.percentage().end - (1. / 3.)).abs() < 0.0001);
1200    }
1201
1202    #[test]
1203    fn custom_mapping_round_trips_a_value_and_its_position() {
1204        let state = SliderState::new()
1205            .min(0.)
1206            .max(100.)
1207            .mapping(ValueMapping::custom(
1208                |value| (value / 100.).sqrt(),
1209                |percentage| percentage * percentage * 100.,
1210            ))
1211            .default_value(25.);
1212
1213        assert!((state.percentage().end - 0.5).abs() < 0.0001);
1214        assert!((state.percentage_to_value(0.5) - 25.).abs() < 0.0001);
1215    }
1216
1217    #[test]
1218    fn custom_mapping_clamps_its_inputs_and_outputs() {
1219        let state = SliderState::new()
1220            .min(0.)
1221            .max(10.)
1222            .mapping(ValueMapping::custom(|_| 2., |_| 1000.))
1223            .default_value(5.);
1224
1225        assert_eq!(state.percentage().end, 1.);
1226        assert_eq!(state.percentage_to_value(0.5), 10.);
1227    }
1228
1229    #[test]
1230    fn custom_mapping_falls_back_from_non_finite_results() {
1231        let state = SliderState::new()
1232            .min(2.)
1233            .max(8.)
1234            .mapping(ValueMapping::custom(|_| f32::NAN, |_| f32::INFINITY))
1235            .default_value(5.);
1236
1237        assert_eq!(state.percentage().end, 0.);
1238        assert_eq!(state.percentage_to_value(0.5), 2.);
1239    }
1240
1241    #[test]
1242    fn custom_mapping_tolerates_builder_bounds_in_any_order() {
1243        // The builder can stand between its `min` and `max`; the custom path
1244        // must not call `f32::clamp`, which panics on an inverted range.
1245        let state = SliderState::new()
1246            .max(0.)
1247            .min(10.)
1248            .mapping(ValueMapping::custom(
1249                |value| value / 10.,
1250                |percentage| percentage * 10.,
1251            ))
1252            .default_value(5.);
1253
1254        assert!(state.percentage().end.is_finite());
1255    }
1256
1257    #[test]
1258    #[should_panic(expected = "`min` must be greater than 0")]
1259    fn logarithmic_mapping_validation_is_preserved() {
1260        let _ = SliderState::new().mapping(ValueMapping::Logarithmic);
1261    }
1262
1263    #[gpui::test]
1264    fn a_disabled_thumb_marks_its_node_disabled(cx: &mut gpui::TestAppContext) {
1265        struct Thumb {
1266            state: Entity<SliderState>,
1267            disabled: bool,
1268        }
1269
1270        impl Render for Thumb {
1271            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1272                SliderThumb::new(&self.state)
1273                    .role(Role::Slider)
1274                    .disabled(self.disabled)
1275            }
1276        }
1277
1278        for disabled in [false, true] {
1279            let (_, cx) = cx.add_window_view(|_, cx| Thumb {
1280                state: cx.new(|_| SliderState::new()),
1281                disabled,
1282            });
1283            cx.update(|window, cx| {
1284                window.draw(cx).clear(cx);
1285                let thumb = crate::test_support::snapshots(window)
1286                    .into_iter()
1287                    .find(|node| node.role() == Some(Role::Slider))
1288                    .expect("a thumb node");
1289                assert_eq!(thumb.disabled(), disabled.then_some(true));
1290            });
1291        }
1292    }
1293
1294    #[gpui::test]
1295    fn a_slider_takes_focus_on_its_own_node(cx: &mut gpui::TestAppContext) {
1296        struct Focusable {
1297            state: Entity<SliderState>,
1298            focus: FocusHandle,
1299        }
1300
1301        impl Render for Focusable {
1302            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1303                Slider::new(&self.state).track_focus(&self.focus)
1304            }
1305        }
1306
1307        let (view, cx) = cx.add_window_view(|_, cx| Focusable {
1308            state: cx.new(|_| SliderState::new()),
1309            focus: cx.focus_handle(),
1310        });
1311        cx.update(|window, cx| {
1312            let focus = view.read(cx).focus.clone();
1313            focus.focus(window, cx);
1314            window.draw(cx).clear(cx);
1315            let slider = crate::test_support::snapshots(window)
1316                .into_iter()
1317                .find(|node| node.role() == Some(Role::Slider))
1318                .expect("a slider node");
1319            assert_eq!(slider.focused(), Some(true));
1320        });
1321    }
1322
1323    #[test]
1324    fn keys_map_to_steps() {
1325        let key = |key: &'static str, axis, rtl| {
1326            key_delta(&Keystroke::parse(key).unwrap(), axis, rtl, 5., 100.)
1327        };
1328        for axis in [Axis::Horizontal, Axis::Vertical] {
1329            assert_eq!(key("right", axis, false), Some(5.));
1330            assert_eq!(key("left", axis, false), Some(-5.));
1331            assert_eq!(key("up", axis, false), Some(5.));
1332            assert_eq!(key("down", axis, false), Some(-5.));
1333            assert_eq!(key("pageup", axis, false), Some(50.));
1334            assert_eq!(key("pagedown", axis, false), Some(-50.));
1335            assert_eq!(key("home", axis, false), Some(-100.));
1336            assert_eq!(key("end", axis, false), Some(100.));
1337            assert_eq!(key("a", axis, false), None);
1338            assert_eq!(key("ctrl-right", axis, false), None);
1339            assert_eq!(key("shift-home", axis, false), None);
1340        }
1341        // Right to left turns only a horizontal slider's left and right.
1342        assert_eq!(key("right", Axis::Horizontal, true), Some(-5.));
1343        assert_eq!(key("left", Axis::Horizontal, true), Some(5.));
1344        assert_eq!(key("up", Axis::Horizontal, true), Some(5.));
1345        assert_eq!(key("right", Axis::Vertical, true), Some(5.));
1346    }
1347
1348    #[gpui::test]
1349    fn a_focused_slider_steps_on_keys_and_reports_each_step(cx: &mut gpui::TestAppContext) {
1350        struct Focusable {
1351            state: Entity<SliderState>,
1352            focus: FocusHandle,
1353            disabled: bool,
1354        }
1355
1356        impl Render for Focusable {
1357            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1358                Slider::new(&self.state)
1359                    .track_focus(&self.focus)
1360                    .disabled(self.disabled)
1361            }
1362        }
1363
1364        let (view, cx) = cx.add_window_view(|_, cx| Focusable {
1365            state: cx.new(|_| SliderState::new().step(5.).default_value(50.)),
1366            focus: cx.focus_handle(),
1367            disabled: false,
1368        });
1369        let state = view.read_with(cx, |view, _| view.state.clone());
1370        let events = std::rc::Rc::new(std::cell::RefCell::new(Vec::new()));
1371        cx.update(|window, cx| {
1372            let events = events.clone();
1373            cx.subscribe(&state, move |_, event: &SliderEvent, _| {
1374                events.borrow_mut().push(match event {
1375                    SliderEvent::Change(value) => ("change", value.end()),
1376                    SliderEvent::Release(value) => ("release", value.end()),
1377                });
1378            })
1379            .detach();
1380            view.read(cx).focus.clone().focus(window, cx);
1381            window.draw(cx).clear(cx);
1382        });
1383
1384        for (key, value) in [
1385            ("right", 55.),
1386            ("left", 50.),
1387            ("up", 55.),
1388            ("down", 50.),
1389            ("pageup", 100.),
1390            ("pagedown", 50.),
1391            ("home", 0.),
1392            ("end", 100.),
1393        ] {
1394            cx.simulate_keystrokes(key);
1395            assert_eq!(
1396                std::mem::take(&mut *events.borrow_mut()),
1397                [("change", value), ("release", value)],
1398                "{key}"
1399            );
1400        }
1401        // At its end, with a modifier, or disabled, a key reports nothing.
1402        cx.simulate_keystrokes("end ctrl-left");
1403        view.update(cx, |view, cx| {
1404            view.disabled = true;
1405            cx.notify();
1406        });
1407        cx.simulate_keystrokes("home");
1408        assert!(events.borrow().is_empty());
1409        assert_eq!(state.read_with(cx, |state, _| state.value().end()), 100.);
1410    }
1411
1412    #[test]
1413    fn min_can_be_set_above_the_default_max_before_max() {
1414        let state = SliderState::new().min(150.).max(200.).default_value(175.);
1415        assert_eq!(state.value(), SliderValue::Single(175.));
1416        assert_eq!(state.percentage(), 0.0..0.5);
1417
1418        let state = SliderState::new()
1419            .default_value((160., 180.))
1420            .min(150.)
1421            .max(200.);
1422        assert_eq!(state.percentage(), 0.2..0.6);
1423    }
1424
1425    #[test]
1426    fn dragging_snaps_from_min() {
1427        // Steps count from `min`: 3 + 5k, not multiples of 5.
1428        assert_eq!(snap_to_step(9.4, 3., 100., 5.), 8.);
1429        assert_eq!(snap_to_step(11., 3., 100., 5.), 13.);
1430        // A step past the end stays inside the range.
1431        assert_eq!(snap_to_step(99., 3., 100., 5.), 98.);
1432        assert_eq!(snap_to_step(100., 0., 99., 10.), 99.);
1433        // A step that is not a positive finite number leaves the value continuous.
1434        assert_eq!(snap_to_step(42.5, 0., 100., 0.), 42.5);
1435        assert_eq!(snap_to_step(42.5, 0., 100., -5.), 42.5);
1436        assert_eq!(snap_to_step(42.5, 0., 100., f32::NAN), 42.5);
1437        assert_eq!(snap_to_step(42.5, 0., 100., f32::INFINITY), 42.5);
1438    }
1439
1440    #[test]
1441    fn accessibility_steps_move_only_the_stepped_thumb() {
1442        assert_eq!(
1443            step_thumb(SliderValue::Range(20., 60.), false, 1., 0., 100., 1.),
1444            SliderValue::Range(20., 61.)
1445        );
1446        assert_eq!(
1447            step_thumb(SliderValue::Range(20., 20.), false, -1., 0., 100., 1.),
1448            SliderValue::Range(20., 20.),
1449            "the end never passes the start"
1450        );
1451        assert_eq!(
1452            step_thumb(SliderValue::Single(99.5), false, 1., 0., 100., 1.),
1453            SliderValue::Single(100.)
1454        );
1455        assert_eq!(
1456            step_thumb(SliderValue::Range(20., 60.), true, -1., 0., 100., 1.),
1457            SliderValue::Range(19., 60.)
1458        );
1459        assert_eq!(
1460            step_thumb(SliderValue::Range(60., 60.), true, 1., 0., 100., 1.),
1461            SliderValue::Range(60., 60.),
1462            "the start never passes the end"
1463        );
1464    }
1465
1466    #[test]
1467    fn accessibility_steps_land_on_the_step_grid() {
1468        assert_eq!(
1469            step_thumb(SliderValue::Single(33.), false, 10., 0., 100., 10.),
1470            SliderValue::Single(40.)
1471        );
1472        assert_eq!(
1473            step_thumb(SliderValue::Single(33.), false, -10., 0., 100., 10.),
1474            SliderValue::Single(20.)
1475        );
1476        assert_eq!(
1477            step_thumb(SliderValue::Single(33.), false, 0.5, 0., 100., 0.),
1478            SliderValue::Single(33.5),
1479            "a continuous slider does not snap"
1480        );
1481    }
1482
1483    #[test]
1484    fn a_continuous_slider_steps_by_a_hundredth_of_its_range() {
1485        for step in [0., -1., f32::NAN] {
1486            let state = SliderState::new().min(0.).max(200.).step(step);
1487            assert_eq!(state.accessibility_step(), 2., "step {step}");
1488        }
1489        assert_eq!(SliderState::new().step(5.).accessibility_step(), 5.);
1490    }
1491
1492    #[test]
1493    fn stepping_leaves_an_invalid_value_or_range_alone() {
1494        let nan = step_thumb(SliderValue::Single(f32::NAN), false, 1., 0., 100., 1.);
1495        assert!(nan.end().is_nan(), "a NaN value does not jump to max");
1496        assert_eq!(
1497            step_thumb(SliderValue::Single(50.), false, 1., 100., 0., 1.),
1498            SliderValue::Single(50.),
1499            "min above max"
1500        );
1501        assert_eq!(
1502            step_thumb(SliderValue::Range(60., 20.), true, 1., 0., 100., 1.),
1503            SliderValue::Range(60., 20.),
1504            "a reversed range"
1505        );
1506    }
1507
1508    struct Holder(Entity<SliderState>);
1509
1510    impl Render for Holder {
1511        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1512            div()
1513        }
1514    }
1515
1516    /// A slider of `state`, 100px wide, in a window.
1517    fn sized(
1518        state: SliderState,
1519        cx: &mut gpui::TestAppContext,
1520    ) -> (Entity<SliderState>, &mut gpui::VisualTestContext) {
1521        let (holder, cx) = cx.add_window_view(|_, cx| Holder(cx.new(|_| state)));
1522        let state = holder.read_with(cx, |holder, _| holder.0.clone());
1523        state.update(cx, |state, _| {
1524            state.set_bounds(Bounds::new(
1525                gpui::point(px(0.), px(0.)),
1526                gpui::size(px(100.), px(10.)),
1527            ));
1528        });
1529        (state, cx)
1530    }
1531
1532    fn drag(state: &Entity<SliderState>, x: f32, start: bool, cx: &mut gpui::VisualTestContext) {
1533        state.update_in(cx, |state, window, cx| {
1534            let position = gpui::point(px(x), px(0.));
1535            state.update_value_by_position(Axis::Horizontal, position, start, window, cx);
1536        })
1537    }
1538
1539    #[gpui::test]
1540    fn a_drag_snaps_to_steps_counted_from_min(cx: &mut gpui::TestAppContext) {
1541        let (state, cx) = sized(SliderState::new().min(3.).max(103.).step(5.), cx);
1542        // 9 is between the steps 8 and 13, not next to 10.
1543        drag(&state, 6., false, cx);
1544        assert_eq!(
1545            state.read_with(cx, |state, _| state.value()),
1546            SliderValue::Single(8.)
1547        );
1548    }
1549
1550    #[gpui::test]
1551    fn a_right_to_left_slider_grows_from_the_right(cx: &mut gpui::TestAppContext) {
1552        let (state, cx) = sized(SliderState::new().step(25.), cx);
1553        cx.update(|_, cx| crate::LayoutDirection::Rtl.set_global(cx));
1554        // 30px from the left is 70px from the start edge on the right.
1555        drag(&state, 30., false, cx);
1556        assert_eq!(
1557            state.read_with(cx, |state, _| state.value()),
1558            SliderValue::Single(75.)
1559        );
1560
1561        state.update_in(cx, |state, window, cx| {
1562            state.set_value((25., 75.), window, cx);
1563        });
1564        // The start thumb now sits on the right: a pointer near it moves it.
1565        let nearer_start = state.read_with(cx, |state, cx| {
1566            state.is_nearer_start(Axis::Horizontal, gpui::point(px(80.), px(0.)), cx)
1567        });
1568        assert!(nearer_start);
1569    }
1570
1571    #[gpui::test]
1572    fn a_dropped_thumb_stands_at_its_value(cx: &mut gpui::TestAppContext) {
1573        let (state, cx) = sized(SliderState::new().step(25.), cx);
1574        drag(&state, 30., false, cx);
1575        state.read_with(cx, |state, _| {
1576            assert_eq!(state.value(), SliderValue::Single(25.));
1577            assert_eq!(state.percentage(), 0.0..0.25);
1578        });
1579
1580        state.update_in(cx, |state, window, cx| {
1581            state.set_value((25., 75.), window, cx);
1582        });
1583        drag(&state, 40., true, cx);
1584        drag(&state, 60., false, cx);
1585        state.read_with(cx, |state, _| {
1586            assert_eq!(state.value(), SliderValue::Range(50., 50.));
1587            assert_eq!(state.percentage(), 0.5..0.5);
1588        });
1589    }
1590
1591    #[gpui::test]
1592    fn a_zero_step_drags_continuously(cx: &mut gpui::TestAppContext) {
1593        for step in [0., -5., f32::NAN, f32::INFINITY] {
1594            let (state, cx) = sized(SliderState::new().step(step), cx);
1595            drag(&state, 30., false, cx);
1596            state.read_with(cx, |state, _| {
1597                let value = state.value().end();
1598                assert!((value - 30.).abs() < 1e-3, "step {step}: {value}");
1599                assert!((state.percentage().end - 0.3).abs() < 1e-5, "step {step}");
1600            });
1601        }
1602    }
1603
1604    #[gpui::test]
1605    fn an_accessibility_step_reports_a_change_then_a_release(cx: &mut gpui::TestAppContext) {
1606        let (state, cx) = sized(SliderState::new().default_value(99.), cx);
1607        let events = std::rc::Rc::new(std::cell::RefCell::new(Vec::new()));
1608        cx.update(|_, cx| {
1609            let events = events.clone();
1610            cx.subscribe(&state, move |_, event: &SliderEvent, _| {
1611                events.borrow_mut().push(match event {
1612                    SliderEvent::Change(value) => ("change", value.end()),
1613                    SliderEvent::Release(value) => ("release", value.end()),
1614                });
1615            })
1616            .detach();
1617        });
1618        let step = |delta: f32, cx: &mut gpui::VisualTestContext| {
1619            state.update_in(cx, |state, window, cx| {
1620                state.step_thumb(false, delta, window, cx)
1621            })
1622        };
1623        step(1., cx);
1624        assert_eq!(&*events.borrow(), &[("change", 100.), ("release", 100.)]);
1625        assert_eq!(state.read_with(cx, |state, _| state.value().end()), 100.);
1626        // At its end the step changes nothing and reports nothing.
1627        step(1., cx);
1628        assert_eq!(events.borrow().len(), 2);
1629        step(-1., cx);
1630        assert_eq!(events.borrow()[2..], [("change", 99.), ("release", 99.)]);
1631    }
1632
1633    #[gpui::test]
1634    fn accessibility_set_value_moves_the_reported_thumb(cx: &mut gpui::TestAppContext) {
1635        let (state, cx) = sized(SliderState::new().step(5.).default_value((20., 60.)), cx);
1636        let events = std::rc::Rc::new(std::cell::RefCell::new(Vec::new()));
1637        cx.update(|_, cx| {
1638            let events = events.clone();
1639            cx.subscribe(&state, move |_, event: &SliderEvent, _| {
1640                events.borrow_mut().push(match event {
1641                    SliderEvent::Change(value) => ("change", *value),
1642                    SliderEvent::Release(value) => ("release", *value),
1643                });
1644            })
1645            .detach();
1646        });
1647        let set = |target, cx: &mut gpui::VisualTestContext| {
1648            state.update_in(cx, |state, window, cx| {
1649                state.handle_accessibility_set_value(
1650                    Some(&ActionData::NumericValue(target)),
1651                    window,
1652                    cx,
1653                );
1654            });
1655        };
1656        set(72., cx);
1657        set(72., cx);
1658        set(f64::NAN, cx);
1659        set(10., cx);
1660        assert_eq!(
1661            &*events.borrow(),
1662            &[
1663                ("change", SliderValue::Range(20., 70.)),
1664                ("release", SliderValue::Range(20., 70.)),
1665                ("change", SliderValue::Range(20., 20.)),
1666                ("release", SliderValue::Range(20., 20.)),
1667            ]
1668        );
1669    }
1670
1671    #[gpui::test]
1672    fn an_accessibility_step_leaves_an_invalid_value_alone(cx: &mut gpui::TestAppContext) {
1673        let cases = [
1674            SliderState::new().default_value(f32::NAN),
1675            SliderState::new().default_value((60., 20.)),
1676        ];
1677        for state in cases {
1678            let (state, cx) = sized(state, cx);
1679            let before = state.read_with(cx, |state, _| state.value());
1680            let changes = std::rc::Rc::new(std::cell::Cell::new(0));
1681            cx.update(|_, cx| {
1682                let changes = changes.clone();
1683                cx.subscribe(&state, move |_, _: &SliderEvent, _| {
1684                    changes.set(changes.get() + 1)
1685                })
1686                .detach();
1687            });
1688            for start in [false, true] {
1689                state.update_in(cx, |state, window, cx| {
1690                    state.step_thumb(start, 1., window, cx)
1691                });
1692            }
1693            let after = state.read_with(cx, |state, _| state.value());
1694            assert_eq!(
1695                (after.start().to_bits(), after.end().to_bits()),
1696                (before.start().to_bits(), before.end().to_bits()),
1697                "{before:?} became {after:?}"
1698            );
1699            assert_eq!(changes.get(), 0, "{before:?} reported a change");
1700        }
1701    }
1702
1703    #[gpui::test]
1704    fn an_accessibility_step_keeps_a_range(cx: &mut gpui::TestAppContext) {
1705        let (state, cx) = sized(SliderState::new().default_value((20., 60.)), cx);
1706        let step = |start: bool, delta: f32, cx: &mut gpui::VisualTestContext| {
1707            state.update_in(cx, |state, window, cx| {
1708                state.step_thumb(start, delta, window, cx)
1709            });
1710            state.read_with(cx, |state, _| state.value())
1711        };
1712        assert_eq!(step(false, 1., cx), SliderValue::Range(20., 61.));
1713        assert_eq!(step(true, 5., cx), SliderValue::Range(25., 61.));
1714        assert_eq!(
1715            step(true, 100., cx),
1716            SliderValue::Range(61., 61.),
1717            "a thumb stops at the other"
1718        );
1719    }
1720
1721    #[gpui::test]
1722    fn a_continuous_slider_reports_a_usable_step(cx: &mut gpui::TestAppContext) {
1723        use gpui::{Element as _, accesskit, canvas};
1724        use std::{cell::Cell, rc::Rc};
1725
1726        struct Probe(Rc<Cell<Option<f64>>>);
1727
1728        impl Render for Probe {
1729            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1730                let reported = self.0.clone();
1731                canvas(
1732                    move |_, window, cx| {
1733                        let state = cx.new(|_| SliderState::new().step(0.));
1734                        let element = Slider::new(&state).render(window, cx).into_element();
1735                        let mut node = accesskit::Node::new(Role::Slider);
1736                        element.write_a11y_info(&mut node);
1737                        reported.set(node.numeric_value_step());
1738                    },
1739                    |_, _, _, _| {},
1740                )
1741            }
1742        }
1743
1744        let reported = Rc::new(Cell::new(None));
1745        let (_, cx) = cx.add_window_view({
1746            let reported = reported.clone();
1747            move |_, _| Probe(reported)
1748        });
1749        cx.update(|window, cx| window.draw(cx).clear(cx));
1750        assert_eq!(reported.get(), Some(1.), "a hundredth of 0..100");
1751    }
1752
1753    #[test]
1754    #[should_panic(expected = "`min` must be greater than 0")]
1755    #[allow(deprecated)]
1756    fn legacy_logarithmic_validation_is_preserved() {
1757        let _ = SliderState::new().scale(SliderScale::Logarithmic);
1758    }
1759
1760    /// A slider's bar beside a view that reads its state, under retained views.
1761    #[cfg(feature = "gpui-fast")]
1762    mod retained {
1763        use std::{cell::Cell, rc::Rc};
1764
1765        use gpui::{
1766            AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render, Styled as _,
1767            TestAppContext, Window, div, px,
1768        };
1769
1770        use super::super::{SliderIndicator, SliderState};
1771
1772        /// A view that shows a slider's value, counting its renders.
1773        struct Readout {
1774            state: Entity<SliderState>,
1775            renders: Rc<Cell<usize>>,
1776        }
1777
1778        impl Render for Readout {
1779            fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1780                self.renders.set(self.renders.get() + 1);
1781                div().child(self.state.read(cx).value().to_string())
1782            }
1783        }
1784
1785        /// A slider's bar in a view of its own.
1786        struct Bar {
1787            state: Entity<SliderState>,
1788        }
1789
1790        impl Render for Bar {
1791            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1792                div()
1793                    .w(px(120.))
1794                    .h(px(24.))
1795                    .child(SliderIndicator::new(&self.state).size_full())
1796            }
1797        }
1798
1799        /// The bar and the readout side by side.
1800        struct Pair {
1801            bar: Entity<Bar>,
1802            readout: Entity<Readout>,
1803        }
1804
1805        impl Render for Pair {
1806            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1807                div()
1808                    .flex()
1809                    .child(self.bar.clone())
1810                    .child(self.readout.clone())
1811            }
1812        }
1813
1814        /// Drawing a slider's bar again where it was changes nothing in the
1815        /// slider's state: a view beside it that reads the state is not built
1816        /// again for it.
1817        #[gpui::test]
1818        fn drawing_a_slider_again_leaves_its_readers_retained(cx: &mut TestAppContext) {
1819            let renders = Rc::new(Cell::new(0));
1820            let (view, cx) = cx.add_window_view({
1821                let renders = renders.clone();
1822                move |_, cx| {
1823                    let state = cx.new(|_| SliderState::new());
1824                    Pair {
1825                        bar: cx.new(|_| Bar {
1826                            state: state.clone(),
1827                        }),
1828                        readout: cx.new(|_| Readout { state, renders }),
1829                    }
1830                }
1831            });
1832            cx.update(|window, cx| window.draw(cx).clear(cx));
1833            cx.update(|window, cx| window.draw(cx).clear(cx));
1834            let rendered = renders.get();
1835            for _ in 0..3 {
1836                view.update(cx, |pair, cx| pair.bar.update(cx, |_, cx| cx.notify()));
1837                cx.update(|window, cx| window.draw(cx).clear(cx));
1838            }
1839            cx.update(|window, cx| window.draw(cx).clear(cx));
1840            assert_eq!(renders.get(), rendered, "the readout was built again");
1841        }
1842    }
1843}