Skip to main content

gpui_component/input/
number_input.rs

1use crate::theme::ActiveTheme;
2use gpui::{
3    AnyElement, App, Entity, FocusHandle, Focusable, InteractiveElement as _,
4    StatefulInteractiveElement as _, Window, div, px,
5};
6use gpui::{
7    IntoElement, ParentElement, RenderOnce, SharedString, StyleRefinement, Styled, TextAlign,
8    prelude::FluentBuilder as _,
9};
10
11use crate::{Disableable, Icon, IconName, Sizable, Size, StyleSized as _, StyledExt as _};
12
13use super::{Input, InputState, input::input_style};
14use crate::ThemeStyled as _;
15use gpui_base::NumberInput as BaseNumberInput;
16pub use gpui_base::{NumberInputEvent, NumberStep, StepAction};
17use rust_i18n::t;
18
19/// A number input element with increment and decrement buttons.
20#[derive(IntoElement)]
21pub struct NumberInput {
22    state: Entity<InputState>,
23    placeholder: SharedString,
24    size: Size,
25    prefix: Option<AnyElement>,
26    suffix: Option<AnyElement>,
27    appearance: bool,
28    focus_ring_enabled: bool,
29    disabled: bool,
30    accessibility_label: Option<SharedString>,
31    stepper: bool,
32    style: StyleRefinement,
33}
34
35impl NumberInput {
36    /// Create a new [`NumberInput`] element bind to the [`InputState`].
37    pub fn new(state: &Entity<InputState>) -> Self {
38        Self {
39            state: state.clone(),
40            size: Size::default(),
41            placeholder: SharedString::default(),
42            prefix: None,
43            suffix: None,
44            appearance: true,
45            focus_ring_enabled: true,
46            disabled: false,
47            accessibility_label: None,
48            stepper: true,
49            style: StyleRefinement::default(),
50        }
51    }
52
53    /// Set the placeholder text of the number input.
54    pub fn placeholder(mut self, placeholder: impl Into<SharedString>) -> Self {
55        self.placeholder = placeholder.into();
56        self
57    }
58
59    /// Set the prefix element of the number input.
60    pub fn prefix(mut self, prefix: impl IntoElement) -> Self {
61        self.prefix = Some(prefix.into_any_element());
62        self
63    }
64
65    /// Set the suffix element of the number input.
66    pub fn suffix(mut self, suffix: impl IntoElement) -> Self {
67        self.suffix = Some(suffix.into_any_element());
68        self
69    }
70
71    /// Set the appearance of the number input, if false will no border and background.
72    pub fn appearance(mut self, appearance: bool) -> Self {
73        self.appearance = appearance;
74        self
75    }
76
77    /// Set the name a screen reader announces.
78    ///
79    /// A number input has no visible text of its own to be named by, so set
80    /// this whenever it is shown without one, for example next to a separate
81    /// label. This does not change what is displayed.
82    pub fn accessibility_label(mut self, label: impl Into<SharedString>) -> Self {
83        self.accessibility_label = Some(label.into());
84        self
85    }
86
87    /// Set whether the increment and decrement buttons are rendered.
88    ///
89    /// The buttons are rendered by default. Up and Down keys continue to step the
90    /// value when the buttons are omitted.
91    pub fn stepper(mut self, stepper: bool) -> Self {
92        self.stepper = stepper;
93        self
94    }
95}
96
97impl Disableable for NumberInput {
98    fn disabled(mut self, disabled: bool) -> Self {
99        self.disabled = disabled;
100        self
101    }
102}
103
104impl crate::FocusableExt for NumberInput {
105    fn focus_ring(mut self, enabled: bool) -> Self {
106        self.focus_ring_enabled = enabled;
107        self
108    }
109
110    fn is_focus_ring_enabled(&self) -> bool {
111        self.focus_ring_enabled
112    }
113}
114
115impl Focusable for NumberInput {
116    fn focus_handle(&self, cx: &App) -> FocusHandle {
117        self.state.focus_handle(cx)
118    }
119}
120
121impl Sizable for NumberInput {
122    fn with_size(mut self, size: impl Into<Size>) -> Self {
123        self.size = size.into();
124        self
125    }
126}
127
128impl Styled for NumberInput {
129    fn style(&mut self) -> &mut StyleRefinement {
130        &mut self.style
131    }
132}
133
134impl RenderOnce for NumberInput {
135    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
136        let focused = self.state.read(cx).focus_handle(cx).is_focused(window) && !self.disabled;
137        let (bg, _) = input_style(self.disabled, cx);
138        let border_color = if self.disabled {
139            cx.theme().input.opacity(0.5)
140        } else {
141            cx.theme().input
142        };
143        // Transparent like a ghost button, but tinted to the frame on hover.
144        let button_foreground = cx.theme().secondary_foreground;
145        let button_hover = cx.theme().input.opacity(0.4);
146        let button_active = cx.theme().input.opacity(0.6);
147        let button_size = self.size;
148        // The buttons sit inside the 1px frame, so their corners are a pixel
149        // tighter than the frame's, or they paint over its inner curve.
150        let button_radius = if self.appearance {
151            (cx.theme().radius - px(1.)).max(px(0.))
152        } else {
153            cx.theme().radius
154        };
155        let base_state = self.state.clone();
156        let content = BaseNumberInput::new(&base_state)
157            .disabled(self.disabled)
158            .stepper(self.stepper)
159            .when_some(self.accessibility_label, |this, label| {
160                this.accessibility_label(label)
161            })
162            .size_full()
163            .when(self.stepper, |this| {
164                this.decrement_button(move |this| {
165                    this.accessibility_label(t!("Input.Decrement"))
166                        .flex()
167                        .items_center()
168                        .justify_center()
169                        .text_color(button_foreground)
170                        .hover(move |this| this.bg(button_hover))
171                        .active(move |this| this.bg(button_active))
172                        // The frame owns the control height, so the buttons fill it
173                        // rather than setting their own and outgrowing the border.
174                        .h_full()
175                        .map(|this| match button_size {
176                            Size::XSmall | Size::Small => this.min_w_6(),
177                            Size::Medium | Size::Large => this.min_w_8(),
178                            Size::Size(size) => this.min_w(size),
179                        })
180                        // Only the outer corners are rounded, to follow the frame.
181                        .rounded_tl(button_radius)
182                        .rounded_bl(button_radius)
183                        .child(Icon::new(IconName::Minus).with_size(button_size))
184                })
185            })
186            .input(
187                Input::new(&self.state)
188                    .appearance(false)
189                    .with_size(button_size)
190                    .h_full()
191                    .disabled(self.disabled)
192                    .gap_0()
193                    .rounded_none()
194                    .text_align(TextAlign::Center)
195                    .when_some(self.prefix, |this, prefix| this.prefix(prefix))
196                    .when_some(self.suffix, |this, suffix| this.suffix(suffix)),
197            )
198            .when(self.stepper, |this| {
199                this.increment_button(move |this| {
200                    this.accessibility_label(t!("Input.Increment"))
201                        .flex()
202                        .items_center()
203                        .justify_center()
204                        .text_color(button_foreground)
205                        .hover(move |this| this.bg(button_hover))
206                        .active(move |this| this.bg(button_active))
207                        .h_full()
208                        .map(|this| match button_size {
209                            Size::XSmall | Size::Small => this.min_w_6(),
210                            Size::Medium | Size::Large => this.min_w_8(),
211                            Size::Size(size) => this.min_w(size),
212                        })
213                        .rounded_tr(button_radius)
214                        .rounded_br(button_radius)
215                        .child(Icon::new(IconName::Plus).with_size(button_size))
216                })
217            });
218
219        // The visual frame wraps the complete spinbutton. BaseNumberInput routes
220        // application children into its text slot, so putting the ring on that
221        // element would incorrectly surround only the editable middle region.
222        div()
223            .flex_1()
224            .input_h(self.size)
225            .rounded(cx.theme().radius)
226            .when(self.appearance, |this| {
227                this.bg(bg)
228                    .border_1()
229                    .border_color(border_color)
230                    .when(focused, |this| {
231                        this.border_1().border_color(cx.theme().ring)
232                    })
233            })
234            .refine_style(&self.style)
235            .when(self.disabled, |this| this.opacity(0.5))
236            .child(content)
237            .when(
238                focused && self.appearance && self.focus_ring_enabled,
239                |this| this.focus_ring_style(window, cx),
240            )
241    }
242}
243
244#[cfg(test)]
245mod tests {
246    use super::StepAction;
247    use gpui_base::step_value;
248
249    // `test_number_step` lives in `state::tests` because `NumberStep::value`
250    // now needs a `Context<InputState>` to invoke the `by_value` closure.
251
252    #[test]
253    fn test_step_value() {
254        fn some(value: &str) -> Option<String> {
255            Some(value.to_string())
256        }
257
258        // Step from empty value
259        assert_eq!(
260            step_value("", StepAction::Increment, 1., None, None),
261            some("1")
262        );
263        assert_eq!(
264            step_value("", StepAction::Decrement, 1., None, None),
265            some("-1")
266        );
267        // Invalid intermediate values are treated as 0
268        assert_eq!(
269            step_value("-", StepAction::Increment, 1., None, None),
270            some("1")
271        );
272        assert_eq!(
273            step_value("1", StepAction::Increment, 1., None, None),
274            some("2")
275        );
276        assert_eq!(
277            step_value("-2", StepAction::Increment, 1., None, None),
278            some("-1")
279        );
280
281        // Avoid float precision issue, e.g. 0.1 + 0.2 != 0.30000000000000004
282        assert_eq!(
283            step_value("0.1", StepAction::Increment, 0.2, None, None),
284            some("0.3")
285        );
286        assert_eq!(
287            step_value("0.3", StepAction::Decrement, 0.1, None, None),
288            some("0.2")
289        );
290        // Keep the fraction digits of the current value
291        assert_eq!(
292            step_value("1.25", StepAction::Increment, 1., None, None),
293            some("2.25")
294        );
295
296        // Step from empty value always steps into the range
297        assert_eq!(
298            step_value("", StepAction::Increment, 1., Some(10.), None),
299            some("10")
300        );
301        assert_eq!(
302            step_value("", StepAction::Decrement, 1., Some(10.), None),
303            some("10")
304        );
305        // Clamp to min/max
306        assert_eq!(
307            step_value("99.5", StepAction::Increment, 1., None, Some(100.)),
308            some("100.0")
309        );
310        assert_eq!(
311            step_value("1000", StepAction::Decrement, 1., None, Some(100.)),
312            some("100")
313        );
314        // Keep the fraction digits of the clamped bound
315        assert_eq!(
316            step_value("1", StepAction::Decrement, 1., Some(0.25), None),
317            some("0.25")
318        );
319
320        // Stepping must move the value in the pressed direction:
321        // no-op at the boundary
322        assert_eq!(
323            step_value("10", StepAction::Decrement, 1., Some(10.), None),
324            None
325        );
326        assert_eq!(
327            step_value("100", StepAction::Increment, 1., None, Some(100.)),
328            None
329        );
330        // Decrement on a below-min value (or Increment on an above-max value)
331        // does nothing, instead of moving the value in the opposite direction
332        assert_eq!(
333            step_value("5", StepAction::Decrement, 1., Some(10.), None),
334            None
335        );
336        assert_eq!(
337            step_value("1000", StepAction::Increment, 1., None, Some(100.)),
338            None
339        );
340    }
341}
342
343#[cfg(all(test, feature = "test-support"))]
344mod interaction_tests {
345    use super::*;
346    use gpui::{Context, Render, TestAppContext, VisualTestContext};
347    use gpui_base::test_support::{ElementSnapshot, find};
348
349    struct Probe {
350        state: Entity<InputState>,
351        show_stepper: bool,
352    }
353
354    impl Render for Probe {
355        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
356            div().size_full().child(
357                NumberInput::new(&self.state).when(!self.show_stepper, |this| this.stepper(false)),
358            )
359        }
360    }
361
362    fn draw(cx: &mut VisualTestContext) {
363        cx.run_until_parked();
364        cx.update(|window, cx| window.draw(cx).clear(cx));
365    }
366
367    fn button(cx: &mut VisualTestContext, id: &'static str) -> Option<ElementSnapshot> {
368        cx.update(|window, _| find(window, &[], &id.into()))
369    }
370
371    #[gpui::test]
372    fn disabling_stepper_omits_buttons_and_keeps_keyboard_stepping(cx: &mut TestAppContext) {
373        use gpui::AppContext as _;
374
375        cx.update(crate::init);
376        let (probe, mut cx) = cx.add_window_view(|window, cx| Probe {
377            state: cx.new(|cx| InputState::new(window, cx).default_value("3")),
378            show_stepper: true,
379        });
380        let state = probe.read_with(cx, |probe, _| probe.state.clone());
381        draw(&mut cx);
382
383        for id in ["decrement", "increment"] {
384            assert!(
385                button(&mut cx, id).is_some(),
386                "{id} should exist by default"
387            );
388        }
389
390        probe.update(cx, |probe, cx| {
391            probe.show_stepper = false;
392            cx.notify();
393        });
394        draw(&mut cx);
395
396        for id in ["decrement", "increment"] {
397            assert!(
398                button(&mut cx, id).is_none(),
399                "{id} should not be constructed"
400            );
401        }
402
403        cx.update(|window, cx| {
404            state.update(cx, |state, cx| state.focus(window, cx));
405        });
406        cx.simulate_keystrokes("up");
407        draw(&mut cx);
408        assert_eq!(
409            state.read_with(cx, |state, _| state.value().to_string()),
410            "4"
411        );
412    }
413
414    /// The frame does not track the editor's focus handle (#3873: two painted
415    /// elements tracking one focused handle both claim accessibility focus
416    /// and abort debug builds), so a step button press must still leave the
417    /// editor focused, step once, and keep arrow keys stepping.
418    #[gpui::test]
419    fn step_button_keeps_editor_focused_and_arrows_step(cx: &mut TestAppContext) {
420        use gpui::{AppContext as _, Modifiers, MouseButton};
421
422        cx.update(crate::init);
423        let (probe, mut cx) = cx.add_window_view(|window, cx| Probe {
424            state: cx.new(|cx| InputState::new(window, cx).default_value("3")),
425            show_stepper: true,
426        });
427        let state = probe.read_with(cx, |probe, _| probe.state.clone());
428        cx.update(|window, cx| {
429            state.update(cx, |state, cx| state.focus(window, cx));
430        });
431        draw(&mut cx);
432
433        let center = button(&mut cx, "increment").unwrap().bounds().center();
434        cx.simulate_mouse_move(center, None, Modifiers::default());
435        cx.simulate_mouse_down(center, MouseButton::Left, Modifiers::default());
436        cx.update(|window, cx| {
437            assert!(
438                state.read(cx).focus_handle(cx).is_focused(window),
439                "pressing the step button moved focus off the editor"
440            );
441        });
442        cx.simulate_mouse_up(center, MouseButton::Left, Modifiers::default());
443        draw(&mut cx);
444        cx.update(|window, cx| {
445            assert!(state.read(cx).focus_handle(cx).is_focused(window));
446            assert_eq!(state.read(cx).value(), "4");
447        });
448
449        cx.simulate_keystrokes("up up down");
450        draw(&mut cx);
451        assert_eq!(
452            state.read_with(cx, |state, _| state.value().to_string()),
453            "5"
454        );
455    }
456}