use crate::theme::ActiveTheme;
use gpui::{
AnyElement, App, Entity, FocusHandle, Focusable, InteractiveElement as _,
StatefulInteractiveElement as _, Window, div, px,
};
use gpui::{
IntoElement, ParentElement, RenderOnce, SharedString, StyleRefinement, Styled, TextAlign,
prelude::FluentBuilder as _,
};
use crate::{Disableable, Icon, IconName, Sizable, Size, StyleSized as _, StyledExt as _};
use super::{Input, InputState, input::input_style};
use crate::ThemeStyled as _;
use gpui_base::NumberInput as BaseNumberInput;
pub use gpui_base::{NumberInputEvent, NumberStep, StepAction};
use rust_i18n::t;
#[derive(IntoElement)]
pub struct NumberInput {
state: Entity<InputState>,
placeholder: SharedString,
size: Size,
prefix: Option<AnyElement>,
suffix: Option<AnyElement>,
appearance: bool,
focus_ring_enabled: bool,
disabled: bool,
accessibility_label: Option<SharedString>,
stepper: bool,
style: StyleRefinement,
}
impl NumberInput {
pub fn new(state: &Entity<InputState>) -> Self {
Self {
state: state.clone(),
size: Size::default(),
placeholder: SharedString::default(),
prefix: None,
suffix: None,
appearance: true,
focus_ring_enabled: true,
disabled: false,
accessibility_label: None,
stepper: true,
style: StyleRefinement::default(),
}
}
pub fn placeholder(mut self, placeholder: impl Into<SharedString>) -> Self {
self.placeholder = placeholder.into();
self
}
pub fn prefix(mut self, prefix: impl IntoElement) -> Self {
self.prefix = Some(prefix.into_any_element());
self
}
pub fn suffix(mut self, suffix: impl IntoElement) -> Self {
self.suffix = Some(suffix.into_any_element());
self
}
pub fn appearance(mut self, appearance: bool) -> Self {
self.appearance = appearance;
self
}
pub fn accessibility_label(mut self, label: impl Into<SharedString>) -> Self {
self.accessibility_label = Some(label.into());
self
}
pub fn stepper(mut self, stepper: bool) -> Self {
self.stepper = stepper;
self
}
}
impl Disableable for NumberInput {
fn disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled;
self
}
}
impl crate::FocusableExt for NumberInput {
fn focus_ring(mut self, enabled: bool) -> Self {
self.focus_ring_enabled = enabled;
self
}
fn is_focus_ring_enabled(&self) -> bool {
self.focus_ring_enabled
}
}
impl Focusable for NumberInput {
fn focus_handle(&self, cx: &App) -> FocusHandle {
self.state.focus_handle(cx)
}
}
impl Sizable for NumberInput {
fn with_size(mut self, size: impl Into<Size>) -> Self {
self.size = size.into();
self
}
}
impl Styled for NumberInput {
fn style(&mut self) -> &mut StyleRefinement {
&mut self.style
}
}
impl RenderOnce for NumberInput {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let focused = self.state.read(cx).focus_handle(cx).is_focused(window) && !self.disabled;
let (bg, _) = input_style(self.disabled, cx);
let border_color = if self.disabled {
cx.theme().input.opacity(0.5)
} else {
cx.theme().input
};
let button_foreground = cx.theme().secondary_foreground;
let button_hover = cx.theme().input.opacity(0.4);
let button_active = cx.theme().input.opacity(0.6);
let button_size = self.size;
let button_radius = if self.appearance {
(cx.theme().radius - px(1.)).max(px(0.))
} else {
cx.theme().radius
};
let base_state = self.state.clone();
let content = BaseNumberInput::new(&base_state)
.disabled(self.disabled)
.stepper(self.stepper)
.when_some(self.accessibility_label, |this, label| {
this.accessibility_label(label)
})
.size_full()
.when(self.stepper, |this| {
this.decrement_button(move |this| {
this.accessibility_label(t!("Input.Decrement"))
.flex()
.items_center()
.justify_center()
.text_color(button_foreground)
.hover(move |this| this.bg(button_hover))
.active(move |this| this.bg(button_active))
.h_full()
.map(|this| match button_size {
Size::XSmall | Size::Small => this.min_w_6(),
Size::Medium | Size::Large => this.min_w_8(),
Size::Size(size) => this.min_w(size),
})
.rounded_tl(button_radius)
.rounded_bl(button_radius)
.child(Icon::new(IconName::Minus).with_size(button_size))
})
})
.input(
Input::new(&self.state)
.appearance(false)
.with_size(button_size)
.h_full()
.disabled(self.disabled)
.gap_0()
.rounded_none()
.text_align(TextAlign::Center)
.when_some(self.prefix, |this, prefix| this.prefix(prefix))
.when_some(self.suffix, |this, suffix| this.suffix(suffix)),
)
.when(self.stepper, |this| {
this.increment_button(move |this| {
this.accessibility_label(t!("Input.Increment"))
.flex()
.items_center()
.justify_center()
.text_color(button_foreground)
.hover(move |this| this.bg(button_hover))
.active(move |this| this.bg(button_active))
.h_full()
.map(|this| match button_size {
Size::XSmall | Size::Small => this.min_w_6(),
Size::Medium | Size::Large => this.min_w_8(),
Size::Size(size) => this.min_w(size),
})
.rounded_tr(button_radius)
.rounded_br(button_radius)
.child(Icon::new(IconName::Plus).with_size(button_size))
})
});
div()
.flex_1()
.input_h(self.size)
.rounded(cx.theme().radius)
.when(self.appearance, |this| {
this.bg(bg)
.border_1()
.border_color(border_color)
.when(focused, |this| {
this.border_1().border_color(cx.theme().ring)
})
})
.refine_style(&self.style)
.when(self.disabled, |this| this.opacity(0.5))
.child(content)
.when(
focused && self.appearance && self.focus_ring_enabled,
|this| this.focus_ring_style(window, cx),
)
}
}
#[cfg(test)]
mod tests {
use super::StepAction;
use gpui_base::step_value;
#[test]
fn test_step_value() {
fn some(value: &str) -> Option<String> {
Some(value.to_string())
}
assert_eq!(
step_value("", StepAction::Increment, 1., None, None),
some("1")
);
assert_eq!(
step_value("", StepAction::Decrement, 1., None, None),
some("-1")
);
assert_eq!(
step_value("-", StepAction::Increment, 1., None, None),
some("1")
);
assert_eq!(
step_value("1", StepAction::Increment, 1., None, None),
some("2")
);
assert_eq!(
step_value("-2", StepAction::Increment, 1., None, None),
some("-1")
);
assert_eq!(
step_value("0.1", StepAction::Increment, 0.2, None, None),
some("0.3")
);
assert_eq!(
step_value("0.3", StepAction::Decrement, 0.1, None, None),
some("0.2")
);
assert_eq!(
step_value("1.25", StepAction::Increment, 1., None, None),
some("2.25")
);
assert_eq!(
step_value("", StepAction::Increment, 1., Some(10.), None),
some("10")
);
assert_eq!(
step_value("", StepAction::Decrement, 1., Some(10.), None),
some("10")
);
assert_eq!(
step_value("99.5", StepAction::Increment, 1., None, Some(100.)),
some("100.0")
);
assert_eq!(
step_value("1000", StepAction::Decrement, 1., None, Some(100.)),
some("100")
);
assert_eq!(
step_value("1", StepAction::Decrement, 1., Some(0.25), None),
some("0.25")
);
assert_eq!(
step_value("10", StepAction::Decrement, 1., Some(10.), None),
None
);
assert_eq!(
step_value("100", StepAction::Increment, 1., None, Some(100.)),
None
);
assert_eq!(
step_value("5", StepAction::Decrement, 1., Some(10.), None),
None
);
assert_eq!(
step_value("1000", StepAction::Increment, 1., None, Some(100.)),
None
);
}
}
#[cfg(all(test, feature = "test-support"))]
mod interaction_tests {
use super::*;
use gpui::{Context, Render, TestAppContext, VisualTestContext};
use gpui_base::test_support::{ElementSnapshot, find};
struct Probe {
state: Entity<InputState>,
show_stepper: bool,
}
impl Render for Probe {
fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
div().size_full().child(
NumberInput::new(&self.state).when(!self.show_stepper, |this| this.stepper(false)),
)
}
}
fn draw(cx: &mut VisualTestContext) {
cx.run_until_parked();
cx.update(|window, cx| window.draw(cx).clear(cx));
}
fn button(cx: &mut VisualTestContext, id: &'static str) -> Option<ElementSnapshot> {
cx.update(|window, _| find(window, &[], &id.into()))
}
#[gpui::test]
fn disabling_stepper_omits_buttons_and_keeps_keyboard_stepping(cx: &mut TestAppContext) {
use gpui::AppContext as _;
cx.update(crate::init);
let (probe, mut cx) = cx.add_window_view(|window, cx| Probe {
state: cx.new(|cx| InputState::new(window, cx).default_value("3")),
show_stepper: true,
});
let state = probe.read_with(cx, |probe, _| probe.state.clone());
draw(&mut cx);
for id in ["decrement", "increment"] {
assert!(
button(&mut cx, id).is_some(),
"{id} should exist by default"
);
}
probe.update(cx, |probe, cx| {
probe.show_stepper = false;
cx.notify();
});
draw(&mut cx);
for id in ["decrement", "increment"] {
assert!(
button(&mut cx, id).is_none(),
"{id} should not be constructed"
);
}
cx.update(|window, cx| {
state.update(cx, |state, cx| state.focus(window, cx));
});
cx.simulate_keystrokes("up");
draw(&mut cx);
assert_eq!(
state.read_with(cx, |state, _| state.value().to_string()),
"4"
);
}
#[gpui::test]
fn step_button_keeps_editor_focused_and_arrows_step(cx: &mut TestAppContext) {
use gpui::{AppContext as _, Modifiers, MouseButton};
cx.update(crate::init);
let (probe, mut cx) = cx.add_window_view(|window, cx| Probe {
state: cx.new(|cx| InputState::new(window, cx).default_value("3")),
show_stepper: true,
});
let state = probe.read_with(cx, |probe, _| probe.state.clone());
cx.update(|window, cx| {
state.update(cx, |state, cx| state.focus(window, cx));
});
draw(&mut cx);
let center = button(&mut cx, "increment").unwrap().bounds().center();
cx.simulate_mouse_move(center, None, Modifiers::default());
cx.simulate_mouse_down(center, MouseButton::Left, Modifiers::default());
cx.update(|window, cx| {
assert!(
state.read(cx).focus_handle(cx).is_focused(window),
"pressing the step button moved focus off the editor"
);
});
cx.simulate_mouse_up(center, MouseButton::Left, Modifiers::default());
draw(&mut cx);
cx.update(|window, cx| {
assert!(state.read(cx).focus_handle(cx).is_focused(window));
assert_eq!(state.read(cx).value(), "4");
});
cx.simulate_keystrokes("up up down");
draw(&mut cx);
assert_eq!(
state.read_with(cx, |state, _| state.value().to_string()),
"5"
);
}
}