Skip to main content

gpui_component/
slider.rs

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