Skip to main content

kitchen_ui/widgets/
stepper.rs

1//! The stepper, the dragged number (scrub label) and the number field that is dragged or typed
2//! (scrub field).
3
4use std::cell::RefCell;
5use std::rc::Rc;
6
7use gpui_kit::component::button::{Button, ButtonVariants as _};
8use gpui_kit::component::{IconName, Sizable as _, h_flex};
9use gpui_kit::prelude::FluentBuilder as _;
10use gpui_kit::{
11    App, CursorStyle, DispatchPhase, InteractiveElement as _, IntoElement, MouseButton, MouseMoveEvent, MouseUpEvent, ParentElement as _,
12    SharedString, Styled as _, TestSupportExt as _, Window, canvas, div, px,
13};
14
15use crate::theme::{self, color};
16
17/// What a stepped number calls with its step (−1 or +1; a fast drag calls it once per step).
18pub type OnStep = Rc<dyn Fn(f32, &mut Window, &mut App)>;
19
20/// What a scrub field calls when it is pressed and let go without being dragged (to type).
21pub type OnClick = Rc<dyn Fn(&mut Window, &mut App)>;
22
23/// Pointer px per step of a dragged number.
24pub const SCRUB_PX: f32 = 6.0;
25
26thread_local! {
27    /// The number being dragged: its id, the pointer x of the last step, and whether it has
28    /// stepped yet (a press let go without a step is a click).
29    static SCRUBBING: RefCell<Option<(String, f32, bool)>> = const { RefCell::new(None) };
30}
31
32/// `− value +`: a number changed in steps, by its buttons or by dragging the number (see
33/// [`scrub_label`]). The caller holds the value and formats it. Element ids: `{id}-minus`,
34/// `{id}-value`, `{id}-plus`. The buttons are gpui-kit's small size, [`theme::XS`] apart
35/// (designparser `touch-target`: about 24 px each).
36pub fn stepper(id: impl Into<String>, value: impl Into<SharedString>, on_step: impl Fn(f32, &mut Window, &mut App) + 'static) -> impl IntoElement {
37    let id: String = id.into();
38    let on_step: OnStep = Rc::new(on_step);
39    let (a, b, c) = (on_step.clone(), on_step.clone(), on_step);
40    h_flex()
41        .gap(px(theme::XS))
42        .child(Button::new(SharedString::from(format!("{id}-minus"))).ghost().small().icon(IconName::Minus).tooltip("Decrease").on_click(move |_, w, cx| a(-1.0, w, cx)))
43        .child(scrub(format!("{id}-value"), value.into(), 52.0, c, None))
44        .child(Button::new(SharedString::from(format!("{id}-plus"))).ghost().small().icon(IconName::Plus).tooltip("Increase").on_click(move |_, w, cx| b(1.0, w, cx)))
45}
46
47/// A number that changes as it is dragged (Affinity, Blender): press it and move left or right;
48/// every [`SCRUB_PX`] px is one step down or up. The pointer may leave it while dragging. The
49/// caller holds the value and formats it; `id` (owned, unique in the window) names the drag.
50pub fn scrub_label(id: impl Into<String>, value: impl Into<SharedString>, on_step: impl Fn(f32, &mut Window, &mut App) + 'static) -> impl IntoElement {
51    scrub(id.into(), value.into(), 0.0, Rc::new(on_step), None)
52}
53
54/// `‹ value ›`: a number dragged left or right to step it (as [`scrub_label`], the chevrons say
55/// so), or pressed and let go without moving to type it: then `on_click` runs and the caller
56/// shows its own text input in its place (it holds the value, formats it and parses it back).
57/// Element id: `id`.
58pub fn scrub_field(
59    id: impl Into<String>,
60    value: impl Into<SharedString>,
61    on_step: impl Fn(f32, &mut Window, &mut App) + 'static,
62    on_click: impl Fn(&mut Window, &mut App) + 'static,
63) -> impl IntoElement {
64    scrub(id.into(), value.into(), 0.0, Rc::new(on_step), Some(Rc::new(on_click)))
65}
66
67fn scrub(id: String, value: SharedString, min_w: f32, on_step: OnStep, on_click: Option<OnClick>) -> impl IntoElement {
68    let active = SCRUBBING.with(|s| s.borrow().as_ref().is_some_and(|(k, ..)| *k == id));
69    let field = on_click.is_some();
70    let down_id = id.clone();
71    let click_id = id.clone();
72    // While dragging, the window's pointer events drive it (the pointer leaves the number)
73    let listener = canvas(
74        |_, _, _| {},
75        move |bounds, _, window, _| {
76            if !active {
77                return;
78            }
79            let (id, step) = (id.clone(), on_step.clone());
80            let up_id = id.clone();
81            window.on_mouse_event(move |e: &MouseMoveEvent, phase, window, cx| {
82                if phase != DispatchPhase::Bubble {
83                    return;
84                }
85                if e.pressed_button != Some(MouseButton::Left) {
86                    SCRUBBING.with(|s| *s.borrow_mut() = None);
87                    window.refresh();
88                    return;
89                }
90                let x = e.position.x.as_f32();
91                let steps = SCRUBBING.with(|s| match &mut *s.borrow_mut() {
92                    Some((k, last, stepped)) if *k == id => {
93                        let n = ((x - *last) / SCRUB_PX).trunc();
94                        *last += n * SCRUB_PX;
95                        *stepped |= n != 0.0;
96                        n as i32
97                    }
98                    _ => 0,
99                });
100                for _ in 0..steps.unsigned_abs() {
101                    step(steps.signum() as f32, window, cx);
102                }
103            });
104            // A drag ends wherever the pointer is let go; a press let go on the number without
105            // a step is a click, which the number's own release handles
106            window.on_mouse_event(move |e: &MouseUpEvent, phase, window, _| {
107                if phase != DispatchPhase::Bubble {
108                    return;
109                }
110                let click = field && bounds.contains(&e.position);
111                SCRUBBING.with(|s| {
112                    let mut s = s.borrow_mut();
113                    if s.as_ref().is_some_and(|(k, _, stepped)| *k == up_id && !(click && !*stepped)) {
114                        *s = None;
115                    }
116                });
117                window.refresh();
118            });
119        },
120    )
121    .absolute()
122    .size_full();
123    div()
124        .id(SharedString::from(down_id.clone()))
125        .test_support()
126        .relative()
127        .min_w(px(min_w))
128        .min_h(px(theme::TARGET_MIN))
129        .flex()
130        .items_center()
131        .justify_center()
132        .px(px(theme::XS))
133        .rounded(px(theme::RADIUS_SM))
134        .text_sm()
135        .font_family("monospace")
136        .cursor(CursorStyle::ResizeLeftRight)
137        .when(active, |d| d.bg(color::accent().opacity(0.35)))
138        .when(!active, |d| d.hover(|d| d.bg(color::hover())))
139        .on_mouse_down(MouseButton::Left, move |e, window, cx| {
140            cx.stop_propagation();
141            SCRUBBING.with(|s| *s.borrow_mut() = Some((down_id.clone(), e.position.x.as_f32(), false)));
142            window.refresh();
143        })
144        .when_some(on_click, |d, on_click| {
145            let id = click_id.clone();
146            d.on_mouse_up(MouseButton::Left, move |_, window, cx| {
147                let clicked = SCRUBBING.with(|s| {
148                    let mut s = s.borrow_mut();
149                    let ours = s.as_ref().is_some_and(|(k, _, stepped)| *k == id && !*stepped);
150                    if ours {
151                        *s = None;
152                    }
153                    ours
154                });
155                if clicked {
156                    cx.stop_propagation();
157                    on_click(window, cx);
158                    window.refresh();
159                }
160            })
161        })
162        // The chevrons of a field: it can be dragged either way
163        .when(field, |d| d.gap(px(2.)).child(chevron(IconName::ChevronLeft)))
164        .child(value)
165        .when(field, |d| d.child(chevron(IconName::ChevronRight)))
166        .child(listener)
167}
168
169/// A small muted chevron beside a scrub field's number.
170fn chevron(icon: IconName) -> impl IntoElement {
171    gpui_kit::component::Icon::new(icon).xsmall().text_color(color::text_muted())
172}