Skip to main content

gpui_deck/
slider.rs

1//! A linear slider with independently focusable thumbs and application-owned visuals.
2//! Derived from GPUI Kit v0.9.0's slider pointer/geometry primitives; GPUI Deck
3//! adds retained ordered values, keyboard, focus, and numeric accessibility.
4
5use std::ops::RangeInclusive;
6
7use gpui::{
8    AccessibleAction, AnyElement, App, AppContext as _, Axis, Bounds, Context, DragMoveEvent,
9    ElementId, Empty, Entity, EntityId, EventEmitter, FocusHandle, InteractiveElement,
10    Interactivity, IntoElement, KeyBinding, MouseButton, MouseDownEvent, Orientation,
11    ParentElement, Pixels, Point, Render, RenderOnce, Role, SharedString,
12    StatefulInteractiveElement, Styled, Window, accesskit, div, prelude::FluentBuilder as _, px,
13};
14
15use crate::{
16    ElementExt as _, TestSupportExt as _,
17    a11y_disabled::A11yDisabledExt as _,
18    actions::{
19        SelectDown, SelectFirst, SelectLast, SelectLeft, SelectPageDown, SelectPageUp, SelectRight,
20        SelectUp,
21    },
22};
23
24const CONTEXT: &str = "Slider";
25
26pub(crate) fn init(cx: &mut App) {
27    cx.bind_keys([
28        KeyBinding::new("left", SelectLeft, Some(CONTEXT)),
29        KeyBinding::new("right", SelectRight, Some(CONTEXT)),
30        KeyBinding::new("down", SelectDown, Some(CONTEXT)),
31        KeyBinding::new("up", SelectUp, Some(CONTEXT)),
32        KeyBinding::new("home", SelectFirst, Some(CONTEXT)),
33        KeyBinding::new("end", SelectLast, Some(CONTEXT)),
34        KeyBinding::new("pageup", SelectPageUp, Some(CONTEXT)),
35        KeyBinding::new("pagedown", SelectPageDown, Some(CONTEXT)),
36    ]);
37}
38
39/// The ordered values after one change, including programmatic changes.
40#[derive(Clone, Debug, PartialEq)]
41pub enum SliderEvent {
42    Change(Vec<f32>),
43}
44
45/// Retained ordered values, thumb focus, and pointer geometry for one slider in one window.
46///
47/// Values snap to steps measured from the minimum. Both endpoints are reachable,
48/// including a maximum that is not on the step grid. Range, step, and thumb count
49/// are fixed for the entity's lifetime. Applications observe this state to redraw.
50pub struct SliderState {
51    min: f32,
52    max: f32,
53    step: f32,
54    values: Vec<f32>,
55    disabled: bool,
56    focus: Vec<FocusHandle>,
57    bounds: Bounds<Pixels>,
58    axis: Axis,
59    direction: crate::Direction,
60    pointer_thumb: usize,
61}
62
63impl SliderState {
64    /// Creates one thumb per initial value. Thumb identities and count remain fixed.
65    /// Values are clamped and snapped, and equal values are allowed.
66    ///
67    /// # Panics
68    /// Endpoints must be finite with `min < max`; `step` must be finite and positive.
69    /// Values must be finite, nonempty, and ordered after normalization.
70    pub fn new(
71        range: RangeInclusive<f32>,
72        step: f32,
73        values: impl IntoIterator<Item = f32>,
74        cx: &mut Context<Self>,
75    ) -> Self {
76        let (min, max) = range.into_inner();
77        assert!(
78            min.is_finite() && max.is_finite() && min < max,
79            "Slider range must have finite endpoints with min < max"
80        );
81        assert!(
82            step.is_finite() && step > 0.,
83            "Slider step must be finite and positive"
84        );
85        let mut state = Self {
86            min,
87            max,
88            step,
89            values: Vec::new(),
90            disabled: false,
91            focus: Vec::new(),
92            bounds: Bounds::default(),
93            axis: Axis::Horizontal,
94            direction: crate::Direction::Ltr,
95            pointer_thumb: 0,
96        };
97        state.values = state.normalized_values(values);
98        assert!(!state.values.is_empty(), "Slider needs at least one thumb");
99        state.focus = state.values.iter().map(|_| cx.focus_handle()).collect();
100        state
101    }
102
103    pub fn values(&self) -> &[f32] {
104        &self.values
105    }
106
107    pub fn min_value(&self) -> f32 {
108        self.min
109    }
110
111    pub fn max_value(&self) -> f32 {
112        self.max
113    }
114
115    pub fn step_value(&self) -> f32 {
116        self.step
117    }
118
119    /// The thumb center's fraction along the travel rail, in `0..=1`.
120    pub fn percentage(&self, index: usize) -> f32 {
121        ((self.values[index] as f64 - self.min as f64) / (self.max as f64 - self.min as f64)) as f32
122    }
123
124    pub fn thumb_focus_handle(&self, index: usize) -> &FocusHandle {
125        &self.focus[index]
126    }
127
128    pub fn is_disabled(&self) -> bool {
129        self.disabled
130    }
131
132    /// Replaces all values, preserving thumb count and order. Emits one event only
133    /// when the normalized values change. The initial validation rules still apply.
134    /// Programmatic changes remain allowed while user interaction is disabled.
135    pub fn set_values(
136        &mut self,
137        values: impl IntoIterator<Item = f32>,
138        window: &mut Window,
139        cx: &mut Context<Self>,
140    ) {
141        let values = self.normalized_values(values);
142        assert_eq!(
143            values.len(),
144            self.values.len(),
145            "Slider thumb count is fixed"
146        );
147        if self.values == values {
148            return;
149        }
150        self.values = values;
151        cx.emit(SliderEvent::Change(self.values.clone()));
152        cx.notify();
153        window.refresh();
154    }
155
156    /// Sets one thumb, snapping from the global minimum and clamping to its
157    /// neighbors so thumbs never cross. Equal adjacent values are allowed.
158    /// Programmatic changes remain allowed while user interaction is disabled.
159    pub fn set_thumb_value(
160        &mut self,
161        index: usize,
162        value: f32,
163        window: &mut Window,
164        cx: &mut Context<Self>,
165    ) {
166        let (min, max) = self.thumb_range(index);
167        let value = self.normalized(value).clamp(min, max);
168        if self.values[index] == value {
169            return;
170        }
171        self.values[index] = value;
172        cx.emit(SliderEvent::Change(self.values.clone()));
173        cx.notify();
174        window.refresh();
175    }
176
177    /// Disables user interaction and removes all thumbs from normal Tab order.
178    /// An already-focused thumb retains its focus binding so Tab can leave it.
179    pub fn set_disabled(&mut self, disabled: bool, window: &mut Window, cx: &mut Context<Self>) {
180        if self.disabled == disabled {
181            return;
182        }
183        self.disabled = disabled;
184        cx.notify();
185        window.refresh();
186    }
187
188    fn normalized(&self, value: f32) -> f32 {
189        assert!(value.is_finite(), "Slider value must be finite");
190        if value <= self.min {
191            return self.min;
192        }
193        if value >= self.max {
194            return self.max;
195        }
196        let min = self.min as f64;
197        let step = self.step as f64;
198        let snapped = min + ((value as f64 - min) / step).round() * step;
199        snapped.clamp(min, self.max as f64) as f32
200    }
201
202    fn normalized_values(&self, values: impl IntoIterator<Item = f32>) -> Vec<f32> {
203        let values: Vec<_> = values
204            .into_iter()
205            .map(|value| self.normalized(value))
206            .collect();
207        assert!(
208            values.windows(2).all(|pair| pair[0] <= pair[1]),
209            "Slider values must be ordered"
210        );
211        values
212    }
213
214    fn thumb_range(&self, index: usize) -> (f32, f32) {
215        assert!(
216            index < self.values.len(),
217            "Slider thumb index must identify a value"
218        );
219        let min = index
220            .checked_sub(1)
221            .map_or(self.min, |index| self.values[index]);
222        let max = self.values.get(index + 1).copied().unwrap_or(self.max);
223        (min, max)
224    }
225
226    fn step_by(&mut self, thumb: usize, steps: f64, window: &mut Window, cx: &mut Context<Self>) {
227        if self.disabled {
228            return;
229        }
230        let min = self.min as f64;
231        let step = self.step as f64;
232        let current = self.values[thumb];
233        let index = (current as f64 - min) / step;
234        let index = if steps < 0. && current == self.max {
235            // An off-grid maximum is the final stop after the last grid value.
236            // Subtracting a raw step and rounding can skip that adjacent value.
237            let last = index.floor();
238            if (min + last * step) as f32 == self.max {
239                last
240            } else {
241                last + 1.
242            }
243        } else {
244            index.round()
245        };
246        let value = (min + (index + steps) * step).clamp(min, self.max as f64) as f32;
247        self.set_thumb_value(thumb, value, window, cx);
248    }
249
250    fn to_edge(&mut self, thumb: usize, last: bool, window: &mut Window, cx: &mut Context<Self>) {
251        if !self.disabled {
252            self.set_thumb_value(thumb, if last { self.max } else { self.min }, window, cx);
253        }
254    }
255
256    fn pointer_value(&self, position: Point<Pixels>) -> Option<f32> {
257        let (offset, length) = match self.axis {
258            Axis::Horizontal => (position.x - self.bounds.left(), self.bounds.size.width),
259            Axis::Vertical => (self.bounds.bottom() - position.y, self.bounds.size.height),
260        };
261        if length <= px(0.) {
262            return None;
263        }
264        let fraction = (offset / length).clamp(0., 1.);
265        let fraction = if self.axis == Axis::Horizontal {
266            self.direction.physical_fraction(fraction)
267        } else {
268            fraction
269        } as f64;
270        let value = self.min as f64 + (self.max as f64 - self.min as f64) * fraction;
271        Some(value as f32)
272    }
273
274    fn press_track(
275        &mut self,
276        position: Point<Pixels>,
277        window: &mut Window,
278        cx: &mut Context<Self>,
279    ) {
280        if self.disabled {
281            return;
282        }
283        if let Some(value) = self.pointer_value(position) {
284            let thumb = self
285                .values
286                .iter()
287                .enumerate()
288                .min_by(|(left_index, left), (right_index, right)| {
289                    ((**left as f64) - value as f64)
290                        .abs()
291                        .total_cmp(&((**right as f64) - value as f64).abs())
292                        .then_with(|| {
293                            // A collapsed range must open toward the pointer:
294                            // its last thumb can increase, and its first can decrease.
295                            if left == right && value > **left {
296                                right_index.cmp(left_index)
297                            } else {
298                                left_index.cmp(right_index)
299                            }
300                        })
301                })
302                .map(|(index, _)| index)
303                .unwrap();
304            self.pointer_thumb = thumb;
305            self.focus[thumb].focus(window, cx);
306            self.set_thumb_value(thumb, value, window, cx);
307        }
308    }
309
310    fn drag_at_pointer(
311        &mut self,
312        position: Point<Pixels>,
313        window: &mut Window,
314        cx: &mut Context<Self>,
315    ) {
316        if !self.disabled
317            && let Some(value) = self.pointer_value(position)
318        {
319            self.set_thumb_value(self.pointer_thumb, value, window, cx);
320        }
321    }
322}
323
324impl EventEmitter<SliderEvent> for SliderState {}
325
326#[derive(Clone)]
327struct DragSlider(EntityId);
328
329impl Render for DragSlider {
330    fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
331        Empty
332    }
333}
334
335/// An unstyled slider group and thumb-center travel rail.
336///
337/// Render one [`SliderThumb`] per value, in index order, alongside non-interactive
338/// track and fill children. Applications position each thumb using
339/// [`SliderState::percentage`]. Horizontal values grow in the logical direction;
340/// vertical values grow bottom to top. Reserve desired space around the thumbs
341/// outside this rail. The library imposes no thumb size, track thickness, or colors.
342#[derive(IntoElement)]
343pub struct Slider {
344    base: crate::ObservedElement<gpui::Stateful<gpui::Div>>,
345    state: Entity<SliderState>,
346    axis: Axis,
347    direction: Option<crate::Direction>,
348    label: Option<SharedString>,
349    children: Vec<AnyElement>,
350}
351
352impl Slider {
353    pub fn new(id: impl Into<ElementId>, state: &Entity<SliderState>) -> Self {
354        Self {
355            base: div().id(id).test_support(),
356            state: state.clone(),
357            axis: Axis::Horizontal,
358            direction: None,
359            label: None,
360            children: Vec::new(),
361        }
362    }
363
364    /// Mirrors horizontal keys and pointer geometry in RTL. Application-owned
365    /// fill/thumb layout can use `direction.physical_fraction(percentage)`.
366    pub fn direction(mut self, direction: crate::Direction) -> Self {
367        self.direction = Some(direction);
368        self
369    }
370
371    pub fn axis(mut self, axis: Axis) -> Self {
372        self.axis = axis;
373        self
374    }
375
376    pub fn accessibility_label(mut self, label: impl Into<SharedString>) -> Self {
377        self.label = Some(label.into());
378        self
379    }
380}
381
382impl Styled for Slider {
383    fn style(&mut self) -> &mut gpui::StyleRefinement {
384        self.base.style()
385    }
386}
387
388impl ParentElement for Slider {
389    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
390        self.children.extend(elements);
391    }
392}
393
394impl InteractiveElement for Slider {
395    fn interactivity(&mut self) -> &mut Interactivity {
396        self.base.interactivity()
397    }
398}
399
400impl StatefulInteractiveElement for Slider {}
401
402impl RenderOnce for Slider {
403    fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
404        let axis = self.axis;
405        let direction = self
406            .direction
407            .unwrap_or_else(|| crate::Direction::current(cx));
408        self.state.update(cx, |state, _| {
409            state.axis = axis;
410            state.direction = direction;
411        });
412        let disabled = self.state.read(cx).disabled;
413        let entity_id = self.state.entity_id();
414        let press = self.state.clone();
415        let drag_start = self.state.clone();
416        let drag_move = self.state.clone();
417        let geometry = self.state;
418        self.base
419            .role(Role::Group)
420            .when_some(self.label, |this, label| this.aria_label(label))
421            .when(disabled, |this| {
422                this.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
423            })
424            .when(!disabled, |this| {
425                this.on_mouse_down(MouseButton::Left, move |event, window, cx| {
426                    press.update(cx, |state, cx| {
427                        state.press_track(event.position, window, cx)
428                    });
429                })
430                .on_drag(DragSlider(entity_id), move |drag, _, window, cx| {
431                    let position = window.mouse_position();
432                    drag_start.update(cx, |state, cx| state.drag_at_pointer(position, window, cx));
433                    cx.stop_propagation();
434                    cx.new(|_| drag.clone())
435                })
436                .on_drag_move(
437                    move |event: &DragMoveEvent<DragSlider>, window, cx| {
438                        if event.drag(cx).0 == entity_id {
439                            drag_move.update(cx, |state, cx| {
440                                state.drag_at_pointer(event.event.position, window, cx);
441                            });
442                        }
443                    },
444                )
445            })
446            .children(self.children)
447            .on_prepaint(move |bounds, _, cx| {
448                if geometry.read(cx).bounds != bounds {
449                    geometry.update(cx, |state, _| state.bounds = bounds);
450                }
451            })
452            .a11y_disabled(disabled)
453    }
454}
455
456fn thumb_id(state: EntityId, index: usize) -> ElementId {
457    (ElementId::from(("slider-thumb", state)), index.to_string()).into()
458}
459
460/// One independently focusable slider value. Render inside its matching [`Slider`]
461/// and give each thumb an accessible name distinguishing its purpose.
462///
463/// The root supplies axis, direction, and pointer geometry. This part owns native
464/// numeric metadata, keyboard and assistive-technology adjustment, and pointer
465/// selection of this exact thumb. Its range is bounded by its neighboring values;
466/// thumbs can meet but never exchange identities or cross. Applications own all
467/// positioning, dimensions, and focus/disabled styling.
468#[derive(IntoElement)]
469pub struct SliderThumb {
470    base: crate::ObservedElement<gpui::Stateful<gpui::Div>>,
471    state: Entity<SliderState>,
472    index: usize,
473    label: Option<SharedString>,
474    children: Vec<AnyElement>,
475}
476
477impl SliderThumb {
478    /// `index` must identify a value in the matching state.
479    pub fn new(state: &Entity<SliderState>, index: usize) -> Self {
480        Self {
481            base: div().id(thumb_id(state.entity_id(), index)).test_support(),
482            state: state.clone(),
483            index,
484            label: None,
485            children: Vec::new(),
486        }
487    }
488
489    pub fn accessibility_label(mut self, label: impl Into<SharedString>) -> Self {
490        self.label = Some(label.into());
491        self
492    }
493}
494
495impl Styled for SliderThumb {
496    fn style(&mut self) -> &mut gpui::StyleRefinement {
497        self.base.style()
498    }
499}
500
501impl ParentElement for SliderThumb {
502    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
503        self.children.extend(elements);
504    }
505}
506
507impl InteractiveElement for SliderThumb {
508    fn interactivity(&mut self) -> &mut Interactivity {
509        self.base.interactivity()
510    }
511}
512
513impl StatefulInteractiveElement for SliderThumb {}
514
515impl RenderOnce for SliderThumb {
516    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
517        let model = self.state.read(cx);
518        let index = self.index;
519        let focus = model.focus[index].clone();
520        let disabled = model.disabled;
521        let axis = model.axis;
522        let direction = model.direction;
523        let (min, max) = model.thumb_range(index);
524        let entity_id = self.state.entity_id();
525        let drag_start = self.state.clone();
526        let increment = self.state.clone();
527        let decrement = self.state.clone();
528        let set_value = self.state.clone();
529
530        self.base
531            .role(Role::Slider)
532            .when_some(self.label, |this, label| this.aria_label(label))
533            .aria_numeric_value(model.values[index] as f64)
534            .aria_min_numeric_value(min as f64)
535            .aria_max_numeric_value(max as f64)
536            .aria_numeric_value_step(model.step as f64)
537            .aria_orientation(match axis {
538                Axis::Horizontal => Orientation::Horizontal,
539                Axis::Vertical => Orientation::Vertical,
540            })
541            .key_context(CONTEXT)
542            .when(!disabled || focus.is_focused(window), |this| {
543                this.track_focus(&focus.tab_stop(!disabled))
544            })
545            .on_action(window.listener_for(
546                &self.state,
547                move |state, _: &SelectLeft, window, cx| {
548                    state.step_by(
549                        index,
550                        if axis == Axis::Horizontal && direction.is_rtl() {
551                            1.
552                        } else {
553                            -1.
554                        },
555                        window,
556                        cx,
557                    );
558                },
559            ))
560            .on_action(window.listener_for(
561                &self.state,
562                move |state, _: &SelectRight, window, cx| {
563                    state.step_by(
564                        index,
565                        if axis == Axis::Horizontal && direction.is_rtl() {
566                            -1.
567                        } else {
568                            1.
569                        },
570                        window,
571                        cx,
572                    );
573                },
574            ))
575            .on_action(window.listener_for(
576                &self.state,
577                move |state, _: &SelectDown, window, cx| {
578                    state.step_by(index, -1., window, cx);
579                },
580            ))
581            .on_action(
582                window.listener_for(&self.state, move |state, _: &SelectUp, window, cx| {
583                    state.step_by(index, 1., window, cx);
584                }),
585            )
586            .on_action(window.listener_for(
587                &self.state,
588                move |state, _: &SelectFirst, window, cx| {
589                    state.to_edge(index, false, window, cx);
590                },
591            ))
592            .on_action(window.listener_for(
593                &self.state,
594                move |state, _: &SelectLast, window, cx| {
595                    state.to_edge(index, true, window, cx);
596                },
597            ))
598            .on_action(window.listener_for(
599                &self.state,
600                move |state, _: &SelectPageUp, window, cx| {
601                    state.step_by(index, 10., window, cx);
602                },
603            ))
604            .on_action(window.listener_for(
605                &self.state,
606                move |state, _: &SelectPageDown, window, cx| {
607                    state.step_by(index, -10., window, cx);
608                },
609            ))
610            .when(disabled, |this| {
611                this.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
612            })
613            .when(!disabled, |this| {
614                this.on_mouse_down(
615                    MouseButton::Left,
616                    window.listener_for(
617                        &self.state,
618                        move |state, _: &MouseDownEvent, window, cx| {
619                            cx.stop_propagation();
620                            if !state.disabled {
621                                state.pointer_thumb = index;
622                                state.focus[index].focus(window, cx);
623                            }
624                        },
625                    ),
626                )
627                .on_drag(DragSlider(entity_id), move |drag, _, window, cx| {
628                    let position = window.mouse_position();
629                    drag_start.update(cx, |state, cx| state.drag_at_pointer(position, window, cx));
630                    cx.stop_propagation();
631                    cx.new(|_| drag.clone())
632                })
633                .on_a11y_action(AccessibleAction::Increment, move |_, window, cx| {
634                    increment.update(cx, |state, cx| state.step_by(index, 1., window, cx));
635                })
636                .on_a11y_action(AccessibleAction::Decrement, move |_, window, cx| {
637                    decrement.update(cx, |state, cx| state.step_by(index, -1., window, cx));
638                })
639                .on_a11y_action(
640                    AccessibleAction::SetValue,
641                    move |data, window, cx| {
642                        if let Some(accesskit::ActionData::NumericValue(value)) = data {
643                            set_value.update(cx, |state, cx| {
644                                if !state.disabled && value.is_finite() {
645                                    let value =
646                                        value.clamp(state.min as f64, state.max as f64) as f32;
647                                    state.set_thumb_value(index, value, window, cx);
648                                }
649                            });
650                        }
651                    },
652                )
653            })
654            .children(self.children)
655            .a11y_disabled(disabled)
656    }
657}
658
659#[cfg(test)]
660mod tests {
661    use std::{cell::RefCell, rc::Rc};
662
663    use gpui::{
664        Element as _, Modifiers, Subscription, TestAppContext, VisualTestContext, point, relative,
665    };
666
667    use super::*;
668    use crate::{Button, Root};
669
670    struct Harness {
671        state: Entity<SliderState>,
672        axis: Axis,
673        direction: crate::Direction,
674        before: FocusHandle,
675        after: FocusHandle,
676        _subscription: Subscription,
677    }
678
679    impl Render for Harness {
680        fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
681            let state = self.state.read(cx);
682            let thumbs = state
683                .values()
684                .iter()
685                .enumerate()
686                .map(|(index, _)| {
687                    let percentage = state.percentage(index);
688                    SliderThumb::new(&self.state, index)
689                        .accessibility_label(format!("Position {}", index + 1))
690                        .debug_selector(move || format!("thumb-{index}").into())
691                        .absolute()
692                        .when(self.axis == Axis::Horizontal, |thumb| {
693                            thumb
694                                .left(relative(self.direction.physical_fraction(percentage)))
695                                .top_0()
696                                .ml(px(-6.))
697                                .w(px(12.))
698                                .h(px(24.))
699                        })
700                        .when(self.axis == Axis::Vertical, |thumb| {
701                            thumb
702                                .bottom(relative(percentage))
703                                .left_0()
704                                .mb(px(-6.))
705                                .w(px(24.))
706                                .h(px(12.))
707                        })
708                })
709                .collect::<Vec<_>>();
710            div()
711                .w(px(300.))
712                .flex()
713                .flex_col()
714                .child(
715                    Button::new("before")
716                        .h(px(30.))
717                        .track_focus(&self.before)
718                        .child("Before"),
719                )
720                .child(
721                    Slider::new("slider", &self.state)
722                        .debug_selector(|| "slider".into())
723                        .axis(self.axis)
724                        .direction(self.direction)
725                        .relative()
726                        .accessibility_label("Position")
727                        .when(self.axis == Axis::Horizontal, |this| {
728                            this.w(px(200.)).h(px(24.))
729                        })
730                        .when(self.axis == Axis::Vertical, |this| {
731                            this.w(px(24.)).h(px(200.))
732                        })
733                        .children(thumbs),
734                )
735                .child(
736                    Button::new("after")
737                        .h(px(30.))
738                        .track_focus(&self.after)
739                        .child("After"),
740                )
741        }
742    }
743
744    type Changes = Rc<RefCell<Vec<Vec<f32>>>>;
745
746    fn harness(
747        cx: &mut TestAppContext,
748        axis: Axis,
749        values: Vec<f32>,
750    ) -> (&mut VisualTestContext, Entity<Harness>, Changes) {
751        cx.update(crate::init);
752        let (root, cx) = cx.add_window_view(move |window, cx| {
753            let view = cx.new(|cx| {
754                let state = cx.new(|cx| SliderState::new(3.0..=100.0, 10., values, cx));
755                let subscription = cx.observe(&state, |_, _, cx| cx.notify());
756                Harness {
757                    state,
758                    axis,
759                    direction: crate::Direction::Ltr,
760                    before: cx.focus_handle().tab_stop(true),
761                    after: cx.focus_handle().tab_stop(true),
762                    _subscription: subscription,
763                }
764            });
765            Root::new(view, window, cx)
766        });
767        let view = root
768            .read_with(cx, |root, _| root.view().clone())
769            .downcast::<Harness>()
770            .unwrap();
771        let changes = Rc::new(RefCell::new(Vec::new()));
772        cx.update(|window, cx| {
773            let changes = changes.clone();
774            let state = view.read(cx).state.clone();
775            cx.subscribe(&state, move |_, event: &SliderEvent, _| {
776                let SliderEvent::Change(values) = event;
777                changes.borrow_mut().push(values.clone());
778            })
779            .detach();
780            window.activate_window();
781            view.read(cx).before.clone().focus(window, cx);
782            window.draw(cx).clear(cx);
783        });
784        cx.run_until_parked();
785        (cx, view, changes)
786    }
787
788    fn draw(cx: &mut VisualTestContext) {
789        cx.update(|window, cx| window.draw(cx).clear(cx));
790    }
791
792    #[gpui::test]
793    fn value_snaps_from_minimum_and_native_metadata_tracks_the_value(cx: &mut TestAppContext) {
794        let (cx, view, changes) = harness(cx, Axis::Horizontal, vec![34.]);
795        cx.update(|window, cx| {
796            let state = view.read(cx).state.clone();
797            assert_eq!(state.read(cx).values()[0], 33.);
798            assert_eq!(state.read(cx).percentage(0), 30. / 97.);
799            state.update(cx, |state, cx| {
800                for value in [34., -100., 1000., 94., 96.] {
801                    state.set_values([value], window, cx);
802                }
803            });
804            for (max, step, previous) in [(10., 3., 9.), (0.3, 0.1, 0.2)] {
805                let edge = cx.new(|cx| SliderState::new(0.0..=max, step, [max], cx));
806                edge.update(cx, |state, cx| {
807                    state.step_by(0, -1., window, cx);
808                    assert_eq!(
809                        state.values()[0],
810                        previous,
811                        "move to the preceding grid value"
812                    );
813                    state.step_by(0, 1., window, cx);
814                    assert_eq!(state.values()[0], max);
815                });
816            }
817            let _ = Slider::new("numeric-probe", &state)
818                .axis(Axis::Vertical)
819                .accessibility_label("Position")
820                .render(window, cx);
821            let element = SliderThumb::new(&state, 0)
822                .accessibility_label("Position")
823                .render(window, cx)
824                .into_element();
825            let mut node = accesskit::Node::new(element.a11y_role().unwrap());
826            element.write_a11y_info(&mut node);
827            assert_eq!(node.role(), Role::Slider);
828            assert_eq!(node.label(), Some("Position"));
829            assert_eq!(node.numeric_value(), Some(93.));
830            assert_eq!(node.min_numeric_value(), Some(3.));
831            assert_eq!(node.max_numeric_value(), Some(100.));
832            assert_eq!(node.numeric_value_step(), Some(10.));
833            assert_eq!(node.orientation(), Some(Orientation::Vertical));
834            for action in [
835                AccessibleAction::Increment,
836                AccessibleAction::Decrement,
837                AccessibleAction::SetValue,
838            ] {
839                assert!(node.supports_action(action));
840            }
841            state.update(cx, |state, cx| state.set_disabled(true, window, cx));
842            let element = SliderThumb::new(&state, 0)
843                .render(window, cx)
844                .into_element();
845            let mut disabled = accesskit::Node::new(element.a11y_role().unwrap());
846            element.write_a11y_info(&mut disabled);
847            assert!(disabled.is_disabled());
848            assert!(!disabled.supports_action(AccessibleAction::SetValue));
849        });
850        assert_eq!(*changes.borrow(), [vec![3.], vec![100.], vec![93.]]);
851    }
852
853    #[gpui::test]
854    fn keyboard_changes_are_bounded_and_disabling_keeps_a_tab_exit(cx: &mut TestAppContext) {
855        let (cx, view, changes) = harness(cx, Axis::Horizontal, vec![34.]);
856        cx.simulate_keystrokes("tab");
857        for (key, expected) in [
858            ("right", 43.),
859            ("up", 53.),
860            ("left", 43.),
861            ("down", 33.),
862            ("home", 3.),
863            ("end", 100.),
864            ("down", 93.),
865            ("pagedown", 3.),
866            ("pageup", 100.),
867            ("right", 100.),
868        ] {
869            cx.simulate_keystrokes(key);
870            draw(cx);
871            cx.update(|window, cx| {
872                let state = view.read(cx).state.read(cx);
873                assert!(state.thumb_focus_handle(0).is_focused(window));
874                assert_eq!(state.values()[0], expected);
875            });
876        }
877        assert_eq!(
878            changes.borrow().len(),
879            9,
880            "clamped keys emit no duplicate value"
881        );
882        cx.update(|window, cx| {
883            let state = view.read(cx).state.clone();
884            state.update(cx, |state, cx| state.set_disabled(true, window, cx));
885        });
886        draw(cx);
887        cx.simulate_keystrokes("home left");
888        draw(cx);
889        cx.update(|_, cx| assert_eq!(view.read(cx).state.read(cx).values()[0], 100.));
890        let center = cx.debug_bounds("slider").unwrap().center();
891        cx.simulate_click(center, Modifiers::default());
892        draw(cx);
893        cx.update(|_, cx| assert_eq!(view.read(cx).state.read(cx).values()[0], 100.));
894        cx.simulate_keystrokes("tab");
895        draw(cx);
896        cx.update(|window, cx| assert!(view.read(cx).after.is_focused(window)));
897        cx.simulate_keystrokes("shift-tab");
898        draw(cx);
899        cx.update(|window, cx| assert!(view.read(cx).before.is_focused(window)));
900        assert_eq!(changes.borrow().len(), 9);
901    }
902
903    #[gpui::test]
904    fn track_press_and_drag_follow_both_axes_and_stop_on_release(cx: &mut TestAppContext) {
905        for axis in [Axis::Horizontal, Axis::Vertical] {
906            let (cx, view, changes) = harness(cx, axis, vec![34.]);
907            let bounds = cx.debug_bounds("slider").unwrap();
908            let at = |fraction: f32| match axis {
909                Axis::Horizontal => point(
910                    bounds.left() + bounds.size.width * fraction,
911                    bounds.center().y,
912                ),
913                Axis::Vertical => point(
914                    bounds.center().x,
915                    bounds.bottom() - bounds.size.height * fraction,
916                ),
917            };
918            cx.simulate_mouse_down(at(0.5), MouseButton::Left, Modifiers::default());
919            draw(cx);
920            cx.update(|window, cx| {
921                let state = view.read(cx).state.read(cx);
922                assert_eq!(state.values()[0], 53.);
923                assert!(state.thumb_focus_handle(0).is_focused(window));
924            });
925            cx.simulate_mouse_move(at(1.25), MouseButton::Left, Modifiers::default());
926            draw(cx);
927            cx.update(|_, cx| assert_eq!(view.read(cx).state.read(cx).values()[0], 100.));
928            cx.simulate_mouse_move(at(-0.25), MouseButton::Left, Modifiers::default());
929            draw(cx);
930            cx.update(|_, cx| assert_eq!(view.read(cx).state.read(cx).values()[0], 3.));
931            cx.simulate_mouse_up(at(-0.25), MouseButton::Left, Modifiers::default());
932            draw(cx);
933            cx.simulate_mouse_move(at(0.5), None, Modifiers::default());
934            draw(cx);
935            cx.update(|_, cx| {
936                assert_eq!(view.read(cx).state.read(cx).values()[0], 3.);
937                assert!(!cx.has_active_drag());
938            });
939            assert_eq!(*changes.borrow(), [vec![53.], vec![100.], vec![3.]]);
940        }
941    }
942
943    #[gpui::test]
944    fn each_thumb_has_stable_tab_focus_and_neighbor_bounded_native_values(cx: &mut TestAppContext) {
945        let (cx, view, changes) = harness(cx, Axis::Horizontal, vec![23., 53., 83.]);
946        cx.simulate_keystrokes("tab end right tab end tab home end shift-tab home right");
947        draw(cx);
948        cx.update(|window, cx| {
949            let state = view.read(cx).state.clone();
950            assert_eq!(state.read(cx).values(), [53., 63., 100.]);
951            assert!(state.read(cx).thumb_focus_handle(1).is_focused(window));
952            for (index, min, value, max) in
953                [(0, 3., 53., 63.), (1, 53., 63., 100.), (2, 63., 100., 100.)]
954            {
955                let element = SliderThumb::new(&state, index)
956                    .accessibility_label(format!("Position {}", index + 1))
957                    .render(window, cx)
958                    .into_element();
959                let mut node = accesskit::Node::new(element.a11y_role().unwrap());
960                element.write_a11y_info(&mut node);
961                assert_eq!(node.role(), Role::Slider);
962                assert_eq!(
963                    node.label(),
964                    Some(format!("Position {}", index + 1).as_str())
965                );
966                assert_eq!(node.numeric_value(), Some(value));
967                assert_eq!(node.min_numeric_value(), Some(min));
968                assert_eq!(node.max_numeric_value(), Some(max));
969            }
970        });
971        assert_eq!(
972            changes.borrow().len(),
973            5,
974            "neighbor clamps emit no duplicate changes"
975        );
976        cx.simulate_keystrokes("tab tab");
977        draw(cx);
978        cx.update(|window, cx| assert!(view.read(cx).after.is_focused(window)));
979        cx.simulate_keystrokes("shift-tab shift-tab");
980        draw(cx);
981        cx.update(|window, cx| {
982            let state = view.read(cx).state.clone();
983            assert!(state.read(cx).thumb_focus_handle(1).is_focused(window));
984            state.update(cx, |state, cx| state.set_disabled(true, window, cx));
985        });
986        draw(cx);
987        cx.simulate_keystrokes("home left tab");
988        draw(cx);
989        cx.update(|window, cx| {
990            assert!(view.read(cx).after.is_focused(window));
991            assert_eq!(view.read(cx).state.read(cx).values(), [53., 63., 100.]);
992        });
993        cx.simulate_keystrokes("shift-tab");
994        draw(cx);
995        cx.update(|window, cx| assert!(view.read(cx).before.is_focused(window)));
996        assert_eq!(changes.borrow().len(), 5);
997    }
998
999    #[gpui::test]
1000    fn range_updates_snap_preserve_order_and_remain_programmatic_while_disabled(
1001        cx: &mut TestAppContext,
1002    ) {
1003        let (cx, view, changes) = harness(cx, Axis::Horizontal, vec![23., 83.]);
1004        cx.update(|window, cx| {
1005            let state = view.read(cx).state.clone();
1006            state.update(cx, |state, cx| {
1007                state.set_values([24., 84.], window, cx);
1008                state.set_thumb_value(0, 200., window, cx);
1009                state.set_thumb_value(0, 100., window, cx);
1010                state.set_values([3., 100.], window, cx);
1011                state.set_disabled(true, window, cx);
1012                state.set_values([13., 93.], window, cx);
1013                state.set_thumb_value(1, -100., window, cx);
1014                assert_eq!(state.values(), [13., 13.]);
1015            });
1016        });
1017        assert_eq!(
1018            *changes.borrow(),
1019            [
1020                vec![83., 83.],
1021                vec![3., 100.],
1022                vec![13., 93.],
1023                vec![13., 13.]
1024            ]
1025        );
1026    }
1027
1028    #[gpui::test]
1029    fn track_picks_nearest_and_thumb_drag_keeps_identity_in_rtl_and_vertical_layouts(
1030        cx: &mut TestAppContext,
1031    ) {
1032        for axis in [Axis::Horizontal, Axis::Vertical] {
1033            let (cx, view, changes) = harness(cx, axis, vec![23., 53., 83.]);
1034            view.update(cx, |view, cx| {
1035                view.direction = crate::Direction::Rtl;
1036                cx.notify();
1037            });
1038            draw(cx);
1039            let bounds = cx.debug_bounds("slider").unwrap();
1040            let at = |fraction: f32| match axis {
1041                Axis::Horizontal => point(
1042                    bounds.right() - bounds.size.width * fraction,
1043                    bounds.center().y,
1044                ),
1045                Axis::Vertical => point(
1046                    bounds.center().x,
1047                    bounds.bottom() - bounds.size.height * fraction,
1048                ),
1049            };
1050            cx.simulate_click(at(0.95), Modifiers::default());
1051            draw(cx);
1052            cx.update(|window, cx| {
1053                let state = view.read(cx).state.read(cx);
1054                assert_eq!(state.values(), [23., 53., 93.]);
1055                assert!(state.thumb_focus_handle(2).is_focused(window));
1056            });
1057            let middle = cx.debug_bounds("thumb-1").unwrap().center();
1058            cx.simulate_mouse_down(middle, MouseButton::Left, Modifiers::default());
1059            draw(cx);
1060            cx.simulate_mouse_move(at(1.25), MouseButton::Left, Modifiers::default());
1061            draw(cx);
1062            cx.update(|window, cx| {
1063                let state = view.read(cx).state.read(cx);
1064                assert_eq!(state.values(), [23., 93., 93.]);
1065                assert!(state.thumb_focus_handle(1).is_focused(window));
1066            });
1067            cx.simulate_mouse_move(at(-0.25), MouseButton::Left, Modifiers::default());
1068            draw(cx);
1069            cx.update(|window, cx| {
1070                let state = view.read(cx).state.clone();
1071                assert_eq!(state.read(cx).values(), [23., 23., 93.]);
1072                state.update(cx, |state, cx| state.set_disabled(true, window, cx));
1073            });
1074            draw(cx);
1075            cx.simulate_mouse_move(at(1.), MouseButton::Left, Modifiers::default());
1076            cx.simulate_mouse_up(at(1.), MouseButton::Left, Modifiers::default());
1077            draw(cx);
1078            cx.update(|window, cx| {
1079                let state = view.read(cx).state.clone();
1080                state.update(cx, |state, cx| state.set_disabled(false, window, cx));
1081                assert_eq!(state.read(cx).values(), [23., 23., 93.]);
1082                assert!(!cx.has_active_drag());
1083            });
1084            draw(cx);
1085            cx.simulate_mouse_move(at(0.5), None, Modifiers::default());
1086            draw(cx);
1087            cx.update(|_, cx| assert_eq!(view.read(cx).state.read(cx).values(), [23., 23., 93.]));
1088            assert_eq!(
1089                *changes.borrow(),
1090                [
1091                    vec![23., 53., 93.],
1092                    vec![23., 93., 93.],
1093                    vec![23., 23., 93.]
1094                ]
1095            );
1096            for (fraction, expected, selected) in
1097                [(0.95, [53., 53., 93.], 2), (0.1, [13., 53., 53.], 0)]
1098            {
1099                cx.update(|window, cx| {
1100                    let state = view.read(cx).state.clone();
1101                    state.update(cx, |state, cx| {
1102                        state.set_values([53., 53., 53.], window, cx)
1103                    });
1104                });
1105                draw(cx);
1106                cx.simulate_click(at(fraction), Modifiers::default());
1107                draw(cx);
1108                cx.update(|window, cx| {
1109                    let state = view.read(cx).state.read(cx);
1110                    assert_eq!(state.values(), expected);
1111                    assert!(state.thumb_focus_handle(selected).is_focused(window));
1112                });
1113            }
1114            assert_eq!(changes.borrow().len(), 7);
1115        }
1116    }
1117
1118    #[gpui::test]
1119    fn thumb_count_and_order_are_fixed_configuration_contracts(cx: &mut TestAppContext) {
1120        cx.new(|cx| {
1121            for values in [vec![], vec![83., 23.]] {
1122                assert!(
1123                    std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
1124                        SliderState::new(3.0..=100.0, 10., values, cx)
1125                    }))
1126                    .is_err()
1127                );
1128            }
1129            SliderState::new(3.0..=100.0, 10., [23., 83.], cx)
1130        });
1131        let (cx, view, changes) = harness(cx, Axis::Horizontal, vec![23., 83.]);
1132        cx.update(|window, cx| {
1133            let state = view.read(cx).state.clone();
1134            state.update(cx, |state, cx| {
1135                for values in [vec![23.], vec![83., 23.]] {
1136                    assert!(
1137                        std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
1138                            state.set_values(values, window, cx);
1139                        }))
1140                        .is_err()
1141                    );
1142                }
1143                assert_eq!(state.values(), [23., 83.]);
1144            });
1145        });
1146        assert!(changes.borrow().is_empty());
1147    }
1148}