Skip to main content

gpui_material_components/
slider.rs

1mod geometry;
2mod render;
3
4use gpui::{
5    AnyElement, App, Axis, ElementId, Entity, FocusHandle, Hsla, IntoElement, Pixels, Point,
6    SharedString, Size, Window,
7};
8use gpui_material_foundation::InteractionSource;
9
10use crate::ControlSize;
11
12pub use gpui_base::slider::{SliderEvent, SliderScale, SliderState, SliderValue};
13pub use gpui_material_foundation::RangeThumb;
14
15/// Optional track dimensions in logical pixels.
16#[derive(Clone, Copy, Debug, Default, PartialEq)]
17pub struct SliderTrackStyle {
18    /// Cross-axis thickness of the slider track.
19    pub thickness: Option<Pixels>,
20    /// Corner radius at the outer ends of the track.
21    pub outer_radius: Option<Pixels>,
22    /// Corner radius at the inner track edges adjacent to the thumb gap.
23    pub inner_radius: Option<Pixels>,
24    /// Gap between the thumb handle and the active/inactive track segments.
25    pub thumb_gap: Option<Pixels>,
26}
27
28/// Optional dimensions and colors for one handle.
29#[derive(Clone, Copy, Debug, Default, PartialEq)]
30pub struct SliderThumbStyle {
31    /// The first dimension lies along the slider axis, the second across it.
32    pub size: Option<Size<Pixels>>,
33    /// The dimension along the slider axis while the handle is pressed.
34    pub pressed_width: Option<Pixels>,
35    /// Handle fill color when enabled.
36    pub color: Option<Hsla>,
37    /// Handle fill color when disabled.
38    pub disabled_color: Option<Hsla>,
39    /// Handle fill color when keyboard focus is visible.
40    pub focused_color: Option<Hsla>,
41}
42
43/// Optional slider colors. Unspecified fields use the window theme.
44#[derive(Clone, Copy, Debug, Default, PartialEq)]
45pub struct SliderColors {
46    /// Enabled handle fill color.
47    pub thumb: Option<Hsla>,
48    /// Enabled active track fill color.
49    pub active_track: Option<Hsla>,
50    /// Enabled inactive track fill color.
51    pub inactive_track: Option<Hsla>,
52    /// Enabled tick and stop marker color on the active track segment.
53    pub active_tick: Option<Hsla>,
54    /// Enabled tick and stop marker color on the inactive track segment.
55    pub inactive_tick: Option<Hsla>,
56    /// Disabled handle fill color.
57    pub disabled_thumb: Option<Hsla>,
58    /// Disabled active track fill color.
59    pub disabled_active_track: Option<Hsla>,
60    /// Disabled inactive track fill color.
61    pub disabled_inactive_track: Option<Hsla>,
62    /// Disabled tick and stop marker color on the active track segment.
63    pub disabled_active_tick: Option<Hsla>,
64    /// Disabled tick and stop marker color on the inactive track segment.
65    pub disabled_inactive_tick: Option<Hsla>,
66}
67
68/// The window position and default paint of a track tick or stop.
69#[derive(Clone, Copy, Debug, PartialEq)]
70#[non_exhaustive]
71pub struct SliderMarker {
72    /// Center point of the marker in window coordinates.
73    pub center: Point<Pixels>,
74    /// Default marker diameter in logical pixels.
75    pub diameter: Pixels,
76    /// Resolved marker color for the active or inactive track segment.
77    pub color: Hsla,
78}
79
80type DrawMarker = Box<dyn Fn(SliderMarker, &mut Window, &mut App)>;
81type FormatValue = Box<dyn Fn(f32) -> SharedString>;
82
83#[derive(Default)]
84struct ThumbOptions {
85    style: SliderThumbStyle,
86    content: Option<AnyElement>,
87    focus: Option<FocusHandle>,
88    source: Option<Entity<InteractionSource>>,
89    source_key: Option<ElementId>,
90}
91
92fn thumb_index(which: RangeThumb) -> usize {
93    usize::from(which == RangeThumb::End)
94}
95
96fn thumb_id(id: &ElementId, which: RangeThumb) -> ElementId {
97    (
98        id.clone(),
99        if which == RangeThumb::Start {
100            "start"
101        } else {
102            "end"
103        },
104    )
105        .into()
106}
107
108/// Origin of the active track fill for a single-value [`Slider`].
109#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
110pub enum SliderKind {
111    /// Active track extends from the start of the range to the handle (default).
112    #[default]
113    Standard,
114    /// Active track extends symmetrically from the midpoint of the range to the handle.
115    Centered,
116}
117
118/// An Expressive slider. Base owns the value and step grid. The caller retains
119/// the state entity and observes its SliderEvent notifications.
120#[derive(IntoElement)]
121pub struct Slider {
122    id: ElementId,
123    name: SharedString,
124    state: Entity<SliderState>,
125    kind: SliderKind,
126    axis: Axis,
127    reverse_vertical: bool,
128    size: ControlSize,
129    disabled: bool,
130    icon: Option<AnyElement>,
131    tick_intervals: u16,
132    range_end_name: Option<SharedString>,
133    track_style: SliderTrackStyle,
134    track: Option<AnyElement>,
135    thumbs: [ThumbOptions; 2],
136    colors: SliderColors,
137    draw_tick: Option<DrawMarker>,
138    draw_stop: Option<DrawMarker>,
139    show_stop_indicators: bool,
140    value_indicator: bool,
141    format_value: Option<FormatValue>,
142}
143
144impl Slider {
145    /// Creates a horizontal single-value slider bound to `state` with an element ID and accessible name.
146    pub fn new(
147        id: impl Into<ElementId>,
148        name: impl Into<SharedString>,
149        state: &Entity<SliderState>,
150    ) -> Self {
151        Self {
152            id: id.into(),
153            name: name.into(),
154            state: state.clone(),
155            kind: SliderKind::Standard,
156            axis: Axis::Horizontal,
157            reverse_vertical: false,
158            size: ControlSize::ExtraSmall,
159            disabled: false,
160            icon: None,
161            tick_intervals: 0,
162            range_end_name: None,
163            track_style: SliderTrackStyle::default(),
164            track: None,
165            thumbs: Default::default(),
166            colors: SliderColors::default(),
167            draw_tick: None,
168            draw_stop: None,
169            show_stop_indicators: true,
170            value_indicator: true,
171            format_value: None,
172        }
173    }
174
175    /// Supplies the two accessible names of a slider with a Base range value.
176    pub fn range(
177        id: impl Into<ElementId>,
178        start_name: impl Into<SharedString>,
179        end_name: impl Into<SharedString>,
180        state: &Entity<SliderState>,
181    ) -> Self {
182        let mut slider = Self::new(id, start_name, state);
183        slider.range_end_name = Some(end_name.into());
184        slider
185    }
186
187    /// Selects standard start-anchored or centered active track geometry.
188    pub fn kind(mut self, kind: SliderKind) -> Self {
189        self.kind = kind;
190        self
191    }
192
193    /// Sets the slider orientation (`Axis::Horizontal` by default).
194    pub fn axis(mut self, axis: Axis) -> Self {
195        self.axis = axis;
196        self
197    }
198
199    /// Increases vertical sliders from top to bottom. Horizontal sliders follow the window direction.
200    pub fn reverse_vertical(mut self, reverse: bool) -> Self {
201        self.reverse_vertical = reverse;
202        self
203    }
204
205    /// Selects the expressive track size. ExtraSmall (16 dp) is the default.
206    pub fn size(mut self, size: ControlSize) -> Self {
207        self.size = size;
208        self
209    }
210
211    /// Disables pointer dragging, keyboard adjustment, and focus traversal when `true`.
212    pub fn disabled(mut self, disabled: bool) -> Self {
213        self.disabled = disabled;
214        self
215    }
216
217    /// Draws equally spaced ticks in the visual range without changing the Base value scale.
218    /// Pass the number of intervals, including the two endpoints.
219    pub fn tick_intervals(mut self, intervals: u16) -> Self {
220        self.tick_intervals = intervals;
221        self
222    }
223
224    /// Places an optional decorative icon inside the active track on medium and larger sizes.
225    pub fn icon(mut self, icon: impl IntoElement) -> Self {
226        self.icon = Some(icon.into_any_element());
227        self
228    }
229
230    /// Replaces the built-in track, icon, and marker artwork. The slider retains its input region.
231    pub fn track(mut self, element: impl IntoElement) -> Self {
232        self.track = Some(element.into_any_element());
233        self
234    }
235
236    /// Sets the built-in track dimensions. Thickness also sizes a custom track's slot.
237    pub fn track_style(mut self, style: SliderTrackStyle) -> Self {
238        self.track_style = style;
239        self
240    }
241
242    /// Replaces the handle artwork. Use `RangeThumb::End` for a single value.
243    pub fn thumb(mut self, which: RangeThumb, element: impl IntoElement) -> Self {
244        self.thumbs[thumb_index(which)].content = Some(element.into_any_element());
245        self
246    }
247
248    /// Sets per-handle size and colors. Use `RangeThumb::End` for a single value.
249    pub fn thumb_style(mut self, which: RangeThumb, style: SliderThumbStyle) -> Self {
250        self.thumbs[thumb_index(which)].style = style;
251        self
252    }
253
254    /// Overrides enabled and disabled track, thumb, and tick colors.
255    pub fn colors(mut self, colors: SliderColors) -> Self {
256        self.colors = colors;
257        self
258    }
259
260    /// Uses the caller's focus handle for one handle instead of an internal keyed handle.
261    /// Use `RangeThumb::End` for a single-value slider.
262    pub fn track_focus(mut self, which: RangeThumb, focus: &FocusHandle) -> Self {
263        self.thumbs[thumb_index(which)].focus = Some(focus.clone());
264        self
265    }
266
267    /// Observes one handle under the slider ID paired with `"start"` or `"end"`.
268    pub fn interaction_source(
269        mut self,
270        which: RangeThumb,
271        source: &Entity<InteractionSource>,
272    ) -> Self {
273        let entry = &mut self.thumbs[thumb_index(which)];
274        entry.source = Some(source.clone());
275        entry.source_key = None;
276        self
277    }
278
279    #[cfg(feature = "surfaces")]
280    pub(crate) fn interaction_source_with_id(
281        mut self,
282        which: RangeThumb,
283        id: ElementId,
284        source: &Entity<InteractionSource>,
285    ) -> Self {
286        let entry = &mut self.thumbs[thumb_index(which)];
287        entry.source = Some(source.clone());
288        entry.source_key = Some(id);
289        self
290    }
291
292    /// Replaces the default dot painter for visual ticks.
293    pub fn draw_ticks(
294        mut self,
295        draw: impl Fn(SliderMarker, &mut Window, &mut App) + 'static,
296    ) -> Self {
297        self.draw_tick = Some(Box::new(draw));
298        self
299    }
300
301    /// Replaces the default dot painter for track stops.
302    pub fn draw_stop_indicators(
303        mut self,
304        draw: impl Fn(SliderMarker, &mut Window, &mut App) + 'static,
305    ) -> Self {
306        self.draw_stop = Some(Box::new(draw));
307        self
308    }
309
310    /// Controls whether endpoint stop dots are drawn on the track. Defaults to `true`.
311    pub fn show_stop_indicators(mut self, show: bool) -> Self {
312        self.show_stop_indicators = show;
313        self
314    }
315
316    /// Enables the value indicator during dragging and keyboard focus. It is enabled by default.
317    pub fn value_indicator(mut self, show: bool) -> Self {
318        self.value_indicator = show;
319        self
320    }
321
322    /// Formats the current value of the handle whose indicator is visible.
323    pub fn format_value(mut self, format: impl Fn(f32) -> SharedString + 'static) -> Self {
324        self.format_value = Some(Box::new(format));
325        self
326    }
327}