1use std::rc::Rc;
2
3use gpui::{
4 AnyElement, App, AppContext, Context, ElementId, Empty, Entity, EventEmitter, FocusHandle,
5 Focusable, InteractiveElement, IntoElement, MouseButton, ParentElement, Render, RenderOnce,
6 SharedString, StatefulInteractiveElement, Styled, Subscription, Window, div,
7 prelude::FluentBuilder, px,
8};
9use gpui_base::{
10 Button as BaseButton, NumberInput as BaseNumberInput, StepAction as BaseStepAction,
11 TestSupportExt, step_value,
12};
13use gpui_material_components::{
14 Icon, IconName, Text, TextField, TextFieldColors, TextFieldEvent, TextFieldState,
15 TextFieldVariant,
16};
17use gpui_material_foundation::{color, current_material_theme};
18use gpui_material_theme::{ColorRole, Density, Direction};
19
20#[derive(Clone, Copy, Debug, PartialEq, Eq)]
22pub enum NumberStepAction {
23 Decrement,
25 Increment,
27}
28
29impl From<BaseStepAction> for NumberStepAction {
30 fn from(action: BaseStepAction) -> Self {
31 match action {
32 BaseStepAction::Decrement => Self::Decrement,
33 BaseStepAction::Increment => Self::Increment,
34 }
35 }
36}
37
38impl From<NumberStepAction> for BaseStepAction {
39 fn from(action: NumberStepAction) -> Self {
40 match action {
41 NumberStepAction::Decrement => Self::Decrement,
42 NumberStepAction::Increment => Self::Increment,
43 }
44 }
45}
46
47#[derive(Clone, Copy, Debug, PartialEq)]
49pub enum NumberInputEvent {
50 Change(Option<f64>),
52 Step(NumberStepAction),
54 Submit(Option<f64>),
56}
57
58#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
60pub enum NumberInputStepper {
61 #[default]
63 Split,
64 Trailing,
66 None,
68}
69
70pub struct NumberInputState {
75 editor: Entity<TextFieldState>,
76 min: Option<f64>,
77 max: Option<f64>,
78 step: f64,
79 precision: Option<usize>,
80 _subscriptions: Vec<Subscription>,
81}
82
83impl NumberInputState {
84 pub fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {
86 let editor = cx.new(|cx| {
87 let mut state = TextFieldState::new(window, cx);
88 state.ensure_number_mask();
89 state
90 });
91 let subscriptions = vec![
92 cx.observe(&editor, |_, _, cx| cx.notify()),
93 cx.subscribe_in(
94 &editor,
95 window,
96 |_, editor, event: &TextFieldEvent, _, cx| match event {
97 TextFieldEvent::Change => {
98 let parsed = parse_number(editor.read(cx).unmask_value().as_str());
99 cx.emit(NumberInputEvent::Change(parsed));
100 cx.notify();
101 }
102 TextFieldEvent::PressEnter { .. } => {
103 let parsed = parse_number(editor.read(cx).unmask_value().as_str());
104 cx.emit(NumberInputEvent::Submit(parsed));
105 }
106 _ => {}
107 },
108 ),
109 ];
110 Self {
111 editor,
112 min: None,
113 max: None,
114 step: 1.0,
115 precision: None,
116 _subscriptions: subscriptions,
117 }
118 }
119
120 pub fn default_value(self, value: f64, window: &mut Window, cx: &mut Context<Self>) -> Self {
122 let clamped = clamp_value(value, self.min, self.max);
123 let formatted = format_number(clamped, self.step, self.precision, "");
124 self.editor
125 .update(cx, |editor, cx| editor.set_value(formatted, window, cx));
126 self
127 }
128
129 pub fn min(mut self, min: f64) -> Self {
131 if min.is_finite() {
132 self.min = Some(min);
133 }
134 self
135 }
136
137 pub fn max(mut self, max: f64) -> Self {
139 if max.is_finite() {
140 self.max = Some(max);
141 }
142 self
143 }
144
145 pub fn bounds(mut self, min: f64, max: f64) -> Self {
149 if min.is_finite() && max.is_finite() {
150 let (lo, hi) = if min <= max { (min, max) } else { (max, min) };
151 self.min = Some(lo);
152 self.max = Some(hi);
153 }
154 self
155 }
156
157 pub fn step(mut self, step: f64) -> Self {
160 if step.is_finite() && step > 0.0 {
161 self.step = step;
162 }
163 self
164 }
165
166 pub fn precision(mut self, digits: usize) -> Self {
168 self.precision = Some(digits.min(12));
169 self
170 }
171
172 pub fn set_min(&mut self, min: Option<f64>, cx: &mut Context<Self>) {
174 self.min = min.filter(|v| v.is_finite());
175 cx.notify();
176 }
177
178 pub fn set_max(&mut self, max: Option<f64>, cx: &mut Context<Self>) {
180 self.max = max.filter(|v| v.is_finite());
181 cx.notify();
182 }
183
184 pub fn set_step(&mut self, step: f64, cx: &mut Context<Self>) {
186 if step.is_finite() && step > 0.0 {
187 self.step = step;
188 cx.notify();
189 }
190 }
191
192 pub fn min_value(&self) -> Option<f64> {
194 self.min
195 }
196
197 pub fn max_value(&self) -> Option<f64> {
199 self.max
200 }
201
202 pub fn step_value(&self) -> f64 {
204 self.step
205 }
206
207 pub fn value(&self, cx: &App) -> Option<f64> {
209 parse_number(self.editor.read(cx).unmask_value().as_str())
210 }
211
212 pub fn text(&self, cx: &App) -> SharedString {
214 self.editor.read(cx).value()
215 }
216
217 pub fn set_value(&mut self, value: f64, window: &mut Window, cx: &mut Context<Self>) {
219 if !value.is_finite() {
220 return;
221 }
222 let clamped = clamp_value(value, self.min, self.max);
223 let current = self.editor.read(cx).unmask_value();
224 let formatted = format_number(clamped, self.step, self.precision, current.as_str());
225 self.editor
226 .update(cx, |editor, cx| editor.set_value(formatted, window, cx));
227 cx.notify();
228 }
229
230 pub fn set_text(
232 &mut self,
233 text: impl Into<SharedString>,
234 window: &mut Window,
235 cx: &mut Context<Self>,
236 ) {
237 let text: SharedString = text.into();
238 self.editor
239 .update(cx, |editor, cx| editor.set_value(text, window, cx));
240 cx.notify();
241 }
242
243 pub fn is_disabled(&self, cx: &App) -> bool {
245 self.editor.read(cx).presentation().is_disabled()
246 }
247
248 pub fn set_disabled(&mut self, disabled: bool, cx: &mut Context<Self>) {
250 self.editor
251 .update(cx, |editor, cx| editor.set_disabled(disabled, cx));
252 cx.notify();
253 }
254
255 pub fn is_readonly(&self, cx: &App) -> bool {
257 self.editor.read(cx).presentation().is_readonly()
258 }
259
260 pub fn set_readonly(&mut self, readonly: bool, cx: &mut Context<Self>) {
262 self.editor
263 .update(cx, |editor, cx| editor.set_readonly(readonly, cx));
264 cx.notify();
265 }
266
267 pub fn can_increment(&self, cx: &App) -> bool {
269 if self.is_disabled(cx) || self.is_readonly(cx) {
270 return false;
271 }
272 match (self.value(cx), self.max) {
273 (Some(value), Some(max)) => value < max,
274 _ => true,
275 }
276 }
277
278 pub fn can_decrement(&self, cx: &App) -> bool {
280 if self.is_disabled(cx) || self.is_readonly(cx) {
281 return false;
282 }
283 match (self.value(cx), self.min) {
284 (Some(value), Some(min)) => value > min,
285 _ => true,
286 }
287 }
288
289 pub fn step_by(
293 &mut self,
294 action: NumberStepAction,
295 window: &mut Window,
296 cx: &mut Context<Self>,
297 ) -> bool {
298 if self.is_disabled(cx) || self.is_readonly(cx) {
299 return false;
300 }
301 let raw = self.editor.read(cx).unmask_value();
302 let next = compute_step(
303 raw.as_str(),
304 action,
305 self.step,
306 self.min,
307 self.max,
308 self.precision,
309 );
310 let Some(next) = next else {
311 return false;
312 };
313 let parsed = parse_number(&next);
314 self.editor
315 .update(cx, |editor, cx| editor.set_value(next, window, cx));
316 cx.emit(NumberInputEvent::Step(action));
317 cx.emit(NumberInputEvent::Change(parsed));
318 cx.notify();
319 true
320 }
321
322 pub fn increment(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
324 self.step_by(NumberStepAction::Increment, window, cx)
325 }
326
327 pub fn decrement(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
329 self.step_by(NumberStepAction::Decrement, window, cx)
330 }
331
332 pub fn focus(&self, window: &mut Window, cx: &mut Context<Self>) {
334 self.editor
335 .update(cx, |editor, cx| editor.focus(window, cx));
336 }
337
338 pub fn editor(&self) -> &Entity<TextFieldState> {
340 &self.editor
341 }
342}
343
344impl Focusable for NumberInputState {
345 fn focus_handle(&self, cx: &App) -> FocusHandle {
346 self.editor.read(cx).focus_handle(cx)
347 }
348}
349
350impl EventEmitter<NumberInputEvent> for NumberInputState {}
351
352impl Render for NumberInputState {
353 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
354 Empty
355 }
356}
357
358type StepCallback = Rc<dyn Fn(NumberStepAction, &mut Window, &mut App)>;
359type ChangeCallback = Rc<dyn Fn(Option<f64>, &mut Window, &mut App)>;
360
361#[derive(IntoElement)]
365pub struct NumberInput {
366 id: ElementId,
367 label: SharedString,
368 state: Entity<NumberInputState>,
369 variant: TextFieldVariant,
370 stepper: NumberInputStepper,
371 placeholder: Option<SharedString>,
372 prefix: Option<AnyElement>,
373 suffix: Option<AnyElement>,
374 supporting: Option<SharedString>,
375 error: Option<SharedString>,
376 invalid: bool,
377 disabled: bool,
378 required: bool,
379 show_label: bool,
380 decrement_label: SharedString,
381 increment_label: SharedString,
382 colors: TextFieldColors,
383 on_step: Option<StepCallback>,
384 on_change: Option<ChangeCallback>,
385}
386
387impl NumberInput {
388 pub fn new(
390 id: impl Into<ElementId>,
391 label: impl Into<SharedString>,
392 state: &Entity<NumberInputState>,
393 ) -> Self {
394 Self {
395 id: id.into(),
396 label: label.into(),
397 state: state.clone(),
398 variant: TextFieldVariant::Filled,
399 stepper: NumberInputStepper::Split,
400 placeholder: None,
401 prefix: None,
402 suffix: None,
403 supporting: None,
404 error: None,
405 invalid: false,
406 disabled: false,
407 required: false,
408 show_label: true,
409 decrement_label: SharedString::new_static("Decrease"),
410 increment_label: SharedString::new_static("Increase"),
411 colors: TextFieldColors::default(),
412 on_step: None,
413 on_change: None,
414 }
415 }
416
417 pub fn filled(
419 id: impl Into<ElementId>,
420 label: impl Into<SharedString>,
421 state: &Entity<NumberInputState>,
422 ) -> Self {
423 Self::new(id, label, state).variant(TextFieldVariant::Filled)
424 }
425
426 pub fn outlined(
428 id: impl Into<ElementId>,
429 label: impl Into<SharedString>,
430 state: &Entity<NumberInputState>,
431 ) -> Self {
432 Self::new(id, label, state).variant(TextFieldVariant::Outlined)
433 }
434
435 pub fn variant(mut self, variant: TextFieldVariant) -> Self {
437 self.variant = variant;
438 self
439 }
440
441 pub fn stepper(mut self, stepper: NumberInputStepper) -> Self {
443 self.stepper = stepper;
444 self
445 }
446
447 pub fn placeholder(mut self, text: impl Into<SharedString>) -> Self {
449 self.placeholder = Some(text.into());
450 self
451 }
452
453 pub fn prefix(mut self, element: impl IntoElement) -> Self {
455 self.prefix = Some(element.into_any_element());
456 self
457 }
458
459 pub fn suffix(mut self, element: impl IntoElement) -> Self {
461 self.suffix = Some(element.into_any_element());
462 self
463 }
464
465 pub fn supporting_text(mut self, text: impl Into<SharedString>) -> Self {
467 self.supporting = Some(text.into());
468 self
469 }
470
471 pub fn error(mut self, message: impl Into<SharedString>) -> Self {
473 self.error = Some(message.into());
474 self.invalid = true;
475 self
476 }
477
478 pub fn invalid(mut self, invalid: bool) -> Self {
480 self.invalid = invalid;
481 self
482 }
483
484 pub fn disabled(mut self, disabled: bool) -> Self {
486 self.disabled = disabled;
487 self
488 }
489
490 pub fn required(mut self, required: bool) -> Self {
492 self.required = required;
493 self
494 }
495
496 pub fn show_label(mut self, show: bool) -> Self {
499 self.show_label = show;
500 self
501 }
502
503 pub fn decrement_label(mut self, label: impl Into<SharedString>) -> Self {
505 self.decrement_label = label.into();
506 self
507 }
508
509 pub fn increment_label(mut self, label: impl Into<SharedString>) -> Self {
511 self.increment_label = label.into();
512 self
513 }
514
515 pub fn colors(mut self, colors: TextFieldColors) -> Self {
517 self.colors = colors;
518 self
519 }
520
521 pub fn on_step(
523 mut self,
524 handler: impl Fn(NumberStepAction, &mut Window, &mut App) + 'static,
525 ) -> Self {
526 self.on_step = Some(Rc::new(handler));
527 self
528 }
529
530 pub fn on_change(
532 mut self,
533 handler: impl Fn(Option<f64>, &mut Window, &mut App) + 'static,
534 ) -> Self {
535 self.on_change = Some(Rc::new(handler));
536 self
537 }
538}
539
540impl RenderOnce for NumberInput {
541 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
542 let theme = current_material_theme(window, cx);
543 let rtl = theme.layout.direction == Direction::Rtl;
544 let button_side = match theme.layout.density {
545 Density::Compact => px(32.),
546 Density::Standard => px(36.),
547 Density::Comfortable => px(40.),
548 };
549 let editor = self.state.read(cx).editor().clone();
550 let state_disabled = self.state.read(cx).is_disabled(cx);
551 let state_readonly = self.state.read(cx).is_readonly(cx);
552 let disabled = self.disabled || state_disabled;
553 let can_dec = !disabled && !state_readonly && self.state.read(cx).can_decrement(cx);
554 let can_inc = !disabled && !state_readonly && self.state.read(cx).can_increment(cx);
555
556 let icon_enabled = color(theme.colors.color(ColorRole::OnSurfaceVariant));
557 let icon_disabled = color(theme.colors.color(ColorRole::OnSurface)).opacity(0.38);
558 let hover_bg = color(theme.colors.color(ColorRole::OnSurface)).opacity(0.08);
559 let active_bg = color(theme.colors.color(ColorRole::OnSurface)).opacity(0.12);
560
561 let state_for_step = self.state.clone();
562 let on_step_cb = self.on_step.clone();
563 let on_change_cb = self.on_change.clone();
564 let perform_step: StepCallback = Rc::new(move |action, window, cx| {
565 let changed = state_for_step.update(cx, |state, cx| {
566 state.focus(window, cx);
567 state.step_by(action, window, cx)
568 });
569 if changed {
570 if let Some(cb) = on_step_cb.as_ref() {
571 cb(action, window, cx);
572 }
573 if let Some(cb) = on_change_cb.as_ref() {
574 let value = state_for_step.read(cx).value(cx);
575 cb(value, window, cx);
576 }
577 }
578 });
579
580 let build_step_button = |suffix: &'static str,
581 label: SharedString,
582 icon: IconName,
583 enabled: bool,
584 action: NumberStepAction,
585 perform: StepCallback| {
586 let tint = if enabled { icon_enabled } else { icon_disabled };
587 BaseButton::new((self.id.clone(), suffix))
588 .focusable(false)
589 .disabled(!enabled)
590 .accessibility_label(label)
591 .w(button_side)
592 .h(button_side)
593 .rounded_full()
594 .flex()
595 .items_center()
596 .justify_center()
597 .text_color(tint)
598 .when(enabled, |this| {
599 this.cursor_pointer()
600 .hover(move |style| style.bg(hover_bg))
601 .active(move |style| style.bg(active_bg))
602 .on_mouse_down(MouseButton::Left, |_, window, cx| {
603 window.prevent_default();
604 cx.stop_propagation();
605 })
606 .on_click(move |_, window, cx| {
607 cx.stop_propagation();
608 perform(action, window, cx);
609 })
610 })
611 .child(Icon::new(icon).size(px(18.)).inherit_color())
612 };
613
614 let mut field = TextField::new((self.id.clone(), "field"), self.label.clone(), &editor)
615 .variant(self.variant)
616 .disabled(disabled)
617 .invalid(self.invalid)
618 .required(self.required)
619 .show_label(self.show_label)
620 .colors(self.colors);
621
622 if let Some(placeholder) = self.placeholder {
623 field = field.placeholder_content(placeholder.clone(), Text::new(placeholder));
624 }
625 if let Some(prefix) = self.prefix {
626 field = field.prefix(prefix);
627 }
628 if let Some(suffix) = self.suffix {
629 field = field.suffix(suffix);
630 }
631 if let Some(error) = self.error {
632 field = field.error(error);
633 } else if let Some(supporting) = self.supporting {
634 field = field.supporting_text(supporting);
635 }
636
637 match self.stepper {
638 NumberInputStepper::Split => {
639 let dec = build_step_button(
640 "decrement",
641 self.decrement_label,
642 IconName::Remove,
643 can_dec,
644 NumberStepAction::Decrement,
645 perform_step.clone(),
646 );
647 let inc = build_step_button(
648 "increment",
649 self.increment_label,
650 IconName::Add,
651 can_inc,
652 NumberStepAction::Increment,
653 perform_step.clone(),
654 );
655 field = field.leading(dec).trailing(inc);
656 }
657 NumberInputStepper::Trailing => {
658 let dec = build_step_button(
659 "decrement",
660 self.decrement_label,
661 IconName::Remove,
662 can_dec,
663 NumberStepAction::Decrement,
664 perform_step.clone(),
665 );
666 let inc = build_step_button(
667 "increment",
668 self.increment_label,
669 IconName::Add,
670 can_inc,
671 NumberStepAction::Increment,
672 perform_step.clone(),
673 );
674 let group = div()
675 .flex()
676 .items_center()
677 .gap_0p5()
678 .when(rtl, Styled::flex_row_reverse)
679 .child(dec)
680 .child(inc);
681 field = field.trailing(group);
682 }
683 NumberInputStepper::None => {}
684 }
685
686 let base_step = perform_step.clone();
687 div().id(self.id).test_support().w_full().child(
688 BaseNumberInput::new(&editor)
689 .w_full()
690 .stepper(false)
691 .disabled(disabled)
692 .accessibility_label(self.label)
693 .on_step(move |action, window, cx| {
694 base_step(action.into(), window, cx);
695 })
696 .input(field),
697 )
698 }
699}
700
701fn parse_number(value: &str) -> Option<f64> {
702 let trimmed = value.trim();
703 if trimmed.is_empty() {
704 return None;
705 }
706 let parsed = trimmed.parse::<f64>().ok()?;
707 parsed.is_finite().then_some(parsed)
708}
709
710fn clamp_value(value: f64, min: Option<f64>, max: Option<f64>) -> f64 {
711 let mut clamped = value;
712 if let Some(min) = min {
713 clamped = clamped.max(min);
714 }
715 if let Some(max) = max {
716 clamped = clamped.min(max);
717 }
718 if clamped == 0.0 { 0.0 } else { clamped }
719}
720
721fn fraction_digits(value: &str) -> usize {
722 value.split('.').nth(1).map_or(0, |frac| frac.len())
723}
724
725fn format_number(value: f64, step: f64, precision: Option<usize>, current_text: &str) -> String {
726 let clean = if value == 0.0 { 0.0 } else { value };
727 if let Some(digits) = precision {
728 return format!("{clean:.digits$}");
729 }
730 let digits = fraction_digits(current_text).max(fraction_digits(&step.to_string()));
731 format!("{clean:.digits$}")
732}
733
734fn compute_step(
735 current_text: &str,
736 action: NumberStepAction,
737 step: f64,
738 min: Option<f64>,
739 max: Option<f64>,
740 precision: Option<usize>,
741) -> Option<String> {
742 let stepped = step_value(current_text, action.into(), step, min, max)?;
743 if let Some(digits) = precision {
744 let parsed = parse_number(&stepped)?;
745 let clean = if parsed == 0.0 { 0.0 } else { parsed };
746 Some(format!("{clean:.digits$}"))
747 } else if stepped == "-0" || stepped.starts_with("-0.") && parse_number(&stepped) == Some(0.0) {
748 Some(stepped.trim_start_matches('-').to_owned())
749 } else {
750 Some(stepped)
751 }
752}
753
754#[cfg(test)]
755mod tests {
756 use super::*;
757
758 #[test]
759 fn compute_step_respects_bounds_precision_and_zero_sign() {
760 assert_eq!(
761 compute_step("0.1", NumberStepAction::Increment, 0.2, None, None, None).as_deref(),
762 Some("0.3")
763 );
764 assert_eq!(
765 compute_step(
766 "10",
767 NumberStepAction::Increment,
768 1.0,
769 Some(0.0),
770 Some(10.0),
771 None
772 ),
773 None
774 );
775 assert_eq!(
776 compute_step(
777 "0",
778 NumberStepAction::Decrement,
779 1.0,
780 Some(0.0),
781 Some(10.0),
782 None
783 ),
784 None
785 );
786 assert_eq!(
787 compute_step(
788 "9.5",
789 NumberStepAction::Increment,
790 1.0,
791 Some(0.0),
792 Some(10.0),
793 Some(2)
794 )
795 .as_deref(),
796 Some("10.00")
797 );
798 assert_eq!(
799 compute_step("-1", NumberStepAction::Increment, 1.0, None, None, None).as_deref(),
800 Some("0")
801 );
802 }
803
804 #[test]
805 fn clamp_and_parse_filter_invalid_values() {
806 assert_eq!(parse_number(""), None);
807 assert_eq!(parse_number(" "), None);
808 assert_eq!(parse_number("NaN"), None);
809 assert_eq!(parse_number("42.5"), Some(42.5));
810 assert_eq!(clamp_value(-5.0, Some(0.0), Some(10.0)), 0.0);
811 assert_eq!(clamp_value(25.0, Some(0.0), Some(10.0)), 10.0);
812 assert_eq!(clamp_value(-0.0, None, None).to_bits(), 0.0_f64.to_bits());
813 }
814}