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