Skip to main content

kitchen_ui/widgets/
slider.rs

1//! The slider.
2
3use std::cell::{Cell, RefCell};
4use std::rc::Rc;
5
6use gpui_kit::component::h_flex;
7use gpui_kit::prelude::FluentBuilder as _;
8use gpui_kit::{
9    App, Bounds, DispatchPhase, InteractiveElement as _, IntoElement, MouseButton, MouseMoveEvent, MouseUpEvent,
10    ParentElement as _, Pixels, SharedString, Styled as _, TestSupportExt as _, Window, canvas, div, px, relative,
11};
12
13use crate::theme::{self, color};
14
15/// What a slider calls: the new value and whether the drag ended (to commit one undo step).
16pub type OnSlide = Rc<dyn Fn(f32, bool, &mut Window, &mut App)>;
17
18thread_local! {
19    /// The slider being dragged: its id and its track (window px: left, width).
20    static SLIDING: RefCell<Option<(String, f32, f32)>> = const { RefCell::new(None) };
21}
22
23/// Height of the track's pointer target (px): [`theme::TARGET_MIN`], though the bar drawn is 4.
24const TRACK_H: f32 = theme::TARGET_MIN;
25/// Diameter of the thumb (px).
26const THUMB: f32 = 12.;
27
28/// A horizontal slider over `min..=max` with the value printed beside it (`fmt`). A click sets the
29/// value; a drag follows the pointer (even off the track) and ends on release, when `on_change`
30/// gets `true`. It keeps no state: the caller holds the value, and `id` (owned, unique in the
31/// window) names the drag in progress. The track's element id is `{id}-track`.
32pub fn slider(
33    id: impl Into<String>,
34    value: f32,
35    (min, max): (f32, f32),
36    fmt: impl Fn(f32) -> String,
37    on_change: impl Fn(f32, bool, &mut Window, &mut App) + 'static,
38) -> impl IntoElement {
39    let on_change: OnSlide = Rc::new(on_change);
40    let id: String = id.into();
41    let t = ((value - min) / (max - min).max(1e-12)).clamp(0.0, 1.0);
42    let active = SLIDING.with(|s| s.borrow().as_ref().is_some_and(|(k, _, _)| *k == id));
43    let bounds = Rc::new(Cell::new(Bounds::<Pixels>::default()));
44    let to_value =
45        move |x: f32, left: f32, width: f32| min + ((x - left) / width.max(1.0)).clamp(0.0, 1.0) * (max - min);
46    // While dragging, the window's pointer events drive it
47    let (b1, id1, ch1) = (bounds.clone(), id.clone(), on_change.clone());
48    let listener = canvas(
49        move |b, _, _| b1.set(b),
50        move |_, _, window, _| {
51            if !active {
52                return;
53            }
54            let (id, ch) = (id1.clone(), ch1.clone());
55            window.on_mouse_event(move |e: &MouseMoveEvent, phase, window, cx| {
56                if phase != DispatchPhase::Bubble {
57                    return;
58                }
59                let Some((_, left, width)) = SLIDING.with(|s| s.borrow().clone()).filter(|(k, _, _)| *k == id) else {
60                    return;
61                };
62                if e.pressed_button != Some(MouseButton::Left) {
63                    SLIDING.with(|s| *s.borrow_mut() = None);
64                    ch(to_value(e.position.x.as_f32(), left, width), true, window, cx);
65                    window.refresh();
66                    return;
67                }
68                ch(to_value(e.position.x.as_f32(), left, width), false, window, cx);
69            });
70            let (id, ch) = (id1.clone(), ch1.clone());
71            window.on_mouse_event(move |e: &MouseUpEvent, phase, window, cx| {
72                if phase != DispatchPhase::Bubble {
73                    return;
74                }
75                if let Some((_, left, width)) = SLIDING.with(|s| s.borrow_mut().take()).filter(|(k, _, _)| *k == id) {
76                    ch(to_value(e.position.x.as_f32(), left, width), true, window, cx);
77                    window.refresh();
78                }
79            });
80        },
81    )
82    .absolute()
83    .size_full();
84    let (b2, id2, ch2) = (bounds, id.clone(), on_change);
85    let bar_top = (TRACK_H - 4.) / 2.;
86    let track = div()
87        .id(SharedString::from(format!("{id}-track")))
88        .relative()
89        .flex_1()
90        .min_w(px(60.))
91        .h(px(TRACK_H))
92        .cursor_pointer()
93        .on_mouse_down(MouseButton::Left, move |e, window, cx| {
94            cx.stop_propagation();
95            let b = b2.get();
96            let (left, width) = (b.origin.x.as_f32(), b.size.width.as_f32());
97            SLIDING.with(|s| *s.borrow_mut() = Some((id2.clone(), left, width)));
98            ch2(to_value(e.position.x.as_f32(), left, width), false, window, cx);
99            window.refresh();
100        })
101        // The track, its filled part (a mark: ≥ 3:1 on the panel), the thumb
102        .child(div().absolute().left_0().right_0().top(px(bar_top)).h(px(4.)).rounded_full().bg(color::control()))
103        .child(
104            div().absolute().left_0().top(px(bar_top)).h(px(4.)).w(relative(t)).rounded_full().bg(color::accent_mark()),
105        )
106        .child(
107            div()
108                .absolute()
109                .top(px((TRACK_H - THUMB) / 2.))
110                .left(relative(t))
111                .ml(px(-THUMB / 2.))
112                .size(px(THUMB))
113                .rounded_full()
114                .bg(gpui_kit::white())
115                .border_color(color::accent_mark())
116                .map(|d| if active { d.border_2() } else { d.border_1() }),
117        )
118        .child(listener)
119        .test_support();
120    h_flex()
121        .w_full()
122        .min_w_0()
123        .gap(px(theme::SM))
124        .child(track)
125        .child(div().flex_none().w(px(44.)).text_right().text_xs().font_family("monospace").child(fmt(value)))
126}