Skip to main content

gpui_component/
slider.rs

1use std::sync::Arc;
2
3use crate::{ActiveTheme, AxisExt, StyledExt, ThemeStyled as _};
4pub use gpui_base::slider::{SliderEvent, SliderScale, SliderState, SliderValue};
5use gpui_base::{
6    LogicalStyledExt as _, Slider as BaseSlider, SliderIndicator, SliderThumb, SliderTrack, spring,
7};
8
9use gpui::{
10    App, Axis, Background, Corners, DefiniteLength, ElementId, Entity, EntityId, Hsla,
11    InteractiveElement as _, IntoElement, MouseButton, ParentElement as _, Pixels, RenderOnce,
12    SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled, Window, div,
13    prelude::FluentBuilder as _, px, relative,
14};
15
16/// Width of the translucent ring that grows outside a hovered thumb.
17const THUMB_RING_WIDTH: Pixels = px(3.);
18/// Opacity of the fully grown thumb ring.
19const THUMB_RING_OPACITY: f32 = 0.5;
20/// The animated hover ring of one thumb.
21struct ThumbRing {
22    interaction: Entity<ThumbInteraction>,
23    width: Pixels,
24    color: Hsla,
25}
26
27/// Pointer state of one thumb, written by its own listeners and read on the
28/// next frame to size the ring.
29#[derive(Default)]
30struct ThumbInteraction {
31    hovered: bool,
32    pressed: bool,
33}
34
35impl ThumbInteraction {
36    /// The ring shows while the pointer is over the thumb, and stays while the
37    /// thumb is dragged: dragging moves the thumb under the pointer, so hover
38    /// alone drops out for a frame on every move and the ring would flicker.
39    fn is_active(&self) -> bool {
40        self.hovered || self.pressed
41    }
42}
43
44impl ThumbRing {
45    /// Samples the ring for the `start` or end thumb of the slider `id`. The ring
46    /// also shows while the thumb is `focused`: the one the keys move.
47    fn new(
48        id: EntityId,
49        start: bool,
50        focused: bool,
51        color: Hsla,
52        window: &mut Window,
53        cx: &mut App,
54    ) -> Self {
55        let channel = if start { "start" } else { "end" };
56        let interaction = window.use_keyed_state(
57            ElementId::NamedChild(Arc::new(("slider-thumb-ring", id).into()), channel.into()),
58            cx,
59            |_, _| ThumbInteraction::default(),
60        );
61        let progress = spring(
62            (("slider-thumb-ring", id), channel),
63            if focused || interaction.read(cx).is_active() {
64                1.
65            } else {
66                0.
67            },
68            cx.theme().motion_tokens().spring_control,
69            window,
70            cx,
71        );
72
73        Self {
74            interaction,
75            width: THUMB_RING_WIDTH * progress,
76            color: color.alpha(THUMB_RING_OPACITY * progress),
77        }
78    }
79
80    /// Returns a listener that records whether the thumb is being pressed.
81    fn press_listener<E>(&self, pressed: bool) -> impl Fn(&E, &mut Window, &mut App) + use<E> {
82        let interaction = self.interaction.clone();
83        move |_, _, cx| {
84            interaction.update(cx, |interaction, cx| {
85                if interaction.pressed != pressed {
86                    interaction.pressed = pressed;
87                    cx.notify();
88                }
89            });
90        }
91    }
92}
93
94/// A Slider element.
95#[derive(IntoElement)]
96pub struct Slider {
97    state: Entity<SliderState>,
98    axis: Axis,
99    style: StyleRefinement,
100    disabled: bool,
101    accessibility_label: Option<SharedString>,
102    reverse: bool,
103    tab_stop: bool,
104    tab_index: isize,
105}
106
107impl Slider {
108    /// Create a new [`Slider`] element bind to the [`SliderState`].
109    pub fn new(state: &Entity<SliderState>) -> Self {
110        Self {
111            axis: Axis::Horizontal,
112            state: state.clone(),
113            style: StyleRefinement::default(),
114            disabled: false,
115            accessibility_label: None,
116            reverse: false,
117            tab_stop: true,
118            tab_index: 0,
119        }
120    }
121
122    /// As a horizontal slider.
123    pub fn horizontal(mut self) -> Self {
124        self.axis = Axis::Horizontal;
125        self
126    }
127
128    /// As a vertical slider.
129    pub fn vertical(mut self) -> Self {
130        self.axis = Axis::Vertical;
131        self
132    }
133
134    /// Set the disabled state of the slider, default: false
135    pub fn disabled(mut self, disabled: bool) -> Self {
136        self.disabled = disabled;
137        self
138    }
139
140    /// Sets the label exposed to accessibility clients.
141    pub fn accessibility_label(mut self, label: impl Into<SharedString>) -> Self {
142        self.accessibility_label = Some(label.into());
143        self
144    }
145
146    /// Set the tab stop for the slider, default is true.
147    pub fn tab_stop(mut self, tab_stop: bool) -> Self {
148        self.tab_stop = tab_stop;
149        self
150    }
151
152    /// Set the tab index for the slider, default is 0.
153    pub fn tab_index(mut self, tab_index: isize) -> Self {
154        self.tab_index = tab_index;
155        self
156    }
157
158    /// Reverse the filled (highlighted) side of the track, default: false.
159    ///
160    /// By default the track is filled from the min end to the thumb. With
161    /// `reverse`, the fill goes from the thumb to the max end instead — useful
162    /// when the slider represents a remaining amount (e.g. time left).
163    ///
164    /// This only changes the visual fill; values, events and interactions are
165    /// unaffected. It applies to single-value sliders and is ignored for
166    /// range sliders.
167    pub fn reverse(mut self) -> Self {
168        self.reverse = true;
169        self
170    }
171}
172
173impl Styled for Slider {
174    fn style(&mut self) -> &mut StyleRefinement {
175        &mut self.style
176    }
177}
178
179impl RenderOnce for Slider {
180    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
181        let axis = self.axis;
182        let state = self.state.read(cx);
183        let is_range = state.value().is_range();
184        let percentage = state.percentage();
185        let (bar_start, bar_end) = if self.reverse && !is_range {
186            // Fill from the thumb to the max end (remaining side).
187            (relative(percentage.end), relative(0.))
188        } else {
189            (relative(percentage.start), relative(1. - percentage.end))
190        };
191        let rem_size = window.rem_size();
192
193        let bar_color = self
194            .style
195            .background
196            .clone()
197            .and_then(|bg| bg.color())
198            .unwrap_or(cx.theme().tokens.slider_bar.into());
199        let thumb_bg: Background = self
200            .style
201            .text
202            .color
203            .map(Into::into)
204            .unwrap_or_else(|| cx.theme().tokens.slider_thumb.into());
205        let corner_radii = self.style.corner_radii.clone();
206        // The track is a pill by default, and square when the theme squares its
207        // corners. A caller's own corner radii still win.
208        let default_radius = cx.theme().radius_full();
209        let radius = Corners {
210            top_left: corner_radii
211                .top_left
212                .map(|v| v.to_pixels(rem_size))
213                .unwrap_or(default_radius),
214            top_right: corner_radii
215                .top_right
216                .map(|v| v.to_pixels(rem_size))
217                .unwrap_or(default_radius),
218            bottom_left: corner_radii
219                .bottom_left
220                .map(|v| v.to_pixels(rem_size))
221                .unwrap_or(default_radius),
222            bottom_right: corner_radii
223                .bottom_right
224                .map(|v| v.to_pixels(rem_size))
225                .unwrap_or(default_radius),
226        };
227
228        let ring_color = cx.theme().ring;
229        let entity_id = self.state.entity_id();
230        let focus_handle = window
231            .use_keyed_state(("slider-focus", entity_id), cx, |_, cx| cx.focus_handle())
232            .read(cx)
233            .clone();
234        let is_focused = focus_handle.is_focused(window);
235        let start_ring =
236            is_range.then(|| ThumbRing::new(entity_id, true, false, ring_color, window, cx));
237        // The keys move the end thumb, so it carries the focus ring.
238        let end_ring = ThumbRing::new(entity_id, false, is_focused, ring_color, window, cx);
239
240        let thumb = |position: DefiniteLength, start: bool, ring: ThumbRing| {
241            SliderThumb::new(&self.state)
242                .axis(axis)
243                .start(start)
244                .disabled(self.disabled)
245                .when(!self.disabled, |this| {
246                    this.absolute()
247                        .when(axis.is_horizontal(), |this| {
248                            this.top(px(-5.)).inset_s(position, cx).ms(-px(8.), cx)
249                        })
250                        .when(axis.is_vertical(), |this| {
251                            this.bottom(position).left(px(-5.)).mb(-px(8.))
252                        })
253                        .flex()
254                        .items_center()
255                        .justify_center()
256                        .flex_shrink_0()
257                        .rounded_full_style(cx)
258                        .bg(bar_color.opacity(0.5))
259                        .size_4()
260                        .p(px(1.))
261                        .on_hover({
262                            let interaction = ring.interaction.clone();
263                            move |entered, _, cx| {
264                                let entered = *entered;
265                                interaction.update(cx, |interaction, cx| {
266                                    if interaction.hovered != entered {
267                                        interaction.hovered = entered;
268                                        cx.notify();
269                                    }
270                                });
271                            }
272                        })
273                        // The base thumb stops propagation on mouse down to own
274                        // the drag, so the press is read in the capture phase.
275                        .capture_any_mouse_down(ring.press_listener(true))
276                        .capture_any_mouse_up(ring.press_listener(false))
277                        .on_mouse_up_out(MouseButton::Left, ring.press_listener(false))
278                        // The ring grows outward from the thumb's edge: inset by
279                        // its own width so its inner edge sits flush against it.
280                        .child(
281                            div()
282                                .flex_none()
283                                .absolute()
284                                .top(-ring.width)
285                                .left(-ring.width)
286                                .right(-ring.width)
287                                .bottom(-ring.width)
288                                .rounded_full_style(cx)
289                                .border(ring.width)
290                                .border_color(ring.color),
291                        )
292                        .child(
293                            div()
294                                .flex_shrink_0()
295                                .size_full()
296                                .rounded_full_style(cx)
297                                .bg(thumb_bg),
298                        )
299                })
300        };
301
302        BaseSlider::new(&self.state)
303            .axis(axis)
304            .disabled(self.disabled)
305            // Keep the current focus in the dispatch tree when the slider is
306            // disabled while focused, so Tab can still leave in either direction.
307            .when(!self.disabled || is_focused, |this| {
308                this.track_focus(
309                    &focus_handle
310                        .tab_index(self.tab_index)
311                        .tab_stop(self.tab_stop && !self.disabled),
312                )
313            })
314            .when_some(self.accessibility_label, |this, label| {
315                this.accessibility_label(label)
316            })
317            .flex()
318            .flex_1()
319            .items_center()
320            .justify_center()
321            .when(axis.is_vertical(), |this| this.h(px(120.)))
322            .when(axis.is_horizontal(), |this| this.w_full())
323            .refine_style(&self.style)
324            .bg(cx.theme().transparent)
325            .text_color(cx.theme().foreground)
326            .child(
327                SliderTrack::new(&self.state)
328                    .axis(axis)
329                    .disabled(self.disabled)
330                    .flex()
331                    .when(axis.is_horizontal(), |this| {
332                        this.items_center().h_6().w_full()
333                    })
334                    .when(axis.is_vertical(), |this| {
335                        this.justify_center().w_6().h_full()
336                    })
337                    .flex_shrink_0()
338                    .child(
339                        SliderIndicator::new(&self.state)
340                            .relative()
341                            .when(axis.is_horizontal(), |this| this.w_full().h_1p5())
342                            .when(axis.is_vertical(), |this| this.h_full().w_1p5())
343                            .bg(bar_color.opacity(0.2))
344                            .active(|this| this.bg(bar_color.opacity(0.4)))
345                            .corner_radii(radius)
346                            .child(
347                                div()
348                                    .absolute()
349                                    .when(axis.is_horizontal(), |this| {
350                                        // The fill runs from the start edge: the right in RTL.
351                                        this.h_full().inset_s(bar_start, cx).inset_e(bar_end, cx)
352                                    })
353                                    .when(axis.is_vertical(), |this| {
354                                        this.w_full().bottom(bar_start).top(bar_end)
355                                    })
356                                    .bg(bar_color)
357                                    .rounded_full_style(cx),
358                            )
359                            .when_some(start_ring, |this, ring| {
360                                this.child(thumb(relative(percentage.start), true, ring))
361                            })
362                            .child(thumb(relative(percentage.end), false, end_ring)),
363                    ),
364            )
365    }
366}
367
368#[cfg(test)]
369mod tests {
370    use gpui::{AppContext as _, Context, Modifiers, Render, TestAppContext, point};
371
372    use super::*;
373
374    struct Harness {
375        state: Entity<SliderState>,
376        disabled: bool,
377    }
378
379    impl Render for Harness {
380        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
381            div()
382                .w(px(100.))
383                .h(px(24.))
384                .child(Slider::new(&self.state).disabled(self.disabled))
385        }
386    }
387
388    fn harness(
389        cx: &mut TestAppContext,
390        disabled: bool,
391    ) -> (&mut gpui::VisualTestContext, Entity<SliderState>) {
392        cx.update(crate::theme::init);
393        let state = cx.new(|_| SliderState::new());
394        let result = state.clone();
395        let (_, cx) = cx.add_window_view(move |_, _| Harness { state, disabled });
396        cx.update(|window, cx| window.draw(cx).clear(cx));
397        (cx, result)
398    }
399
400    #[gpui::test]
401    fn pointer_updates_the_migrated_state(cx: &mut TestAppContext) {
402        let (cx, state) = harness(cx, false);
403        cx.simulate_click(point(px(50.), px(12.)), Modifiers::default());
404        cx.update(|_, cx| assert!((state.read(cx).value().end() - 50.).abs() < 1.));
405    }
406
407    /// Moves focus as Tab does, then presses `keys`.
408    fn tab_then_press(cx: &mut gpui::VisualTestContext, keys: &str) {
409        cx.update(|window, cx| {
410            window.focus_next(cx);
411            window.draw(cx).clear(cx);
412        });
413        cx.simulate_keystrokes(keys);
414    }
415
416    #[gpui::test]
417    fn tab_reaches_the_slider_and_keys_step_it(cx: &mut TestAppContext) {
418        let (cx, state) = harness(cx, false);
419        tab_then_press(cx, "right right");
420        cx.update(|_, cx| assert_eq!(state.read(cx).value(), SliderValue::Single(2.)));
421        cx.simulate_keystrokes("end");
422        cx.update(|_, cx| assert_eq!(state.read(cx).value(), SliderValue::Single(100.)));
423    }
424
425    #[gpui::test]
426    fn tab_skips_a_disabled_slider(cx: &mut TestAppContext) {
427        let (cx, state) = harness(cx, true);
428        tab_then_press(cx, "right end");
429        cx.update(|_, cx| assert_eq!(state.read(cx).value(), SliderValue::Single(0.)));
430    }
431
432    #[gpui::test]
433    fn disabled_slider_is_inert(cx: &mut TestAppContext) {
434        let (cx, state) = harness(cx, true);
435        cx.simulate_click(point(px(50.), px(12.)), Modifiers::default());
436        cx.update(|_, cx| assert_eq!(state.read(cx).value(), SliderValue::Single(0.)));
437    }
438}