fc_ui/capabilities/controls/
number_input.rs1use crate::capabilities::foundation::theme::use_theme;
2use gpui::{prelude::FluentBuilder as _, *};
3use std::rc::Rc;
4
5#[derive(Copy, Clone, Debug, PartialEq, Eq)]
6pub enum NumberInputSize {
7 Sm,
8 Md,
9 Lg,
10}
11
12pub struct NumberInputState {
13 value: f64,
14 has_value: bool,
15 min: Option<f64>,
16 max: Option<f64>,
17 step: f64,
18 precision: usize,
19 focus_handle: FocusHandle,
20}
21
22impl NumberInputState {
23 pub fn new(cx: &mut Context<Self>) -> Self {
24 Self {
25 value: 0.0,
26 has_value: false,
27 min: None,
28 max: None,
29 step: 1.0,
30 precision: 0,
31 focus_handle: cx.focus_handle(),
32 }
33 }
34
35 pub fn with_value(cx: &mut Context<Self>, value: f64) -> Self {
36 Self {
37 value,
38 has_value: true,
39 min: None,
40 max: None,
41 step: 1.0,
42 precision: 0,
43 focus_handle: cx.focus_handle(),
44 }
45 }
46
47 pub fn value(&self) -> f64 {
48 self.value
49 }
50
51 pub fn has_value(&self) -> bool {
52 self.has_value
53 }
54
55 pub fn set_value(&mut self, value: f64, cx: &mut Context<Self>) {
56 self.value = self.clamp_value(value);
57 self.has_value = true;
58 cx.notify();
59 }
60
61 pub fn set_min(&mut self, min: Option<f64>, cx: &mut Context<Self>) {
62 self.min = min;
63 self.value = self.clamp_value(self.value);
64 cx.notify();
65 }
66
67 pub fn set_max(&mut self, max: Option<f64>, cx: &mut Context<Self>) {
68 self.max = max;
69 self.value = self.clamp_value(self.value);
70 cx.notify();
71 }
72
73 pub fn set_step(&mut self, step: f64) {
74 self.step = step.max(0.001);
75 }
76
77 pub fn set_precision(&mut self, precision: usize) {
78 self.precision = precision;
79 }
80
81 pub fn increment(&mut self, cx: &mut Context<Self>) {
82 self.set_value(self.value + self.step, cx);
83 }
84
85 pub fn decrement(&mut self, cx: &mut Context<Self>) {
86 self.set_value(self.value - self.step, cx);
87 }
88
89 pub fn can_increment(&self) -> bool {
90 self.max.is_none_or(|max| self.value < max)
91 }
92
93 pub fn can_decrement(&self) -> bool {
94 self.min.is_none_or(|min| self.value > min)
95 }
96
97 fn clamp_value(&self, value: f64) -> f64 {
98 let mut v = value;
99 if let Some(min) = self.min {
100 v = v.max(min);
101 }
102 if let Some(max) = self.max {
103 v = v.min(max);
104 }
105 v
106 }
107
108 fn format_value(&self) -> String {
109 if self.precision == 0 {
110 format!("{}", self.value.round() as i64)
111 } else {
112 format!("{:.prec$}", self.value, prec = self.precision)
113 }
114 }
115}
116
117impl Focusable for NumberInputState {
118 fn focus_handle(&self, _: &App) -> FocusHandle {
119 self.focus_handle.clone()
120 }
121}
122
123impl Render for NumberInputState {
124 fn render(&mut self, _: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
125 div()
126 }
127}
128
129#[derive(IntoElement)]
130pub struct NumberInput {
131 state: Entity<NumberInputState>,
132 size: NumberInputSize,
133 placeholder: Option<SharedString>,
134 disabled: bool,
135 show_buttons: bool,
136 on_change: Option<Rc<dyn Fn(f64, &mut Window, &mut App)>>,
137 style: StyleRefinement,
138}
139
140impl NumberInput {
141 pub fn new(state: Entity<NumberInputState>) -> Self {
142 Self {
143 state,
144 size: NumberInputSize::Md,
145 placeholder: None,
146 disabled: false,
147 show_buttons: true,
148 on_change: None,
149 style: StyleRefinement::default(),
150 }
151 }
152
153 pub fn size(mut self, size: NumberInputSize) -> Self {
154 self.size = size;
155 self
156 }
157
158 pub fn placeholder(mut self, placeholder: impl Into<SharedString>) -> Self {
159 self.placeholder = Some(placeholder.into());
160 self
161 }
162
163 pub fn disabled(mut self, disabled: bool) -> Self {
164 self.disabled = disabled;
165 self
166 }
167
168 pub fn show_buttons(mut self, show: bool) -> Self {
169 self.show_buttons = show;
170 self
171 }
172
173 pub fn on_change(mut self, handler: impl Fn(f64, &mut Window, &mut App) + 'static) -> Self {
174 self.on_change = Some(Rc::new(handler));
175 self
176 }
177}
178
179impl Styled for NumberInput {
180 fn style(&mut self) -> &mut StyleRefinement {
181 &mut self.style
182 }
183}
184
185impl RenderOnce for NumberInput {
186 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
187 let theme = use_theme(cx);
188 let user_style = self.style;
189 let state_data = self.state.read(cx);
190 let has_value = state_data.has_value();
191 let value_text = state_data.format_value();
192 let can_increment = state_data.can_increment();
193 let can_decrement = state_data.can_decrement();
194 let focus_handle = state_data.focus_handle(cx);
195 let is_focused = focus_handle.is_focused(window);
196 let state = self.state.clone();
197
198 let show_placeholder = !has_value && self.placeholder.is_some();
199 let display_text: SharedString = if show_placeholder {
200 self.placeholder.clone().unwrap()
201 } else {
202 value_text.into()
203 };
204
205 let (height, padding_x, text_size, button_size) = match self.size {
206 NumberInputSize::Sm => (px(32.0), px(8.0), px(13.0), px(24.0)),
207 NumberInputSize::Md => (px(40.0), px(12.0), px(14.0), px(32.0)),
208 NumberInputSize::Lg => (px(48.0), px(14.0), px(16.0), px(40.0)),
209 };
210
211 div()
212 .flex()
213 .items_center()
214 .map(|mut this| {
215 this.style().refine(&user_style);
216 this
217 })
218 .child(
219 div()
220 .flex()
221 .items_center()
222 .h(height)
223 .bg(theme.tokens.background)
224 .border_1()
225 .border_color(if is_focused {
226 theme.tokens.ring
227 } else {
228 theme.tokens.input
229 })
230 .rounded(theme.tokens.radius_md)
231 .when(!self.disabled, |d| {
232 d.track_focus(&focus_handle.tab_index(0).tab_stop(true))
233 })
234 .when(!self.disabled, {
235 let state_for_key = state.clone();
236 let on_change_for_key = self.on_change.clone();
237 move |d| {
238 d.on_key_down(window.listener_for(
239 &state_for_key,
240 move |s, e: &KeyDownEvent, window, cx| {
241 match e.keystroke.key.as_str() {
242 "up" => s.increment(cx),
243 "down" => s.decrement(cx),
244 _ => return,
245 }
246 cx.stop_propagation();
247 if let Some(ref handler) = on_change_for_key {
248 handler(s.value, window, cx);
249 }
250 },
251 ))
252 }
253 })
254 .when(self.disabled, |d| d.opacity(0.5))
255 .when(self.show_buttons, {
256 let state = state.clone();
257 let on_change = self.on_change.clone();
258 let disabled = self.disabled;
259 move |d| {
260 d.child(
261 div()
262 .id("decrement")
263 .flex()
264 .items_center()
265 .justify_center()
266 .w(button_size)
267 .h_full()
268 .border_r_1()
269 .border_color(theme.tokens.border)
270 .text_color(if can_decrement && !disabled {
271 theme.tokens.foreground
272 } else {
273 theme.tokens.muted_foreground
274 })
275 .when(can_decrement && !disabled, |d| {
276 d.cursor_pointer()
277 .hover(|s| s.bg(theme.tokens.accent.opacity(0.5)))
278 })
279 .when(can_decrement && !disabled, {
280 let state = state.clone();
281 let on_change = on_change.clone();
282 move |d| {
283 d.on_click(move |_, window, cx| {
284 state.update(cx, |s, cx| {
285 s.decrement(cx);
286 if let Some(ref handler) = on_change {
287 handler(s.value, window, cx);
288 }
289 });
290 })
291 }
292 })
293 .child(
294 div()
295 .text_size(px(18.0))
296 .font_weight(FontWeight::MEDIUM)
297 .child("−"),
298 ),
299 )
300 }
301 })
302 .child(
303 div()
304 .flex_1()
305 .flex()
306 .items_center()
307 .justify_center()
308 .px(padding_x)
309 .h_full()
310 .min_w(px(60.0))
311 .text_size(text_size)
312 .text_color(if show_placeholder {
313 theme.tokens.muted_foreground
314 } else {
315 theme.tokens.foreground
316 })
317 .font_family(theme.tokens.font_family.clone())
318 .child(display_text),
319 )
320 .when(self.show_buttons, {
321 let state = state.clone();
322 let on_change = self.on_change.clone();
323 let disabled = self.disabled;
324 move |d| {
325 d.child(
326 div()
327 .id("increment")
328 .flex()
329 .items_center()
330 .justify_center()
331 .w(button_size)
332 .h_full()
333 .border_l_1()
334 .border_color(theme.tokens.border)
335 .text_color(if can_increment && !disabled {
336 theme.tokens.foreground
337 } else {
338 theme.tokens.muted_foreground
339 })
340 .when(can_increment && !disabled, |d| {
341 d.cursor_pointer()
342 .hover(|s| s.bg(theme.tokens.accent.opacity(0.5)))
343 })
344 .when(can_increment && !disabled, {
345 let state = state.clone();
346 let on_change = on_change.clone();
347 move |d| {
348 d.on_click(move |_, window, cx| {
349 state.update(cx, |s, cx| {
350 s.increment(cx);
351 if let Some(ref handler) = on_change {
352 handler(s.value, window, cx);
353 }
354 });
355 })
356 }
357 })
358 .child(
359 div()
360 .text_size(px(18.0))
361 .font_weight(FontWeight::MEDIUM)
362 .child("+"),
363 ),
364 )
365 }
366 }),
367 )
368 }
369}