number_input: Add support for prefix and suffix (#896)

<img width="1097" alt="image"
src="https://github.com/user-attachments/assets/b4c1fc69-88ad-4ecd-b1c8-1a5a92836e82"
/>
This commit is contained in:
Floyd Wang 2025-05-26 16:16:22 +08:00 committed by GitHub
parent a95482fdd8
commit a1ad647527
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 35 additions and 8 deletions

View file

@ -6,8 +6,9 @@ use regex::Regex;
use crate::section;
use gpui_component::{
button::{Button, ButtonVariants},
input::{InputEvent, InputState, MaskPattern, NumberInput, NumberInputEvent, StepAction},
v_flex, FocusableCycle, Sizable,
v_flex, FocusableCycle, IconName, Sizable,
};
actions!(input_story, [Tab, TabPrev]);
@ -215,9 +216,15 @@ impl Render for NumberInputStory {
.child(NumberInput::new(&self.number_input1)),
)
.child(
section("Small Size")
.max_w_md()
.child(NumberInput::new(&self.number_input2).small()),
section("Small Size with suffix").max_w_md().child(
NumberInput::new(&self.number_input2).small().suffix(
Button::new("info")
.ghost()
.icon(IconName::Info)
.xsmall()
.mr_3(),
),
),
)
.child(
section("With mask pattern")

View file

@ -1,7 +1,7 @@
use gpui::{
actions, prelude::FluentBuilder as _, px, App, Context, ElementId, Entity, EventEmitter,
FocusHandle, Focusable, InteractiveElement, IntoElement, KeyBinding, ParentElement, RenderOnce,
SharedString, Styled, Window,
actions, prelude::FluentBuilder as _, px, AnyElement, App, Context, ElementId, Entity,
EventEmitter, FocusHandle, Focusable, InteractiveElement, IntoElement, KeyBinding,
ParentElement, RenderOnce, SharedString, Styled, Window,
};
use crate::{
@ -28,6 +28,8 @@ pub struct NumberInput {
state: Entity<InputState>,
placeholder: SharedString,
size: Size,
prefix: Option<AnyElement>,
suffix: Option<AnyElement>,
}
impl NumberInput {
@ -38,6 +40,8 @@ impl NumberInput {
state: state.clone(),
size: Size::default(),
placeholder: SharedString::default(),
prefix: None,
suffix: None,
}
}
@ -62,6 +66,16 @@ impl NumberInput {
state.on_action_decrement(&Decrement, window, cx);
})
}
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
}
}
impl InputState {
@ -142,7 +156,13 @@ impl RenderOnce for NumberInput {
}
}),
)
.child(TextInput::new(&self.state).appearance(false).no_gap())
.child(
TextInput::new(&self.state)
.appearance(false)
.no_gap()
.when_some(self.prefix, |this, prefix| this.prefix(prefix))
.when_some(self.suffix, |this, suffix| this.suffix(suffix)),
)
.child(
Button::new("plus")
.ghost()