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