Skip to main content

fc_ui/capabilities/controls/
slider.rs

1use crate::capabilities::foundation::theme::use_theme;
2use gpui::{prelude::*, *};
3use std::rc::Rc;
4
5/// Shared slider math used by both `Slider` and `RangeSlider`.
6///
7/// Normalized 0..=1 track position of `value` between `min` and `max`.
8pub(crate) fn value_percentage(value: f32, min: f32, max: f32) -> f32 {
9    if max == min {
10        return 0.0;
11    }
12    ((value - min) / (max - min)).clamp(0.0, 1.0)
13}
14
15/// Clamp `value` into `lo..=hi`, snap it to the nearest `step` multiple, and
16/// clamp again so the result stays in range.
17pub(crate) fn snap_to_step(value: f32, step: f32, lo: f32, hi: f32) -> f32 {
18    ((value.clamp(lo, hi) / step).round() * step).clamp(lo, hi)
19}
20
21/// Track-relative drag percentage for a horizontal slider. `None` when the
22/// track has no width yet.
23pub(crate) fn horizontal_drag_percentage(
24    bounds: Bounds<Pixels>,
25    position: Point<Pixels>,
26) -> Option<f32> {
27    let width = bounds.size.width;
28    if width <= px(0.0) {
29        return None;
30    }
31    let relative_x = (position.x - bounds.left()).clamp(px(0.0), width);
32    Some((relative_x / width).clamp(0.0, 1.0))
33}
34
35/// Track-relative drag percentage for a vertical slider (0 at the bottom).
36/// `None` when the track has no height yet.
37pub(crate) fn vertical_drag_percentage(
38    bounds: Bounds<Pixels>,
39    position: Point<Pixels>,
40) -> Option<f32> {
41    let height = bounds.size.height;
42    if height <= px(0.0) {
43        return None;
44    }
45    let relative_y = (position.y - bounds.top()).clamp(px(0.0), height);
46    Some(1.0 - (relative_y / height).clamp(0.0, 1.0))
47}
48
49/// New (unclamped) value for a slider navigation key, or `None` when the key
50/// is not a slider key. Callers pass the result through their clamping
51/// setters.
52pub(crate) fn keyboard_value(key: &str, value: f32, step: f32, min: f32, max: f32) -> Option<f32> {
53    match key {
54        "left" | "down" => Some(value - step),
55        "right" | "up" => Some(value + step),
56        "home" => Some(min),
57        "end" => Some(max),
58        _ => None,
59    }
60}
61
62#[derive(Copy, Clone, Debug, PartialEq, Eq)]
63pub enum SliderSize {
64    Sm,
65    Md,
66    Lg,
67}
68
69#[derive(Copy, Clone, Debug, PartialEq, Eq)]
70pub enum SliderAxis {
71    Horizontal,
72    Vertical,
73}
74
75impl SliderSize {
76    pub fn track_height(&self) -> Pixels {
77        match self {
78            SliderSize::Sm => px(2.0),
79            SliderSize::Md => px(4.0),
80            SliderSize::Lg => px(6.0),
81        }
82    }
83
84    pub fn thumb_width(&self) -> Pixels {
85        match self {
86            SliderSize::Sm => px(16.0),
87            SliderSize::Md => px(20.0),
88            SliderSize::Lg => px(24.0),
89        }
90    }
91
92    pub fn thumb_height(&self) -> Pixels {
93        match self {
94            SliderSize::Sm => px(12.0),
95            SliderSize::Md => px(16.0),
96            SliderSize::Lg => px(20.0),
97        }
98    }
99}
100
101pub struct SliderState {
102    min: f32,
103    max: f32,
104    value: f32,
105    step: f32,
106    focus_handle: FocusHandle,
107    is_dragging: bool,
108    bounds: Bounds<Pixels>,
109}
110
111impl SliderState {
112    pub fn new(cx: &mut Context<Self>) -> Self {
113        Self {
114            min: 0.0,
115            max: 100.0,
116            value: 0.0,
117            step: 1.0,
118            focus_handle: cx.focus_handle(),
119            is_dragging: false,
120            bounds: Bounds::default(),
121        }
122    }
123
124    pub fn min(&self) -> f32 {
125        self.min
126    }
127
128    /// Set the minimum. If `min` exceeds the current maximum, the maximum is
129    /// raised to `min`, so the ordering `min <= max` is always preserved.
130    pub fn set_min(&mut self, min: f32, cx: &mut Context<Self>) {
131        self.min = min;
132        self.max = self.max.max(self.min);
133        self.value = self.value.clamp(self.min, self.max);
134        cx.notify();
135    }
136
137    pub fn max(&self) -> f32 {
138        self.max
139    }
140
141    /// Set the maximum. If `max` is below the current minimum, the minimum is
142    /// lowered to `max`, so the ordering `min <= max` is always preserved.
143    pub fn set_max(&mut self, max: f32, cx: &mut Context<Self>) {
144        self.max = max;
145        self.min = self.min.min(self.max);
146        self.value = self.value.clamp(self.min, self.max);
147        cx.notify();
148    }
149
150    pub fn value(&self) -> f32 {
151        self.value
152    }
153
154    pub fn set_value(&mut self, value: f32, cx: &mut Context<Self>) {
155        let stepped = snap_to_step(value, self.step, self.min, self.max);
156
157        if (self.value - stepped).abs() > f32::EPSILON {
158            self.value = stepped;
159            cx.notify();
160        }
161    }
162
163    pub fn step(&self) -> f32 {
164        self.step
165    }
166
167    pub fn set_step(&mut self, step: f32, cx: &mut Context<Self>) {
168        self.step = step;
169        cx.notify();
170    }
171
172    fn percentage(&self) -> f32 {
173        value_percentage(self.value, self.min, self.max)
174    }
175
176    fn update_from_position(&mut self, position: Point<Pixels>, cx: &mut Context<Self>) {
177        let Some(percentage) = horizontal_drag_percentage(self.bounds, position) else {
178            return;
179        };
180        self.set_value(self.min + percentage * (self.max - self.min), cx);
181    }
182
183    fn update_from_position_vertical(&mut self, position: Point<Pixels>, cx: &mut Context<Self>) {
184        let Some(percentage) = vertical_drag_percentage(self.bounds, position) else {
185            return;
186        };
187        self.set_value(self.min + percentage * (self.max - self.min), cx);
188    }
189}
190
191impl Focusable for SliderState {
192    fn focus_handle(&self, _: &App) -> FocusHandle {
193        self.focus_handle.clone()
194    }
195}
196
197impl Render for SliderState {
198    fn render(&mut self, _: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
199        div()
200    }
201}
202
203#[derive(IntoElement)]
204pub struct Slider {
205    state: Entity<SliderState>,
206    size: SliderSize,
207    axis: SliderAxis,
208    disabled: bool,
209    show_value: bool,
210    on_change: Option<Rc<dyn Fn(f32, &mut Window, &mut App) + 'static>>,
211    style: StyleRefinement,
212}
213
214impl Slider {
215    pub fn new(state: Entity<SliderState>) -> Self {
216        Self {
217            state,
218            size: SliderSize::Md,
219            axis: SliderAxis::Horizontal,
220            disabled: false,
221            show_value: false,
222            on_change: None,
223            style: StyleRefinement::default(),
224        }
225    }
226
227    pub fn size(mut self, size: SliderSize) -> Self {
228        self.size = size;
229        self
230    }
231
232    pub fn horizontal(mut self) -> Self {
233        self.axis = SliderAxis::Horizontal;
234        self
235    }
236
237    pub fn vertical(mut self) -> Self {
238        self.axis = SliderAxis::Vertical;
239        self
240    }
241
242    pub fn disabled(mut self, disabled: bool) -> Self {
243        self.disabled = disabled;
244        self
245    }
246
247    pub fn show_value(mut self, show: bool) -> Self {
248        self.show_value = show;
249        self
250    }
251
252    pub fn on_change(mut self, handler: impl Fn(f32, &mut Window, &mut App) + 'static) -> Self {
253        self.on_change = Some(Rc::new(handler));
254        self
255    }
256}
257
258impl Styled for Slider {
259    fn style(&mut self) -> &mut StyleRefinement {
260        &mut self.style
261    }
262}
263
264impl Slider {
265    fn render_horizontal(
266        self,
267        window: &mut Window,
268        theme: crate::capabilities::foundation::theme::Theme,
269        focus_handle: FocusHandle,
270        is_focused: bool,
271        percentage: f32,
272        value: f32,
273        track_height: Pixels,
274        thumb_width: Pixels,
275        thumb_height: Pixels,
276        track_bg: Hsla,
277        active_bg: Hsla,
278        thumb_bg: Hsla,
279        focus_ring: BoxShadow,
280        user_style: StyleRefinement,
281    ) -> Div {
282        div()
283            .flex()
284            .items_center()
285            .gap_3()
286            .w_full()
287            .map(|this| {
288                let mut div = this;
289                div.style().refine(&user_style);
290                div
291            })
292            .child(
293                div()
294                    .relative()
295                    .flex_1()
296                    .h(thumb_height)
297                    .flex()
298                    .items_center()
299                    .when(!self.disabled, |this| {
300                        this.track_focus(&focus_handle.tab_index(0).tab_stop(true))
301                    })
302                    .when(is_focused && !self.disabled, |this| {
303                        this.shadow(smallvec::smallvec![focus_ring])
304                    })
305                    .rounded(theme.tokens.radius_md)
306                    .when(!self.disabled, |this| {
307                        let on_change_for_key = self.on_change.clone();
308                        this.on_key_down(window.listener_for(
309                            &self.state,
310                            move |state, e: &KeyDownEvent, window, cx| {
311                                let Some(new_value) = keyboard_value(
312                                    e.keystroke.key.as_str(),
313                                    state.value,
314                                    state.step,
315                                    state.min,
316                                    state.max,
317                                ) else {
318                                    return;
319                                };
320                                state.set_value(new_value, cx);
321                                cx.stop_propagation();
322                                if let Some(ref handler) = on_change_for_key {
323                                    handler(state.value, window, cx);
324                                }
325                            },
326                        ))
327                    })
328                    .child(
329                        canvas(
330                            {
331                                let state = self.state.clone();
332                                move |bounds, _, cx| {
333                                    state.update(cx, |state, _| {
334                                        state.bounds = bounds;
335                                    });
336                                }
337                            },
338                            |_, _, _, _| {},
339                        )
340                        .absolute()
341                        .size_full(),
342                    )
343                    .child(
344                        div()
345                            .relative()
346                            .w_full()
347                            .h(track_height)
348                            .rounded_full()
349                            .bg(track_bg)
350                            .overflow_hidden()
351                            .child(
352                                div()
353                                    .absolute()
354                                    .left_0()
355                                    .top_0()
356                                    .h_full()
357                                    .w(relative(percentage))
358                                    .bg(active_bg),
359                            ),
360                    )
361                    .child({
362                        let state_clone = self.state.clone();
363                        let on_change_thumb = self.on_change.clone();
364
365                        div()
366                            .absolute()
367                            .left(relative(percentage))
368                            .top_0()
369                            .ml(-(thumb_width / 2.0))
370                            .w(thumb_width)
371                            .h(thumb_height)
372                            .rounded(thumb_height / 2.0)
373                            .bg(thumb_bg)
374                            .border_2()
375                            .border_color(theme.tokens.background)
376                            .when(!self.disabled, |this| {
377                                this.shadow(smallvec::smallvec![theme.tokens.shadow_sm])
378                                    .cursor(CursorStyle::PointingHand)
379                            })
380                            .when(!self.disabled, |this| {
381                                this.on_mouse_down(
382                                    MouseButton::Left,
383                                    window.listener_for(
384                                        &state_clone,
385                                        move |state, e: &MouseDownEvent, window, cx| {
386                                            state.is_dragging = true;
387                                            state.update_from_position(e.position, cx);
388
389                                            if let Some(ref handler) = on_change_thumb {
390                                                handler(state.value, window, cx);
391                                            }
392
393                                            cx.stop_propagation();
394                                        },
395                                    ),
396                                )
397                            })
398                    })
399                    .when(!self.disabled, |this| {
400                        let state_bar = self.state.clone();
401                        let on_change_bar = self.on_change.clone();
402
403                        this.on_mouse_down(
404                            MouseButton::Left,
405                            window.listener_for(
406                                &state_bar,
407                                move |state, e: &MouseDownEvent, window, cx| {
408                                    state.is_dragging = true;
409                                    state.update_from_position(e.position, cx);
410
411                                    if let Some(ref handler) = on_change_bar {
412                                        handler(state.value, window, cx);
413                                    }
414                                },
415                            ),
416                        )
417                        .on_mouse_move({
418                            let state_move = self.state.clone();
419                            let on_change_move = self.on_change.clone();
420
421                            window.listener_for(
422                                &state_move,
423                                move |state, e: &MouseMoveEvent, window, cx| {
424                                    if state.is_dragging {
425                                        state.update_from_position(e.position, cx);
426
427                                        if let Some(ref handler) = on_change_move {
428                                            handler(state.value, window, cx);
429                                        }
430                                    }
431                                },
432                            )
433                        })
434                        .on_mouse_up(
435                            MouseButton::Left,
436                            window.listener_for(
437                                &self.state,
438                                move |state, _: &MouseUpEvent, _, _cx| {
439                                    state.is_dragging = false;
440                                },
441                            ),
442                        )
443                        .on_mouse_up_out(
444                            MouseButton::Left,
445                            window.listener_for(
446                                &self.state,
447                                move |state, _: &MouseUpEvent, _, _cx| {
448                                    state.is_dragging = false;
449                                },
450                            ),
451                        )
452                    }),
453            )
454            .when(self.show_value, |this| {
455                this.child(
456                    div()
457                        .min_w(px(40.0))
458                        .text_center()
459                        .text_sm()
460                        .text_color(theme.tokens.foreground)
461                        .child(format!("{:.0}", value)),
462                )
463            })
464    }
465
466    fn render_vertical(
467        self,
468        window: &mut Window,
469        theme: crate::capabilities::foundation::theme::Theme,
470        focus_handle: FocusHandle,
471        is_focused: bool,
472        percentage: f32,
473        value: f32,
474        track_height: Pixels,
475        thumb_width: Pixels,
476        thumb_height: Pixels,
477        track_bg: Hsla,
478        active_bg: Hsla,
479        thumb_bg: Hsla,
480        focus_ring: BoxShadow,
481        user_style: StyleRefinement,
482    ) -> Div {
483        div()
484            .flex()
485            .flex_col()
486            .items_center()
487            .gap_3()
488            .h_full()
489            .map(|this| {
490                let mut div = this;
491                div.style().refine(&user_style);
492                div
493            })
494            .child(
495                div()
496                    .relative()
497                    .flex_1()
498                    .w(thumb_width)
499                    .flex()
500                    .items_center()
501                    .justify_center()
502                    .when(!self.disabled, |this| {
503                        this.track_focus(&focus_handle.tab_index(0).tab_stop(true))
504                    })
505                    .when(is_focused && !self.disabled, |this| {
506                        this.shadow(smallvec::smallvec![focus_ring])
507                    })
508                    .rounded(theme.tokens.radius_md)
509                    .when(!self.disabled, |this| {
510                        let on_change_for_key = self.on_change.clone();
511                        this.on_key_down(window.listener_for(
512                            &self.state,
513                            move |state, e: &KeyDownEvent, window, cx| {
514                                let Some(new_value) = keyboard_value(
515                                    e.keystroke.key.as_str(),
516                                    state.value,
517                                    state.step,
518                                    state.min,
519                                    state.max,
520                                ) else {
521                                    return;
522                                };
523                                state.set_value(new_value, cx);
524                                cx.stop_propagation();
525                                if let Some(ref handler) = on_change_for_key {
526                                    handler(state.value, window, cx);
527                                }
528                            },
529                        ))
530                    })
531                    .child(
532                        canvas(
533                            {
534                                let state = self.state.clone();
535                                move |bounds, _, cx| {
536                                    state.update(cx, |state, _| {
537                                        state.bounds = bounds;
538                                    });
539                                }
540                            },
541                            |_, _, _, _| {},
542                        )
543                        .absolute()
544                        .size_full(),
545                    )
546                    .child(
547                        div()
548                            .relative()
549                            .h_full()
550                            .w(track_height)
551                            .rounded_full()
552                            .bg(track_bg)
553                            .overflow_hidden()
554                            .child(
555                                div()
556                                    .absolute()
557                                    .left_0()
558                                    .bottom_0()
559                                    .w_full()
560                                    .h(relative(percentage))
561                                    .bg(active_bg),
562                            ),
563                    )
564                    .child({
565                        let state_clone = self.state.clone();
566                        let on_change_thumb = self.on_change.clone();
567
568                        div()
569                            .absolute()
570                            .left_0()
571                            .bottom(relative(percentage))
572                            .mb(-(thumb_height / 2.0))
573                            .w(thumb_width)
574                            .h(thumb_height)
575                            .rounded(thumb_width / 2.0)
576                            .bg(thumb_bg)
577                            .border_2()
578                            .border_color(theme.tokens.background)
579                            .when(!self.disabled, |this| {
580                                this.shadow(smallvec::smallvec![theme.tokens.shadow_sm])
581                                    .cursor(CursorStyle::PointingHand)
582                            })
583                            .when(!self.disabled, |this| {
584                                this.on_mouse_down(
585                                    MouseButton::Left,
586                                    window.listener_for(
587                                        &state_clone,
588                                        move |state, e: &MouseDownEvent, window, cx| {
589                                            state.is_dragging = true;
590                                            state.update_from_position_vertical(e.position, cx);
591
592                                            if let Some(ref handler) = on_change_thumb {
593                                                handler(state.value, window, cx);
594                                            }
595
596                                            cx.stop_propagation();
597                                        },
598                                    ),
599                                )
600                            })
601                    })
602                    .when(!self.disabled, |this| {
603                        let state_bar = self.state.clone();
604                        let on_change_bar = self.on_change.clone();
605
606                        this.on_mouse_down(
607                            MouseButton::Left,
608                            window.listener_for(
609                                &state_bar,
610                                move |state, e: &MouseDownEvent, window, cx| {
611                                    state.is_dragging = true;
612                                    state.update_from_position_vertical(e.position, cx);
613
614                                    if let Some(ref handler) = on_change_bar {
615                                        handler(state.value, window, cx);
616                                    }
617                                },
618                            ),
619                        )
620                        .on_mouse_move({
621                            let state_move = self.state.clone();
622                            let on_change_move = self.on_change.clone();
623
624                            window.listener_for(
625                                &state_move,
626                                move |state, e: &MouseMoveEvent, window, cx| {
627                                    if state.is_dragging {
628                                        state.update_from_position_vertical(e.position, cx);
629
630                                        if let Some(ref handler) = on_change_move {
631                                            handler(state.value, window, cx);
632                                        }
633                                    }
634                                },
635                            )
636                        })
637                        .on_mouse_up(
638                            MouseButton::Left,
639                            window.listener_for(
640                                &self.state,
641                                move |state, _: &MouseUpEvent, _, _cx| {
642                                    state.is_dragging = false;
643                                },
644                            ),
645                        )
646                        .on_mouse_up_out(
647                            MouseButton::Left,
648                            window.listener_for(
649                                &self.state,
650                                move |state, _: &MouseUpEvent, _, _cx| {
651                                    state.is_dragging = false;
652                                },
653                            ),
654                        )
655                    }),
656            )
657            .when(self.show_value, |this| {
658                this.child(
659                    div()
660                        .min_h(px(24.0))
661                        .text_center()
662                        .text_sm()
663                        .text_color(theme.tokens.foreground)
664                        .child(format!("{:.0}", value)),
665                )
666            })
667    }
668}
669
670impl RenderOnce for Slider {
671    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
672        let theme = use_theme(cx);
673        let state = self.state.read(cx);
674        let focus_handle = state.focus_handle(cx);
675        let is_focused = focus_handle.is_focused(window);
676        let percentage = state.percentage();
677        let value = state.value;
678
679        let track_height = self.size.track_height();
680        let thumb_width = self.size.thumb_width();
681        let thumb_height = self.size.thumb_height();
682
683        let (track_bg, active_bg, thumb_bg) = if self.disabled {
684            (
685                theme.tokens.muted.opacity(0.3),
686                theme.tokens.primary.opacity(0.3),
687                theme.tokens.primary.opacity(0.3),
688            )
689        } else {
690            (
691                theme.tokens.muted,
692                theme.tokens.primary,
693                theme.tokens.primary,
694            )
695        };
696
697        let focus_ring = theme.tokens.focus_ring_light();
698        let user_style = self.style.clone();
699
700        match self.axis {
701            SliderAxis::Horizontal => self.render_horizontal(
702                window,
703                theme,
704                focus_handle,
705                is_focused,
706                percentage,
707                value,
708                track_height,
709                thumb_width,
710                thumb_height,
711                track_bg,
712                active_bg,
713                thumb_bg,
714                focus_ring,
715                user_style,
716            ),
717            SliderAxis::Vertical => self.render_vertical(
718                window,
719                theme,
720                focus_handle,
721                is_focused,
722                percentage,
723                value,
724                track_height,
725                thumb_width,
726                thumb_height,
727                track_bg,
728                active_bg,
729                thumb_bg,
730                focus_ring,
731                user_style,
732            ),
733        }
734    }
735}
736
737#[cfg(test)]
738mod tests {
739    use super::*;
740
741    #[gpui::test]
742    fn set_min_above_current_max_preserves_ordering() {
743        let mut app = TestApp::new();
744        let slider = app.update(|cx| cx.new(SliderState::new));
745
746        app.update(|cx| {
747            slider.update(cx, |state, cx| {
748                state.set_value(50.0, cx);
749                // 修复前:max 仍是 100,value.clamp(min, max) 因 min > max 在 f32::clamp 内 panic
750                state.set_min(120.0, cx);
751                assert!(state.min() <= state.max(), "min must never exceed max");
752                assert_eq!(state.max(), 120.0);
753                assert_eq!(state.value(), 120.0, "value must clamp into the new range");
754            });
755        });
756    }
757
758    #[gpui::test]
759    fn set_max_below_current_min_preserves_ordering() {
760        let mut app = TestApp::new();
761        let slider = app.update(|cx| cx.new(SliderState::new));
762
763        app.update(|cx| {
764            slider.update(cx, |state, cx| {
765                state.set_value(50.0, cx);
766                // 修复前:min 仍是 0,value.clamp(0, -10) 同样 panic
767                state.set_max(-10.0, cx);
768                assert!(state.min() <= state.max(), "min must never exceed max");
769                assert_eq!(state.min(), -10.0);
770                assert_eq!(state.value(), -10.0, "value must clamp into the new range");
771            });
772        });
773    }
774}