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