Skip to main content

gpui_material_foundation/
range.rs

1use gpui::{
2    AccessibleAction, App, Axis, Div, Entity, InteractiveElement, Role, SharedString, Stateful,
3    StatefulInteractiveElement, Window,
4    accesskit::{ActionData, Orientation},
5};
6use gpui_base::slider::{SliderState, SliderValue};
7use gpui_material_theme::Direction;
8
9/// Identifies the Base slider value represented by a semantic node.
10#[derive(Clone, Copy, Debug, PartialEq, Eq)]
11pub enum RangeThumb {
12    /// Lower-bound thumb of a range slider (or the single thumb of a continuous slider).
13    Start,
14    /// Upper-bound thumb of a range slider.
15    End,
16}
17
18impl RangeThumb {
19    fn value(self, value: SliderValue) -> f32 {
20        match self {
21            Self::Start => value.start(),
22            Self::End => value.end(),
23        }
24    }
25}
26
27/// Formats the same Base slider value that the track and semantics expose.
28/// The caller supplies locale-aware formatting and decides when to announce it.
29pub fn value_label(
30    state: &Entity<SliderState>,
31    thumb: RangeThumb,
32    cx: &App,
33    format: impl FnOnce(f32) -> SharedString,
34) -> SharedString {
35    format(thumb.value(state.read(cx).value()))
36}
37
38/// Adds native slider semantics to a focusable host for Base track and thumb elements.
39/// Windows UIA SetValue, increment/decrement and arrow keys share Base's value update.
40/// For a disabled control, use the disabled Base Slider semantic host and omit this adapter.
41pub fn range_semantics(
42    element: Stateful<Div>,
43    state: &Entity<SliderState>,
44    thumb: RangeThumb,
45    axis: Axis,
46    cx: &App,
47) -> Stateful<Div> {
48    let slider = state.read(cx);
49    let value = slider.value();
50    let (min, max) = match (value.is_range(), thumb) {
51        (true, RangeThumb::Start) => (slider.min_value(), value.end()),
52        (true, RangeThumb::End) => (value.start(), slider.max_value()),
53        _ => (slider.min_value(), slider.max_value()),
54    };
55    let element = element
56        .role(Role::Slider)
57        .aria_numeric_value(f64::from(thumb.value(value)))
58        .aria_min_numeric_value(f64::from(min))
59        .aria_max_numeric_value(f64::from(max))
60        .aria_numeric_value_step(f64::from(slider.accessibility_step()))
61        .aria_orientation(if axis == Axis::Horizontal {
62            Orientation::Horizontal
63        } else {
64            Orientation::Vertical
65        });
66
67    let set = state.clone();
68    let increment = state.clone();
69    let decrement = state.clone();
70    let keyboard = state.clone();
71    let release = state.clone();
72    let release_outside = state.clone();
73    element
74        .on_a11y_action(AccessibleAction::SetValue, move |data, window, cx| {
75            if let Some(ActionData::NumericValue(target)) = data
76                && target.is_finite()
77            {
78                set.update(cx, |state, cx| {
79                    let target = target
80                        .clamp(f64::from(state.min_value()), f64::from(state.max_value()))
81                        as f32;
82                    let delta = target - thumb.value(state.value());
83                    state.step_thumb(thumb == RangeThumb::Start, delta, window, cx);
84                });
85            }
86        })
87        .on_a11y_action(AccessibleAction::Increment, move |_, window, cx| {
88            step(&increment, thumb, 1., window, cx)
89        })
90        .on_a11y_action(AccessibleAction::Decrement, move |_, window, cx| {
91            step(&decrement, thumb, -1., window, cx)
92        })
93        .on_key_down(move |event, window, cx| {
94            if event.keystroke.modifiers.modified() {
95                return;
96            }
97            let direction = crate::current_material_theme(window, cx).layout.direction;
98            let horizontal = horizontal_step_sign(axis, direction);
99            match event.keystroke.key.as_str() {
100                "left" => step(&keyboard, thumb, -horizontal, window, cx),
101                "right" => step(&keyboard, thumb, horizontal, window, cx),
102                "down" => step(&keyboard, thumb, -1., window, cx),
103                "up" => step(&keyboard, thumb, 1., window, cx),
104                "pageup" => step_large(&keyboard, thumb, 1., window, cx),
105                "pagedown" => step_large(&keyboard, thumb, -1., window, cx),
106                "home" => jump_bound(&keyboard, thumb, false, window, cx),
107                "end" => jump_bound(&keyboard, thumb, true, window, cx),
108                _ => return,
109            }
110            cx.stop_propagation();
111        })
112        .on_mouse_up(gpui::MouseButton::Left, move |_, _, cx| {
113            release.update(cx, |state, cx| state.handle_release(cx));
114        })
115        .on_mouse_up_out(gpui::MouseButton::Left, move |_, _, cx| {
116            release_outside.update(cx, |state, cx| state.handle_release(cx));
117        })
118}
119
120fn step(
121    state: &Entity<SliderState>,
122    thumb: RangeThumb,
123    direction: f32,
124    window: &mut Window,
125    cx: &mut App,
126) {
127    state.update(cx, |state, cx| {
128        state.step_thumb(
129            thumb == RangeThumb::Start,
130            direction * state.accessibility_step(),
131            window,
132            cx,
133        );
134    });
135}
136
137fn step_large(
138    state: &Entity<SliderState>,
139    thumb: RangeThumb,
140    direction: f32,
141    window: &mut Window,
142    cx: &mut App,
143) {
144    state.update(cx, |state, cx| {
145        let base_step = state.accessibility_step();
146        let span = (state.max_value() - state.min_value()).abs();
147        let target_step = (span * 0.1).max(base_step);
148        let delta = if base_step > 0. && base_step.is_finite() {
149            (target_step / base_step).round().max(1.) * base_step
150        } else {
151            target_step
152        };
153        state.step_thumb(thumb == RangeThumb::Start, direction * delta, window, cx);
154    });
155}
156
157fn jump_bound(
158    state: &Entity<SliderState>,
159    thumb: RangeThumb,
160    to_max: bool,
161    window: &mut Window,
162    cx: &mut App,
163) {
164    state.update(cx, |state, cx| {
165        let value = state.value();
166        let target = match (value.is_range(), thumb, to_max) {
167            (true, RangeThumb::Start, true) => value.end(),
168            (true, RangeThumb::End, false) => value.start(),
169            (_, _, false) => state.min_value(),
170            (_, _, true) => state.max_value(),
171        };
172        let delta = target - thumb.value(value);
173        if delta != 0. {
174            state.step_thumb(thumb == RangeThumb::Start, delta, window, cx);
175        }
176    });
177}
178
179fn horizontal_step_sign(axis: Axis, direction: Direction) -> f32 {
180    if axis == Axis::Horizontal && direction == Direction::Rtl {
181        -1.
182    } else {
183        1.
184    }
185}
186
187#[cfg(test)]
188mod tests {
189    use super::*;
190
191    #[test]
192    fn horizontal_step_sign_reverses_only_horizontal_rtl() {
193        assert_eq!(horizontal_step_sign(Axis::Horizontal, Direction::Ltr), 1.);
194        assert_eq!(horizontal_step_sign(Axis::Horizontal, Direction::Rtl), -1.);
195        assert_eq!(horizontal_step_sign(Axis::Vertical, Direction::Ltr), 1.);
196        assert_eq!(horizontal_step_sign(Axis::Vertical, Direction::Rtl), 1.);
197    }
198}