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