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,
12    ParentElement as _, 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(
37    id: impl Into<String>,
38    value: impl Into<SharedString>,
39    on_step: impl Fn(f32, &mut Window, &mut App) + 'static,
40) -> impl IntoElement {
41    let id: String = id.into();
42    let on_step: OnStep = Rc::new(on_step);
43    let (a, b, c) = (on_step.clone(), on_step.clone(), on_step);
44    h_flex()
45        .gap(px(theme::XS))
46        .child(
47            Button::new(SharedString::from(format!("{id}-minus")))
48                .ghost()
49                .small()
50                .icon(IconName::Minus)
51                .tooltip("Decrease")
52                .on_click(move |_, w, cx| a(-1.0, w, cx)),
53        )
54        .child(scrub(format!("{id}-value"), value.into(), 52.0, c, None))
55        .child(
56            Button::new(SharedString::from(format!("{id}-plus")))
57                .ghost()
58                .small()
59                .icon(IconName::Plus)
60                .tooltip("Increase")
61                .on_click(move |_, w, cx| b(1.0, w, cx)),
62        )
63}
64
65/// A number that changes as it is dragged (Affinity, Blender): press it and move left or right;
66/// every [`SCRUB_PX`] px is one step down or up. The pointer may leave it while dragging. The
67/// caller holds the value and formats it; `id` (owned, unique in the window) names the drag.
68pub fn scrub_label(
69    id: impl Into<String>,
70    value: impl Into<SharedString>,
71    on_step: impl Fn(f32, &mut Window, &mut App) + 'static,
72) -> impl IntoElement {
73    scrub(id.into(), value.into(), 0.0, Rc::new(on_step), None)
74}
75
76/// `‹ value ›`: a number dragged left or right to step it (as [`scrub_label`], the chevrons say
77/// so), or pressed and let go without moving to type it: then `on_click` runs and the caller
78/// shows its own text input in its place (it holds the value, formats it and parses it back).
79/// Element id: `id`.
80pub fn scrub_field(
81    id: impl Into<String>,
82    value: impl Into<SharedString>,
83    on_step: impl Fn(f32, &mut Window, &mut App) + 'static,
84    on_click: impl Fn(&mut Window, &mut App) + 'static,
85) -> impl IntoElement {
86    scrub(id.into(), value.into(), 0.0, Rc::new(on_step), Some(Rc::new(on_click)))
87}
88
89fn scrub(id: String, value: SharedString, min_w: f32, on_step: OnStep, on_click: Option<OnClick>) -> impl IntoElement {
90    let active = SCRUBBING.with(|s| s.borrow().as_ref().is_some_and(|(k, ..)| *k == id));
91    let field = on_click.is_some();
92    let down_id = id.clone();
93    let click_id = id.clone();
94    // While dragging, the window's pointer events drive it (the pointer leaves the number)
95    let listener = canvas(
96        |_, _, _| {},
97        move |bounds, _, window, _| {
98            if !active {
99                return;
100            }
101            let (id, step) = (id.clone(), on_step.clone());
102            let up_id = id.clone();
103            window.on_mouse_event(move |e: &MouseMoveEvent, phase, window, cx| {
104                if phase != DispatchPhase::Bubble {
105                    return;
106                }
107                if e.pressed_button != Some(MouseButton::Left) {
108                    SCRUBBING.with(|s| *s.borrow_mut() = None);
109                    window.refresh();
110                    return;
111                }
112                let x = e.position.x.as_f32();
113                let steps = SCRUBBING.with(|s| match &mut *s.borrow_mut() {
114                    Some((k, last, stepped)) if *k == id => {
115                        let n = ((x - *last) / SCRUB_PX).trunc();
116                        *last += n * SCRUB_PX;
117                        *stepped |= n != 0.0;
118                        n as i32
119                    }
120                    _ => 0,
121                });
122                for _ in 0..steps.unsigned_abs() {
123                    step(steps.signum() as f32, window, cx);
124                }
125            });
126            // A drag ends wherever the pointer is let go; a press let go on the number without
127            // a step is a click, which the number's own release handles
128            window.on_mouse_event(move |e: &MouseUpEvent, phase, window, _| {
129                if phase != DispatchPhase::Bubble {
130                    return;
131                }
132                let click = field && bounds.contains(&e.position);
133                SCRUBBING.with(|s| {
134                    let mut s = s.borrow_mut();
135                    if s.as_ref().is_some_and(|(k, _, stepped)| *k == up_id && !(click && !*stepped)) {
136                        *s = None;
137                    }
138                });
139                window.refresh();
140            });
141        },
142    )
143    .absolute()
144    .size_full();
145    div()
146        .id(SharedString::from(down_id.clone()))
147        .test_support()
148        .relative()
149        .min_w(px(min_w))
150        .min_h(px(theme::TARGET_MIN))
151        .flex()
152        .items_center()
153        .justify_center()
154        .px(px(theme::XS))
155        .rounded(px(theme::RADIUS_SM))
156        .text_sm()
157        .font_family("monospace")
158        .cursor(CursorStyle::ResizeLeftRight)
159        .when(active, |d| d.bg(color::accent().opacity(0.35)))
160        .when(!active, |d| d.hover(|d| d.bg(color::hover())))
161        .on_mouse_down(MouseButton::Left, move |e, window, cx| {
162            cx.stop_propagation();
163            SCRUBBING.with(|s| *s.borrow_mut() = Some((down_id.clone(), e.position.x.as_f32(), false)));
164            window.refresh();
165        })
166        .when_some(on_click, |d, on_click| {
167            let id = click_id.clone();
168            d.on_mouse_up(MouseButton::Left, move |_, window, cx| {
169                let clicked = SCRUBBING.with(|s| {
170                    let mut s = s.borrow_mut();
171                    let ours = s.as_ref().is_some_and(|(k, _, stepped)| *k == id && !*stepped);
172                    if ours {
173                        *s = None;
174                    }
175                    ours
176                });
177                if clicked {
178                    cx.stop_propagation();
179                    on_click(window, cx);
180                    window.refresh();
181                }
182            })
183        })
184        // The chevrons of a field: it can be dragged either way
185        .when(field, |d| d.gap(px(2.)).child(chevron(IconName::ChevronLeft)))
186        .child(value)
187        .when(field, |d| d.child(chevron(IconName::ChevronRight)))
188        .child(listener)
189}
190
191/// A small muted chevron beside a scrub field's number.
192fn chevron(icon: IconName) -> impl IntoElement {
193    gpui_kit::component::Icon::new(icon).xsmall().text_color(color::text_muted())
194}