Skip to main content

gpui_material_components/
slider.rs

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