Skip to main content

gpui_component/input/
number_input.rs

1use crate::theme::ActiveTheme;
2use gpui::ColorExt as _;
3use gpui::{
4    AnyElement, App, Entity, FocusHandle, Focusable, InteractiveElement as _,
5    StatefulInteractiveElement as _, Window, div, px,
6};
7use gpui::{
8    IntoElement, ParentElement, RenderOnce, SharedString, StyleRefinement, Styled, TextAlign,
9    prelude::FluentBuilder as _,
10};
11
12use crate::{Disableable, Icon, IconName, Sizable, Size, StyleSized as _};
13
14use super::{Input, InputState, input::input_style};
15use crate::ThemeStyled as _;
16use gpui_base::NumberInput as BaseNumberInput;
17pub use gpui_base::{NumberInputEvent, NumberStep, StepAction};
18use rust_i18n::t;
19
20/// A number input element with increment and decrement buttons.
21#[derive(IntoElement)]
22pub struct NumberInput {
23    state: Entity<InputState>,
24    placeholder: SharedString,
25    size: Size,
26    prefix: Option<AnyElement>,
27    suffix: Option<AnyElement>,
28    appearance: bool,
29    focus_ring_enabled: bool,
30    disabled: bool,
31    style: StyleRefinement,
32}
33
34impl NumberInput {
35    /// Create a new [`NumberInput`] element bind to the [`InputState`].
36    pub fn new(state: &Entity<InputState>) -> Self {
37        Self {
38            state: state.clone(),
39            size: Size::default(),
40            placeholder: SharedString::default(),
41            prefix: None,
42            suffix: None,
43            appearance: true,
44            focus_ring_enabled: true,
45            disabled: false,
46            style: StyleRefinement::default(),
47        }
48    }
49
50    /// Set the placeholder text of the number input.
51    pub fn placeholder(mut self, placeholder: impl Into<SharedString>) -> Self {
52        self.placeholder = placeholder.into();
53        self
54    }
55
56    /// Set the prefix element of the number input.
57    pub fn prefix(mut self, prefix: impl IntoElement) -> Self {
58        self.prefix = Some(prefix.into_any_element());
59        self
60    }
61
62    /// Set the suffix element of the number input.
63    pub fn suffix(mut self, suffix: impl IntoElement) -> Self {
64        self.suffix = Some(suffix.into_any_element());
65        self
66    }
67
68    /// Set the appearance of the number input, if false will no border and background.
69    pub fn appearance(mut self, appearance: bool) -> Self {
70        self.appearance = appearance;
71        self
72    }
73}
74
75impl Disableable for NumberInput {
76    fn disabled(mut self, disabled: bool) -> Self {
77        self.disabled = disabled;
78        self
79    }
80}
81
82impl crate::FocusableExt for NumberInput {
83    fn focus_ring(mut self, enabled: bool) -> Self {
84        self.focus_ring_enabled = enabled;
85        self
86    }
87
88    fn is_focus_ring_enabled(&self) -> bool {
89        self.focus_ring_enabled
90    }
91}
92
93impl Focusable for NumberInput {
94    fn focus_handle(&self, cx: &App) -> FocusHandle {
95        self.state.focus_handle(cx)
96    }
97}
98
99impl Sizable for NumberInput {
100    fn with_size(mut self, size: impl Into<Size>) -> Self {
101        self.size = size.into();
102        self
103    }
104}
105
106impl Styled for NumberInput {
107    fn style(&mut self) -> &mut StyleRefinement {
108        &mut self.style
109    }
110}
111
112impl RenderOnce for NumberInput {
113    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
114        let focused = self.state.read(cx).focus_handle(cx).is_focused(window) && !self.disabled;
115        let (bg, _) = input_style(self.disabled, cx);
116        let border_color = if self.disabled {
117            cx.theme().input.opacity(0.5)
118        } else {
119            cx.theme().input
120        };
121        // Transparent like a ghost button, but tinted to the frame on hover.
122        let button_foreground = cx.theme().secondary_foreground;
123        let button_hover = cx.theme().input.opacity(0.4);
124        let button_active = cx.theme().input.opacity(0.6);
125        let button_size = self.size;
126        // The buttons sit inside the 1px frame, so their corners are a pixel
127        // tighter than the frame's, or they paint over its inner curve.
128        let button_radius = if self.appearance {
129            (cx.theme().radius - px(1.)).max(px(0.))
130        } else {
131            cx.theme().radius
132        };
133        let base_state = self.state.clone();
134        let content = BaseNumberInput::new(&base_state)
135            .disabled(self.disabled)
136            .size_full()
137            .decrement_button(move |this| {
138                this.accessibility_label(t!("Input.Decrement"))
139                    .flex()
140                    .items_center()
141                    .justify_center()
142                    .text_color(button_foreground)
143                    .hover(move |this| this.bg(button_hover))
144                    .active(move |this| this.bg(button_active))
145                    // The frame owns the control height, so the buttons fill it
146                    // rather than setting their own and outgrowing the border.
147                    .h_full()
148                    .map(|this| match button_size {
149                        Size::XSmall | Size::Small => this.min_w_6(),
150                        Size::Medium | Size::Large => this.min_w_8(),
151                        Size::Size(size) => this.min_w(size),
152                    })
153                    // Only the outer corners are rounded, to follow the frame.
154                    .rounded_tl(button_radius)
155                    .rounded_bl(button_radius)
156                    .child(Icon::new(IconName::Minus).with_size(button_size))
157            })
158            .input(
159                Input::new(&self.state)
160                    .appearance(false)
161                    .with_size(button_size)
162                    .h_full()
163                    .disabled(self.disabled)
164                    .gap_0()
165                    .rounded_none()
166                    .text_align(TextAlign::Center)
167                    .when_some(self.prefix, |this, prefix| this.prefix(prefix))
168                    .when_some(self.suffix, |this, suffix| this.suffix(suffix)),
169            )
170            .increment_button(move |this| {
171                this.accessibility_label(t!("Input.Increment"))
172                    .flex()
173                    .items_center()
174                    .justify_center()
175                    .text_color(button_foreground)
176                    .hover(move |this| this.bg(button_hover))
177                    .active(move |this| this.bg(button_active))
178                    .h_full()
179                    .map(|this| match button_size {
180                        Size::XSmall | Size::Small => this.min_w_6(),
181                        Size::Medium | Size::Large => this.min_w_8(),
182                        Size::Size(size) => this.min_w(size),
183                    })
184                    .rounded_tr(button_radius)
185                    .rounded_br(button_radius)
186                    .child(Icon::new(IconName::Plus).with_size(button_size))
187            });
188
189        // The visual frame wraps the complete spinbutton. BaseNumberInput routes
190        // application children into its text slot, so putting the ring on that
191        // element would incorrectly surround only the editable middle region.
192        div()
193            .flex_1()
194            .input_h(self.size)
195            .rounded(cx.theme().radius)
196            .when(self.appearance, |this| {
197                this.bg(bg)
198                    .border_1()
199                    .border_color(border_color)
200                    .when(focused, |this| {
201                        this.border_1().border_color(cx.theme().ring)
202                    })
203            })
204            .refine_style(&self.style)
205            .when(self.disabled, |this| this.opacity(0.5))
206            .child(content)
207            .when(
208                focused && self.appearance && self.focus_ring_enabled,
209                |this| this.focus_ring_style(window, cx),
210            )
211    }
212}
213
214#[cfg(test)]
215mod tests {
216    use super::StepAction;
217    use gpui_base::step_value;
218
219    // `test_number_step` lives in `state::tests` because `NumberStep::value`
220    // now needs a `Context<InputState>` to invoke the `by_value` closure.
221
222    #[test]
223    fn test_step_value() {
224        fn some(value: &str) -> Option<String> {
225            Some(value.to_string())
226        }
227
228        // Step from empty value
229        assert_eq!(
230            step_value("", StepAction::Increment, 1., None, None),
231            some("1")
232        );
233        assert_eq!(
234            step_value("", StepAction::Decrement, 1., None, None),
235            some("-1")
236        );
237        // Invalid intermediate values are treated as 0
238        assert_eq!(
239            step_value("-", StepAction::Increment, 1., None, None),
240            some("1")
241        );
242        assert_eq!(
243            step_value("1", StepAction::Increment, 1., None, None),
244            some("2")
245        );
246        assert_eq!(
247            step_value("-2", StepAction::Increment, 1., None, None),
248            some("-1")
249        );
250
251        // Avoid float precision issue, e.g. 0.1 + 0.2 != 0.30000000000000004
252        assert_eq!(
253            step_value("0.1", StepAction::Increment, 0.2, None, None),
254            some("0.3")
255        );
256        assert_eq!(
257            step_value("0.3", StepAction::Decrement, 0.1, None, None),
258            some("0.2")
259        );
260        // Keep the fraction digits of the current value
261        assert_eq!(
262            step_value("1.25", StepAction::Increment, 1., None, None),
263            some("2.25")
264        );
265
266        // Step from empty value always steps into the range
267        assert_eq!(
268            step_value("", StepAction::Increment, 1., Some(10.), None),
269            some("10")
270        );
271        assert_eq!(
272            step_value("", StepAction::Decrement, 1., Some(10.), None),
273            some("10")
274        );
275        // Clamp to min/max
276        assert_eq!(
277            step_value("99.5", StepAction::Increment, 1., None, Some(100.)),
278            some("100.0")
279        );
280        assert_eq!(
281            step_value("1000", StepAction::Decrement, 1., None, Some(100.)),
282            some("100")
283        );
284        // Keep the fraction digits of the clamped bound
285        assert_eq!(
286            step_value("1", StepAction::Decrement, 1., Some(0.25), None),
287            some("0.25")
288        );
289
290        // Stepping must move the value in the pressed direction:
291        // no-op at the boundary
292        assert_eq!(
293            step_value("10", StepAction::Decrement, 1., Some(10.), None),
294            None
295        );
296        assert_eq!(
297            step_value("100", StepAction::Increment, 1., None, Some(100.)),
298            None
299        );
300        // Decrement on a below-min value (or Increment on an above-max value)
301        // does nothing, instead of moving the value in the opposite direction
302        assert_eq!(
303            step_value("5", StepAction::Decrement, 1., Some(10.), None),
304            None
305        );
306        assert_eq!(
307            step_value("1000", StepAction::Increment, 1., None, Some(100.)),
308            None
309        );
310    }
311}