1use crate::input::InputState;
2use std::rc::Rc;
3
4use gpui::{
5 AnyElement, App, Entity, EventEmitter, InteractiveElement as _, IntoElement, KeyBinding,
6 MouseButton, ParentElement, RenderOnce, Role, SharedString, StatefulInteractiveElement as _,
7 StyleRefinement, Styled, Window, actions, div, prelude::FluentBuilder as _,
8};
9
10use crate::{Button, InputBase, StyledExt as _};
11
12actions!(number_input, [Increment, Decrement]);
13
14const CONTEXT: &str = "NumberInput";
15
16pub(crate) fn init(cx: &mut App) {
17 cx.bind_keys([
18 KeyBinding::new("up", Increment, Some(CONTEXT)),
19 KeyBinding::new("down", Decrement, Some(CONTEXT)),
20 ]);
21}
22
23#[derive(Clone, Copy, Debug, PartialEq, Eq)]
24pub enum StepAction {
25 Decrement,
26 Increment,
27}
28
29#[derive(Clone)]
31pub enum NumberStep {
32 Fixed(f64),
33 ByValue(Rc<dyn Fn(f64, StepAction, &mut gpui::App) -> f64>),
34}
35
36impl NumberStep {
37 pub fn by_value(f: impl Fn(f64, StepAction, &mut gpui::App) -> f64 + 'static) -> Self {
38 Self::ByValue(Rc::new(f))
39 }
40
41 pub(crate) fn value(&self, current: f64, action: StepAction, cx: &mut gpui::App) -> f64 {
42 match self {
43 Self::Fixed(step) => *step,
44 Self::ByValue(f) => f(current, action, cx),
45 }
46 }
47}
48
49impl From<f64> for NumberStep {
50 fn from(step: f64) -> Self {
51 Self::Fixed(step)
52 }
53}
54
55#[derive(Clone)]
56pub enum NumberInputEvent {
57 Step(StepAction),
58}
59impl EventEmitter<NumberInputEvent> for InputState {}
60
61impl InputState {
62 fn apply_number_step(
64 &mut self,
65 action: StepAction,
66 window: &mut Window,
67 cx: &mut gpui::Context<Self>,
68 ) {
69 if self.disabled {
70 return;
71 }
72 if let Some(step) = self.number_step.clone() {
73 let value = self.unmask_value();
74 let current = value.trim().parse::<f64>().unwrap_or(0.);
75 let step = step.value(current, action, cx);
76 if let Some(new_value) =
77 step_value(&value, action, step, self.number_min, self.number_max)
78 {
79 if self.is_valid_input(&new_value, cx) {
80 let range = self.range_to_utf16(&(0..self.value().len()));
81 self.replace_text_in_range_silent(Some(range), &new_value, window, cx);
82 return;
83 }
84 } else {
85 return;
86 }
87 }
88 cx.emit(NumberInputEvent::Step(action));
89 }
90}
91
92type StepHandler = Rc<dyn Fn(StepAction, &mut Window, &mut App)>;
93type ButtonDecorator = Box<dyn FnOnce(Button) -> Button>;
94
95#[derive(IntoElement)]
97pub struct NumberInput {
98 style: StyleRefinement,
99 children: Vec<AnyElement>,
100 disabled: bool,
101 state: Entity<InputState>,
102 on_step: Option<StepHandler>,
103 decrement_button: Option<ButtonDecorator>,
104 increment_button: Option<ButtonDecorator>,
105 stepper: bool,
106 input: Option<AnyElement>,
107 controls_right: bool,
108 accessibility_label: Option<SharedString>,
109}
110
111#[derive(IntoElement)]
116pub struct NumberInputText {
117 style: StyleRefinement,
118 children: Vec<AnyElement>,
119}
120
121impl NumberInputText {
122 pub fn new() -> Self {
123 Self {
124 style: StyleRefinement::default(),
125 children: Vec::new(),
126 }
127 }
128}
129
130impl Default for NumberInputText {
131 fn default() -> Self {
132 Self::new()
133 }
134}
135
136impl Styled for NumberInputText {
137 fn style(&mut self) -> &mut StyleRefinement {
138 &mut self.style
139 }
140}
141
142impl ParentElement for NumberInputText {
143 fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
144 self.children.extend(elements);
145 }
146}
147
148impl RenderOnce for NumberInputText {
149 fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
150 gpui::div()
151 .min_w_0()
152 .flex_1()
153 .children(self.children)
154 .refine_style(&self.style)
155 }
156}
157
158impl NumberInput {
159 pub fn new(state: &Entity<InputState>) -> Self {
160 Self {
161 style: StyleRefinement::default(),
162 children: Vec::new(),
163 disabled: false,
164 state: state.clone(),
165 on_step: None,
166 decrement_button: None,
167 increment_button: None,
168 stepper: true,
169 input: None,
170 controls_right: false,
171 accessibility_label: None,
172 }
173 }
174
175 pub fn disabled(mut self, disabled: bool) -> Self {
176 self.disabled = disabled;
177 self
178 }
179
180 pub fn on_step(
181 mut self,
182 handler: impl Fn(StepAction, &mut Window, &mut App) + 'static,
183 ) -> Self {
184 self.on_step = Some(Rc::new(handler));
185 self
186 }
187
188 pub fn decrement_button(mut self, decorate: impl FnOnce(Button) -> Button + 'static) -> Self {
190 self.decrement_button = Some(Box::new(decorate));
191 self
192 }
193
194 pub fn increment_button(mut self, decorate: impl FnOnce(Button) -> Button + 'static) -> Self {
196 self.increment_button = Some(Box::new(decorate));
197 self
198 }
199
200 pub fn stepper(mut self, stepper: bool) -> Self {
205 self.stepper = stepper;
206 self
207 }
208
209 pub fn input(mut self, input: impl IntoElement) -> Self {
211 self.input = Some(input.into_any_element());
212 self
213 }
214
215 pub fn controls_right(mut self) -> Self {
217 self.controls_right = true;
218 self
219 }
220
221 pub fn accessibility_label(mut self, label: impl Into<SharedString>) -> Self {
226 self.accessibility_label = Some(label.into());
227 self
228 }
229}
230
231impl Styled for NumberInput {
232 fn style(&mut self) -> &mut StyleRefinement {
233 &mut self.style
234 }
235}
236
237impl ParentElement for NumberInput {
238 fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
239 self.children.extend(elements);
240 }
241}
242
243impl RenderOnce for NumberInput {
244 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
245 let disabled = self.disabled;
246 let controls_right = self.controls_right;
247 let on_step = self.on_step.unwrap_or_else(|| {
248 let state = self.state.clone();
249 Rc::new(move |action, window, cx| {
250 state.update(cx, |state, cx| {
251 state.focus(window, cx);
252 state.apply_number_step(action, window, cx);
253 });
254 })
255 });
256 self.state.update(cx, |state, _| state.ensure_number_mask());
257 let value = self.state.read(cx).value().parse::<f64>().ok();
258 let decrement_button = self.stepper.then(|| {
259 self.decrement_button.map_or_else(
260 || Button::new("decrement"),
261 |decorate| decorate(Button::new("decrement")),
262 )
263 });
264 let increment_button = self.stepper.then(|| {
265 self.increment_button.map_or_else(
266 || Button::new("increment"),
267 |decorate| decorate(Button::new("increment")),
268 )
269 });
270 let text = NumberInputText::new().children(self.input);
271
272 let decrement_button = decrement_button.map(|button| {
273 button
277 .when(controls_right, |this| this.flex_1().min_h_0())
278 .when(!controls_right, |this| this.flex_none())
279 .focusable(false)
280 .disabled(disabled)
281 .on_click({
282 let on_step = on_step.clone();
283 move |_, window, cx| {
284 on_step(StepAction::Decrement, window, cx);
285 }
286 })
287 });
288 let increment_button = increment_button.map(|button| {
289 button
290 .when(controls_right, |this| this.flex_1().min_h_0())
291 .when(!controls_right, |this| this.flex_none())
292 .focusable(false)
293 .disabled(disabled)
294 .on_click({
295 let on_step = on_step.clone();
296 move |_, window, cx| {
297 on_step(StepAction::Increment, window, cx);
298 }
299 })
300 });
301
302 let content = if controls_right {
303 div()
304 .flex()
305 .items_center()
306 .size_full()
307 .child(text.children(self.children))
308 .when_some(
309 self.stepper.then(|| {
310 div()
311 .h_full()
312 .flex()
313 .flex_col()
314 .when_some(increment_button, |this, button| this.child(button))
315 .when_some(decrement_button, |this, button| this.child(button))
316 }),
317 |this, buttons| this.child(buttons),
318 )
319 .into_any_element()
320 } else {
321 div()
322 .flex()
323 .items_center()
324 .size_full()
325 .when_some(decrement_button, |this, button| this.child(button))
326 .child(text.children(self.children))
327 .when_some(increment_button, |this, button| this.child(button))
328 .into_any_element()
329 };
330
331 InputBase::new(("number-input", self.state.entity_id()))
332 .on_mouse_down(MouseButton::Left, {
337 let state = self.state.clone();
338 move |_, window, cx| {
339 if !window.default_prevented() {
340 state.update(cx, |state, cx| state.focus(window, cx));
341 window.prevent_default();
342 }
343 }
344 })
345 .flex()
346 .items_center()
347 .disabled(disabled)
348 .role(Role::SpinButton)
349 .when_some(self.accessibility_label, |this, label| {
350 this.aria_label(label)
351 })
352 .when_some(value, |this, value| this.aria_numeric_value(value))
353 .key_context(CONTEXT)
354 .on_action({
355 let on_step = on_step.clone();
356 move |_: &Increment, window, cx| {
357 if disabled {
358 cx.propagate();
359 } else {
360 on_step(StepAction::Increment, window, cx);
361 }
362 }
363 })
364 .on_action(move |_: &Decrement, window, cx| {
365 if disabled {
366 cx.propagate();
367 } else {
368 on_step(StepAction::Decrement, window, cx);
369 }
370 })
371 .child(content)
372 .refine_style(&self.style)
373 .render(window, cx)
374 }
375}
376
377pub fn step_value(
379 value: &str,
380 action: StepAction,
381 step: f64,
382 min: Option<f64>,
383 max: Option<f64>,
384) -> Option<String> {
385 fn fraction_digits(value: &str) -> usize {
386 value.split('.').nth(1).map_or(0, |fraction| fraction.len())
387 }
388
389 let current = value.trim().parse::<f64>().ok();
390 let mut new_value = match action {
391 StepAction::Increment => current.unwrap_or(0.) + step,
392 StepAction::Decrement => current.unwrap_or(0.) - step,
393 };
394 let mut digits = fraction_digits(value).max(fraction_digits(&step.to_string()));
395 if let Some(min) = min
396 && new_value < min
397 {
398 new_value = min;
399 digits = digits.max(fraction_digits(&min.to_string()));
400 }
401 if let Some(max) = max
402 && new_value > max
403 {
404 new_value = max;
405 digits = digits.max(fraction_digits(&max.to_string()));
406 }
407
408 if let Some(current) = current {
409 let moved = match action {
410 StepAction::Increment => new_value > current,
411 StepAction::Decrement => new_value < current,
412 };
413 if !moved {
414 return None;
415 }
416 }
417
418 Some(format!("{new_value:.digits$}"))
419}
420
421#[cfg(test)]
422mod tests {
423 use super::*;
424
425 use crate::theme::Theme;
426 use gpui::Focusable as _;
427 use gpui::{
428 AppContext as _, Context, Entity, Modifiers, MouseButton, Render, TestAppContext,
429 VisualTestContext, point, px,
430 };
431
432 struct StepperHarness {
433 state: Entity<InputState>,
434 }
435
436 impl Render for StepperHarness {
437 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
438 NumberInput::new(&self.state)
439 .w(px(120.))
440 .h(px(20.))
441 .decrement_button(|button| button.w(px(20.)).h_full())
442 .input(div().size_full())
443 .increment_button(|button| button.w(px(20.)).h_full())
444 }
445 }
446
447 #[gpui::test]
451 fn pressing_a_step_button_never_takes_focus_off_the_editor(cx: &mut TestAppContext) {
452 cx.update(crate::init);
453
454 let mut created: Option<Entity<InputState>> = None;
455 let window = cx.update(|cx| {
456 cx.open_window(Default::default(), |window, cx| {
457 cx.set_global(Theme::default());
458 let state = cx.new(|cx| InputState::new(window, cx).step(1.));
459 created = Some(state.clone());
460 cx.new(|_| StepperHarness { state })
461 })
462 .unwrap()
463 });
464 let state = created.unwrap();
465 let cx = &mut VisualTestContext::from_window(window.into(), cx);
466
467 cx.update(|window, cx| {
468 state.update(cx, |state, cx| state.focus(window, cx));
469 window.draw(cx).clear(cx);
470 });
471 cx.update(|window, cx| {
472 assert!(
473 state.read(cx).focus_handle(cx).is_focused(window),
474 "the editor should start focused"
475 );
476 });
477
478 cx.simulate_mouse_move(
480 point(px(10.), px(10.)),
481 MouseButton::Left,
482 Modifiers::default(),
483 );
484 cx.simulate_event(gpui::MouseDownEvent {
485 button: MouseButton::Left,
486 position: point(px(10.), px(10.)),
487 modifiers: Modifiers::default(),
488 click_count: 1,
489 first_mouse: false,
490 });
491
492 cx.update(|window, cx| {
493 assert!(
494 state.read(cx).focus_handle(cx).is_focused(window),
495 "pressing the step button pulled focus off the editor"
496 );
497 });
498
499 cx.simulate_event(gpui::MouseUpEvent {
500 button: MouseButton::Left,
501 position: point(px(10.), px(10.)),
502 modifiers: Modifiers::default(),
503 click_count: 1,
504 });
505
506 cx.update(|window, cx| {
507 assert!(
508 state.read(cx).focus_handle(cx).is_focused(window),
509 "releasing the step button left focus off the editor"
510 );
511 });
512 }
513
514 #[test]
515 fn stepping_preserves_precision_and_directional_bounds() {
516 assert_eq!(
517 step_value("0.1", StepAction::Increment, 0.2, None, None).as_deref(),
518 Some("0.3")
519 );
520 assert_eq!(
521 step_value("10", StepAction::Decrement, 1., Some(10.), None),
522 None
523 );
524 assert_eq!(
525 step_value("99.5", StepAction::Increment, 1., None, Some(100.)).as_deref(),
526 Some("100.0")
527 );
528 assert_eq!(
529 step_value("10", StepAction::Increment, 1., None, Some(10.)),
530 None
531 );
532 assert_eq!(
533 step_value("5", StepAction::Decrement, 10., Some(0.), None).as_deref(),
534 Some("0")
535 );
536 }
537}