1use std::rc::Rc;
17
18use arc_motion::{
19 BlurFallback, arc_spring, arc_spring_with_options, arc_transition, is_reduced_motion,
20 motion_now, spring::SpringOptions,
21};
22use arc_tokens::{ActiveArcTheme as _, ControlHeights, Radii, Spacing, Typography, oklab_mix};
23use gpui_kit::{
24 App, ElementId, FocusHandle, Hsla, IntoElement, KeyDownEvent, MouseButton, MouseDownEvent,
25 MouseMoveEvent, MouseUpEvent, ParentElement, PathBuilder, Pixels, RenderOnce, Role,
26 SharedString, Styled, TestSupportExt as _, Window,
27 base::{Button as BaseButton, StyledExt as _},
28 canvas, div, point,
29 prelude::*,
30 px,
31};
32
33use super::field_message::render_field_message;
34use crate::text::animated_counter::{CounterPart, counter_parts, glyph_alpha, wheel_offset};
35
36type NumberFieldChangeHandler = Rc<dyn Fn(&f64, &mut Window, &mut App)>;
37type DynamicAffixFn = Rc<dyn Fn(f64) -> SharedString>;
38
39pub const NUMBER_FIELD_SCRUB_PX: f32 = 6.0;
41pub const NUMBER_FIELD_RUBBER_LIMIT_PX: f32 = 10.0;
43pub const NUMBER_FIELD_LIMIT_HINT_SECS: f64 = 1.5;
45pub const NUMBER_FIELD_PUSH_WINDOW_SECS: f64 = 0.7;
47pub const NUMBER_FIELD_PUSH_GAIN: f32 = 0.22;
49pub const NUMBER_FIELD_PUSH_CAP: u32 = 4;
50
51pub fn number_field_rubber(distance: f32, limit: f32) -> f32 {
54 if distance.abs() < 1e-5 || limit <= 0.0 {
55 return 0.0;
56 }
57 distance.signum() * (1.0 - 1.0 / (distance.abs() * 0.55 / limit + 1.0)) * limit
58}
59
60pub fn number_field_bump_offset(elapsed: f64, edge: i8, push_count: u32, reduced: bool) -> f32 {
63 if reduced || edge == 0 || !(0.0..0.42).contains(&elapsed) {
64 return 0.0;
65 }
66 let extra =
67 (push_count.saturating_sub(1).min(NUMBER_FIELD_PUSH_CAP) as f32) * NUMBER_FIELD_PUSH_GAIN;
68 let amp = 3.6 * (1.0 + extra);
69 let t = elapsed as f32;
70 let omega = 15.0_f32;
72 let env = (omega * t * std::f32::consts::E * (-omega * t).exp()).clamp(0.0, 1.0);
73 -(edge as f32) * amp * env
74}
75
76pub fn number_field_icon_shake_x(elapsed: f64, reduced: bool) -> f32 {
79 if reduced || !(0.0..0.32).contains(&elapsed) {
80 return 0.0;
81 }
82 let keyframes = [0.0_f32, -2.5, 2.5, -1.5, 1.0, 0.0];
83 let segments = (keyframes.len() - 1) as f32;
84 let pos = ((elapsed / 0.32).clamp(0.0, 1.0) as f32) * segments;
85 let idx = (pos.floor() as usize).min(keyframes.len() - 2);
86 let frac = pos - idx as f32;
87 keyframes[idx] + (keyframes[idx + 1] - keyframes[idx]) * frac
88}
89
90pub fn number_field_step_from(from: f64, base: f64, step: f64, steps: i64, decimals: usize) -> f64 {
93 let safe_step = if step > 0.0 { step } else { 1.0 };
94 let idx = (from - base) / safe_step;
95 let grid_idx = if steps > 0 {
96 (idx + 1e-7).floor()
97 } else if steps < 0 {
98 (idx - 1e-7).ceil()
99 } else {
100 idx.round()
101 };
102 let raw = base + (grid_idx + steps as f64) * safe_step;
103 let scale = 10_f64.powi(decimals as i32);
104 (raw * scale).round() / scale
105}
106
107#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
109pub enum NumberFieldSize {
110 Sm,
111 #[default]
112 Md,
113 Lg,
114}
115
116impl NumberFieldSize {
117 pub fn control_height(self) -> Pixels {
118 match self {
119 Self::Sm => ControlHeights::SM,
120 Self::Md => ControlHeights::MD,
121 Self::Lg => ControlHeights::LG,
122 }
123 }
124
125 pub const fn step_button_px(self) -> f32 {
126 match self {
127 Self::Sm => 24.0,
128 Self::Md => 28.0,
129 Self::Lg => 32.0,
130 }
131 }
132
133 pub const fn inset_px(self) -> f32 {
134 match self {
135 Self::Sm | Self::Md => 2.0,
136 Self::Lg => 3.0,
137 }
138 }
139
140 pub const fn default_width_px(self) -> f32 {
141 match self {
142 Self::Sm => 144.0,
143 Self::Md => 168.0,
144 Self::Lg => 196.0,
145 }
146 }
147
148 pub fn text_size(self) -> Pixels {
149 match self {
150 Self::Sm => Typography::TEXT_XS,
151 Self::Md => Typography::TEXT_SM,
152 Self::Lg => Typography::TEXT_BASE,
153 }
154 }
155
156 pub const fn digit_height_px(self) -> f32 {
157 match self {
158 Self::Sm => 18.0,
159 Self::Md => 20.0,
160 Self::Lg => 22.0,
161 }
162 }
163
164 pub const fn digit_width_px(self) -> f32 {
165 match self {
166 Self::Sm => 8.0,
167 Self::Md => 9.0,
168 Self::Lg => 10.0,
169 }
170 }
171}
172
173#[derive(Clone)]
175pub enum NumberFieldAffix {
176 Static(SharedString),
177 Dynamic(DynamicAffixFn),
178}
179
180impl NumberFieldAffix {
181 pub fn evaluate(&self, value: f64) -> SharedString {
182 match self {
183 Self::Static(s) => s.clone(),
184 Self::Dynamic(f) => f(value),
185 }
186 }
187}
188
189impl From<&'static str> for NumberFieldAffix {
190 fn from(s: &'static str) -> Self {
191 Self::Static(s.into())
192 }
193}
194
195impl From<SharedString> for NumberFieldAffix {
196 fn from(s: SharedString) -> Self {
197 Self::Static(s)
198 }
199}
200
201#[derive(Clone)]
202struct NumberFieldInternal {
203 uncontrolled_value: f64,
204 last_value: f64,
205 direction: i8,
206 pressed_step: i8,
207 hovered_step: i8,
208 control_hovered: bool,
209 label_hovered: bool,
210 pushed_edge: i8,
211 pushed_at_secs: f64,
212 push_count: u32,
213 scrub_active: bool,
214 scrub_pressing: bool,
215 scrub_start_x: f32,
216 scrub_from_value: f64,
217 scrub_rubber_x: f32,
218 focus_handle: FocusHandle,
219}
220
221impl NumberFieldInternal {
222 fn new(initial: f64, now: f64, focus_handle: FocusHandle) -> Self {
223 Self {
224 uncontrolled_value: initial,
225 last_value: initial,
226 direction: 1,
227 pressed_step: 0,
228 hovered_step: 0,
229 control_hovered: false,
230 label_hovered: false,
231 pushed_edge: 0,
232 pushed_at_secs: now - 10.0,
233 push_count: 0,
234 scrub_active: false,
235 scrub_pressing: false,
236 scrub_start_x: 0.0,
237 scrub_from_value: initial,
238 scrub_rubber_x: 0.0,
239 focus_handle,
240 }
241 }
242}
243
244fn paint_plus_or_minus(
245 cx: f32,
246 cy: f32,
247 is_plus: bool,
248 scale: f32,
249 color: Hsla,
250 window: &mut Window,
251) {
252 let half = 4.5 * scale;
253 let mut builder = PathBuilder::stroke(px(1.75));
254 builder.move_to(point(px(cx - half), px(cy)));
255 builder.line_to(point(px(cx + half), px(cy)));
256 if is_plus {
257 builder.move_to(point(px(cx), px(cy - half)));
258 builder.line_to(point(px(cx), px(cy + half)));
259 }
260 if let Ok(path) = builder.build() {
261 window.paint_path(path, color);
262 }
263}
264
265#[derive(IntoElement)]
269pub struct NumberField {
270 id: ElementId,
271 label: SharedString,
272 value: Option<f64>,
273 default_value: f64,
274 min: f64,
275 max: f64,
276 step: f64,
277 large_step: Option<f64>,
278 decimals: Option<usize>,
279 use_grouping: bool,
280 prefix: Option<NumberFieldAffix>,
281 suffix: Option<NumberFieldAffix>,
282 scrub: bool,
283 size: NumberFieldSize,
284 limit_hint: bool,
285 description: Option<SharedString>,
286 disabled: bool,
287 width: Option<Pixels>,
288 on_value_change: Option<NumberFieldChangeHandler>,
289}
290
291impl NumberField {
292 pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
293 Self {
294 id: id.into(),
295 label: label.into(),
296 value: None,
297 default_value: 0.0,
298 min: 0.0,
299 max: 1_000_000_000.0,
300 step: 1.0,
301 large_step: None,
302 decimals: None,
303 use_grouping: true,
304 prefix: None,
305 suffix: None,
306 scrub: false,
307 size: NumberFieldSize::Md,
308 limit_hint: true,
309 description: None,
310 disabled: false,
311 width: None,
312 on_value_change: None,
313 }
314 }
315
316 pub fn value(mut self, value: f64) -> Self {
317 self.value = Some(value);
318 self
319 }
320
321 pub fn default_value(mut self, value: f64) -> Self {
322 self.default_value = value;
323 self
324 }
325
326 pub fn min(mut self, min: f64) -> Self {
327 self.min = min;
328 self
329 }
330
331 pub fn max(mut self, max: f64) -> Self {
332 self.max = max;
333 self
334 }
335
336 pub fn step(mut self, step: f64) -> Self {
337 self.step = if step > 0.0 { step } else { 1.0 };
338 self
339 }
340
341 pub fn large_step(mut self, large_step: f64) -> Self {
342 self.large_step = Some(large_step.max(self.step));
343 self
344 }
345
346 pub fn decimals(mut self, decimals: usize) -> Self {
347 self.decimals = Some(decimals);
348 self
349 }
350
351 pub fn use_grouping(mut self, grouping: bool) -> Self {
352 self.use_grouping = grouping;
353 self
354 }
355
356 pub fn prefix(mut self, prefix: impl Into<NumberFieldAffix>) -> Self {
357 self.prefix = Some(prefix.into());
358 self
359 }
360
361 pub fn prefix_fn(mut self, f: impl Fn(f64) -> SharedString + 'static) -> Self {
362 self.prefix = Some(NumberFieldAffix::Dynamic(Rc::new(f)));
363 self
364 }
365
366 pub fn suffix(mut self, suffix: impl Into<NumberFieldAffix>) -> Self {
367 self.suffix = Some(suffix.into());
368 self
369 }
370
371 pub fn suffix_fn(mut self, f: impl Fn(f64) -> SharedString + 'static) -> Self {
372 self.suffix = Some(NumberFieldAffix::Dynamic(Rc::new(f)));
373 self
374 }
375
376 pub fn scrub(mut self, scrub: bool) -> Self {
377 self.scrub = scrub;
378 self
379 }
380
381 pub fn size(mut self, size: NumberFieldSize) -> Self {
382 self.size = size;
383 self
384 }
385
386 pub fn limit_hint(mut self, limit_hint: bool) -> Self {
387 self.limit_hint = limit_hint;
388 self
389 }
390
391 pub fn description(mut self, description: impl Into<SharedString>) -> Self {
392 self.description = Some(description.into());
393 self
394 }
395
396 pub fn disabled(mut self, disabled: bool) -> Self {
397 self.disabled = disabled;
398 self
399 }
400
401 pub fn width(mut self, width: impl Into<Pixels>) -> Self {
402 self.width = Some(width.into());
403 self
404 }
405
406 pub fn on_value_change(
407 mut self,
408 handler: impl Fn(&f64, &mut Window, &mut App) + 'static,
409 ) -> Self {
410 self.on_value_change = Some(Rc::new(handler));
411 self
412 }
413}
414
415fn infer_decimals(step: f64) -> usize {
416 let s = format!("{step}");
417 s.split('.').nth(1).map(|f| f.len()).unwrap_or(0)
418}
419
420impl RenderOnce for NumberField {
421 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
422 let theme = cx.arc_theme().clone();
423 let colors = theme.colors;
424 let motion = theme.motion;
425 let reduced = is_reduced_motion(cx);
426 let now = motion_now(cx);
427
428 let decimals = self.decimals.unwrap_or_else(|| infer_decimals(self.step));
429 let min_v = self.min;
430 let max_v = self.max.max(min_v);
431 let step_v = self.step;
432 let large_v = self.large_step.unwrap_or(step_v * 10.0);
433
434 let initial_val = self.value.unwrap_or(self.default_value).clamp(min_v, max_v);
435
436 let state_id =
437 ElementId::NamedChild(self.id.clone().into(), "__arc-number-field-state".into());
438 let internal = window.use_keyed_state(state_id, cx, |_, cx| {
439 NumberFieldInternal::new(initial_val, now, cx.focus_handle())
440 });
441
442 let current = self
443 .value
444 .unwrap_or_else(|| internal.read(cx).uncontrolled_value)
445 .clamp(min_v, max_v);
446
447 {
449 let prev = internal.read(cx).last_value;
450 if (current - prev).abs() > 1e-9 {
451 let dir = if current >= prev { 1 } else { -1 };
452 internal.update(cx, |s, _| {
453 s.last_value = current;
454 s.direction = dir;
455 });
456 }
457 }
458
459 let snap = internal.read(cx).clone();
460 let is_focused = snap.focus_handle.is_focused(window);
461 let at_min = current <= min_v + 1e-9;
462 let at_max = current >= max_v - 1e-9;
463
464 let push_elapsed = (now - snap.pushed_at_secs).max(0.0);
466 let active_limit_edge = if self.limit_hint && push_elapsed < NUMBER_FIELD_LIMIT_HINT_SECS {
467 window.request_animation_frame();
468 snap.pushed_edge
469 } else {
470 0
471 };
472 let strain_active = push_elapsed < 0.42 && snap.pushed_edge != 0;
473 if strain_active {
474 window.request_animation_frame();
475 }
476 let bump_y =
477 number_field_bump_offset(push_elapsed, snap.pushed_edge, snap.push_count, reduced);
478 let minus_shake_x = if snap.pushed_edge < 0 {
479 number_field_icon_shake_x(push_elapsed, reduced)
480 } else {
481 0.0
482 };
483 let plus_shake_x = if snap.pushed_edge > 0 {
484 number_field_icon_shake_x(push_elapsed, reduced)
485 } else {
486 0.0
487 };
488
489 let scrub_x = if snap.scrub_active {
491 let _ = arc_spring_with_options(
492 (self.id.clone(), "scrub-x"),
493 snap.scrub_rubber_x,
494 SpringOptions::new(motion.spring.snappy).with_initial_value(snap.scrub_rubber_x),
495 window,
496 cx,
497 );
498 snap.scrub_rubber_x
499 } else if reduced {
500 0.0
501 } else {
502 arc_spring(
503 (self.id.clone(), "scrub-x"),
504 0.0,
505 motion.spring.snappy,
506 window,
507 cx,
508 )
509 };
510
511 let limit_color = oklab_mix(
513 colors.warning,
514 colors.foreground,
515 if theme.mode.is_dark() { 0.12 } else { 0.28 },
516 );
517 let limit_op = arc_transition(
518 (self.id.clone(), "limit-op"),
519 if active_limit_edge != 0 { 1.0 } else { 0.0 },
520 if reduced {
521 motion.duration.instant
522 } else if active_limit_edge != 0 {
523 motion.duration.fast
524 } else {
525 motion.duration.standard
526 },
527 motion.ease.standard,
528 window,
529 cx,
530 );
531 let limit_y = if reduced {
532 0.0
533 } else {
534 arc_spring(
535 (self.id.clone(), "limit-y"),
536 if active_limit_edge != 0 {
537 0.0
538 } else {
539 (snap.pushed_edge as f32) * 5.4
540 },
541 motion.spring.snappy,
542 window,
543 cx,
544 )
545 };
546
547 let prefix_str = self
548 .prefix
549 .as_ref()
550 .map(|p| p.evaluate(current))
551 .unwrap_or_default();
552 let suffix_str = self
553 .suffix
554 .as_ref()
555 .map(|s| s.evaluate(current))
556 .unwrap_or_default();
557 let limit_val = if snap.pushed_edge >= 0 { max_v } else { min_v };
558 let limit_prefix = self
559 .prefix
560 .as_ref()
561 .map(|p| p.evaluate(limit_val))
562 .unwrap_or_default();
563 let limit_suffix = self
564 .suffix
565 .as_ref()
566 .map(|s| s.evaluate(limit_val))
567 .unwrap_or_default();
568 let limit_note_text = SharedString::from(format!(
569 "{} {limit_prefix}{limit_val:.*}{limit_suffix}",
570 if snap.pushed_edge >= 0 { "Max" } else { "Min" },
571 decimals
572 ));
573
574 let digit_h = self.size.digit_height_px();
576 let digit_w = self.size.digit_width_px();
577 let font_sz = self.size.text_size();
578 let mut parts = counter_parts(current, decimals);
579 if !self.use_grouping {
580 parts.retain(|p| !matches!(p, CounterPart::Text { key, .. } if key.starts_with('g')));
581 }
582 let value_text_color = if reduced && strain_active {
583 limit_color
584 } else {
585 colors.foreground
586 };
587
588 let mut number_cols = Vec::with_capacity(parts.len());
589 for part in parts {
590 match part {
591 CounterPart::Text { key, text } => {
592 number_cols.push(
593 div()
594 .id(ElementId::NamedChild(
595 self.id.clone().into(),
596 SharedString::from(key),
597 ))
598 .h(px(digit_h))
599 .flex()
600 .items_center()
601 .text_size(font_sz)
602 .font_medium()
603 .text_color(value_text_color)
604 .child(SharedString::from(text))
605 .into_any_element(),
606 );
607 }
608 CounterPart::Digit { key, digit, .. } => {
609 let pos = if reduced {
610 digit as f32
611 } else {
612 arc_spring(
613 (self.id.clone(), format!("wheel-{key}")),
614 digit as f32,
615 motion.spring.snappy,
616 window,
617 cx,
618 )
619 };
620 let mut col = div()
621 .id(ElementId::NamedChild(
622 self.id.clone().into(),
623 SharedString::from(key),
624 ))
625 .relative()
626 .w(px(digit_w))
627 .h(px(digit_h))
628 .overflow_hidden();
629
630 for d in 0..=9_u8 {
631 let off = wheel_offset(d, pos);
632 let alpha = glyph_alpha(off);
633 if alpha > 0.01 {
634 let blur_px = if off.abs() < 0.02 {
635 0.0
636 } else {
637 off.abs() * 3.0
638 };
639 let blur = BlurFallback::evaluate(px(blur_px), reduced);
640 let y_px = off * digit_h * 1.05;
641 col = col.child(
642 div()
643 .absolute()
644 .left_0()
645 .right_0()
646 .top(px(y_px))
647 .h(px(digit_h))
648 .flex()
649 .items_center()
650 .justify_center()
651 .text_size(font_sz)
652 .font_medium()
653 .text_color(value_text_color)
654 .opacity((alpha * blur.opacity_multiplier).clamp(0.0, 1.0))
655 .child(SharedString::from(d.to_string())),
656 );
657 }
658 }
659 number_cols.push(col.into_any_element());
660 }
661 }
662 }
663
664 let render_affix_chars =
666 |tag: &'static str, text: &str, window: &mut Window, cx: &mut App| {
667 text.chars()
668 .enumerate()
669 .map(|(idx, ch)| {
670 let ch_str = SharedString::from(ch.to_string());
671 let slot_key = format!("affix-{tag}-{idx}-{ch}");
672 let p = arc_transition(
673 (self.id.clone(), slot_key),
674 1.0,
675 if reduced {
676 motion.duration.instant
677 } else {
678 motion.duration.fast
679 },
680 motion.ease.enter,
681 window,
682 cx,
683 );
684 let y = if reduced {
685 0.0
686 } else {
687 (snap.direction as f32) * 3.5 * (1.0 - p)
688 };
689 div()
690 .mt(px(y))
691 .opacity(p)
692 .text_size(font_sz)
693 .text_color(colors.text_secondary)
694 .child(ch_str)
695 .into_any_element()
696 })
697 .collect::<Vec<_>>()
698 };
699
700 let prefix_els = render_affix_chars("pre", &prefix_str, window, cx);
701 let suffix_els = render_affix_chars("suf", &suffix_str, window, cx);
702
703 let step_px = self.size.step_button_px();
705 let inset_px = self.size.inset_px();
706 let step_radius = (Radii::CONTROL - px(inset_px + 1.0)).max(px(4.0));
707 let disabled = self.disabled;
708
709 let make_step_button = |toward: i8, window: &mut Window, cx: &mut App| {
710 let is_plus = toward > 0;
711 let at_limit = if is_plus { at_max } else { at_min };
712 let is_pressed = snap.pressed_step == toward && !disabled;
713 let is_hovered = snap.hovered_step == toward && !disabled && !at_limit;
714 let is_strained = strain_active && snap.pushed_edge == toward;
715
716 let icon_scale = if reduced {
717 1.0
718 } else {
719 arc_spring(
720 (
721 self.id.clone(),
722 if is_plus { "plus-scale" } else { "minus-scale" },
723 ),
724 if is_pressed && !at_limit { 0.82 } else { 1.0 },
725 motion.spring.snappy,
726 window,
727 cx,
728 )
729 };
730
731 let btn_bg = if is_pressed && !at_limit {
732 oklab_mix(colors.foreground, colors.surface, 0.10)
733 } else if is_hovered {
734 colors.surface_muted
735 } else {
736 Hsla::transparent_black()
737 };
738 let icon_color = if is_strained {
739 limit_color
740 } else if is_pressed || is_hovered {
741 colors.foreground
742 } else {
743 colors.text_secondary
744 };
745 let btn_opacity = if disabled {
746 0.35
747 } else if is_strained {
748 0.60
749 } else if at_limit {
750 0.32
751 } else {
752 1.0
753 };
754 let shake_x = if is_plus { plus_shake_x } else { minus_shake_x };
755
756 let int_hover = internal.clone();
757 let int_down = internal.clone();
758 let int_up = internal.clone();
759 let int_out = internal.clone();
760 let int_click = internal.clone();
761 let on_change = self.on_value_change.clone();
762 let focus_for_step = snap.focus_handle.clone();
763 let btn_id = ElementId::NamedChild(
764 self.id.clone().into(),
765 if is_plus {
766 "increase".into()
767 } else {
768 "decrease".into()
769 },
770 );
771 let aria_lbl = SharedString::from(format!(
772 "{} {}",
773 if is_plus { "Increase" } else { "Decrease" },
774 self.label
775 ));
776
777 BaseButton::new(btn_id)
778 .accessibility_label(aria_lbl)
779 .disabled(disabled)
780 .on_click(move |_, window, cx| {
781 if disabled {
782 return;
783 }
784 window.focus(&focus_for_step, cx);
785 let t_now = motion_now(cx);
786 let next_raw =
787 number_field_step_from(current, min_v, step_v, toward as i64, decimals);
788 let clamped = next_raw.clamp(min_v, max_v);
789 let hit_limit = (next_raw - clamped).abs() > 1e-9;
790 int_click.update(cx, |s, _| {
791 s.pressed_step = 0;
792 if hit_limit {
793 let same_window = s.pushed_edge == toward
794 && (t_now - s.pushed_at_secs) < NUMBER_FIELD_PUSH_WINDOW_SECS;
795 s.push_count = if same_window { s.push_count + 1 } else { 1 };
796 s.pushed_edge = toward;
797 s.pushed_at_secs = t_now;
798 }
799 if (clamped - current).abs() > 1e-9 {
800 s.direction = toward;
801 s.uncontrolled_value = clamped;
802 s.last_value = clamped;
803 }
804 });
805 if (clamped - current).abs() > 1e-9
806 && let Some(cb) = &on_change
807 {
808 cb(&clamped, window, cx);
809 }
810 window.refresh();
811 })
812 .w(px(step_px))
813 .h(px(step_px))
814 .flex_none()
815 .flex()
816 .items_center()
817 .justify_center()
818 .rounded(step_radius)
819 .bg(btn_bg)
820 .opacity(btn_opacity)
821 .when(!disabled && !at_limit, |this| this.cursor_pointer())
822 .on_hover(move |hovered, window, cx| {
823 int_hover.update(cx, |s, _| {
824 if *hovered {
825 s.hovered_step = toward;
826 } else if s.hovered_step == toward {
827 s.hovered_step = 0;
828 }
829 });
830 window.refresh();
831 })
832 .on_mouse_down(MouseButton::Left, move |_, window, cx| {
833 if !disabled {
834 int_down.update(cx, |s, _| s.pressed_step = toward);
835 window.refresh();
836 }
837 })
838 .on_mouse_up(MouseButton::Left, move |_, window, cx| {
839 if int_up.read(cx).pressed_step == toward {
840 int_up.update(cx, |s, _| s.pressed_step = 0);
841 window.refresh();
842 }
843 })
844 .on_mouse_up_out(MouseButton::Left, move |_, window, cx| {
845 if int_out.read(cx).pressed_step == toward {
846 int_out.update(cx, |s, _| s.pressed_step = 0);
847 window.refresh();
848 }
849 })
850 .child(
851 div().ml(px(shake_x)).size(px(16.0)).child(
852 canvas(
853 |_, _, _| {},
854 move |rect, _, window, _| {
855 let cx_pt = f32::from(rect.origin.x + rect.size.width * 0.5);
856 let cy_pt = f32::from(rect.origin.y + rect.size.height * 0.5);
857 paint_plus_or_minus(
858 cx_pt, cy_pt, is_plus, icon_scale, icon_color, window,
859 );
860 },
861 )
862 .size_full(),
863 ),
864 )
865 };
866
867 let minus_btn = make_step_button(-1, window, cx);
868 let plus_btn = make_step_button(1, window, cx);
869
870 let can_scrub = self.scrub && !disabled;
872 let int_lbl_hover = internal.clone();
873 let int_lbl_down = internal.clone();
874 let int_scrub_drag = internal.clone();
875 let on_change_scrub = self.on_value_change.clone();
876 let scrub_pressing = snap.scrub_pressing;
877
878 let scrub_listener = canvas(
879 |_, _, _| {},
880 move |_, _, window, _| {
881 if scrub_pressing {
882 let st_move = int_scrub_drag.clone();
883 let cb_move = on_change_scrub.clone();
884 window.on_mouse_event(move |event: &MouseMoveEvent, phase, window, cx| {
885 if !phase.bubble() {
886 return;
887 }
888 let (pressing, start_x, from_val, prev_uncontrolled) = {
889 let s = st_move.read(cx);
890 (
891 s.scrub_pressing,
892 s.scrub_start_x,
893 s.scrub_from_value,
894 s.uncontrolled_value,
895 )
896 };
897 if !pressing {
898 return;
899 }
900 let dx = f32::from(event.position.x) - start_x;
901 if dx.abs() < 3.0 && !st_move.read(cx).scrub_active {
902 return;
903 }
904 let travel = dx / NUMBER_FIELD_SCRUB_PX;
905 let steps = travel.trunc() as i64;
906 let stepped = if steps != 0 {
907 number_field_step_from(from_val, min_v, step_v, steps, decimals)
908 } else {
909 from_val
910 };
911 let clamped = stepped.clamp(min_v, max_v);
912 let raw = from_val + (travel as f64) * step_v;
913 let over_px = if raw > max_v {
914 ((raw - max_v) / step_v) as f32 * NUMBER_FIELD_SCRUB_PX
915 } else if raw < min_v {
916 ((raw - min_v) / step_v) as f32 * NUMBER_FIELD_SCRUB_PX
917 } else {
918 0.0
919 };
920 let rub = if reduced {
921 0.0
922 } else {
923 number_field_rubber(over_px, NUMBER_FIELD_RUBBER_LIMIT_PX)
924 };
925 st_move.update(cx, |s, _| {
926 s.scrub_active = true;
927 s.scrub_rubber_x = rub;
928 if (clamped - prev_uncontrolled).abs() > 1e-9 {
929 s.direction = if clamped >= prev_uncontrolled { 1 } else { -1 };
930 s.uncontrolled_value = clamped;
931 s.last_value = clamped;
932 }
933 });
934 if (clamped - prev_uncontrolled).abs() > 1e-9
935 && let Some(cb) = &cb_move
936 {
937 cb(&clamped, window, cx);
938 }
939 window.refresh();
940 });
941
942 let st_up = int_scrub_drag.clone();
943 window.on_mouse_event(move |_: &MouseUpEvent, phase, window, cx| {
944 if !phase.bubble() {
945 return;
946 }
947 if st_up.read(cx).scrub_pressing {
948 st_up.update(cx, |s, _| {
949 s.scrub_pressing = false;
950 s.scrub_active = false;
951 s.scrub_rubber_x = 0.0;
952 });
953 window.refresh();
954 }
955 });
956 }
957 },
958 )
959 .absolute()
960 .inset_0();
961
962 let shell_w = self
963 .width
964 .unwrap_or_else(|| px(self.size.default_width_px()));
965 let label_font = if self.size == NumberFieldSize::Sm {
966 Typography::TEXT_XS
967 } else {
968 Typography::TEXT_SM
969 };
970
971 let head_row = div()
972 .w(shell_w)
973 .mb(Spacing::S2)
974 .flex()
975 .flex_row()
976 .items_center()
977 .justify_between()
978 .gap(Spacing::S3)
979 .child(
980 div()
981 .id(ElementId::NamedChild(
982 self.id.clone().into(),
983 "label".into(),
984 ))
985 .test_support()
986 .relative()
987 .text_size(label_font)
988 .font_medium()
989 .text_color(colors.foreground)
990 .when(can_scrub, |this| this.cursor_ew_resize())
991 .on_hover(move |hovered, window, cx| {
992 int_lbl_hover.update(cx, |s, _| s.label_hovered = *hovered);
993 window.refresh();
994 })
995 .on_mouse_down(
996 MouseButton::Left,
997 move |event: &MouseDownEvent, window, cx| {
998 if !can_scrub {
999 return;
1000 }
1001 int_lbl_down.update(cx, |s, _| {
1002 s.scrub_pressing = true;
1003 s.scrub_active = false;
1004 s.scrub_start_x = f32::from(event.position.x);
1005 s.scrub_from_value = current;
1006 s.scrub_rubber_x = 0.0;
1007 });
1008 window.refresh();
1009 },
1010 )
1011 .child(scrub_listener)
1012 .child(self.label),
1013 )
1014 .when(limit_op > 0.01, |this| {
1015 this.child(
1016 div()
1017 .mt(px(limit_y))
1018 .opacity(limit_op)
1019 .text_size(Typography::TEXT_XS)
1020 .font_medium()
1021 .text_color(limit_color)
1022 .child(limit_note_text),
1023 )
1024 });
1025
1026 let shell_border = if !disabled && (is_focused || snap.scrub_active) {
1029 colors.foreground
1030 } else if !disabled && (snap.control_hovered || (can_scrub && snap.label_hovered)) {
1031 colors.border_strong
1032 } else {
1033 colors.border
1034 };
1035
1036 let int_ctrl_hover = internal.clone();
1037 let int_focus_click = internal.clone();
1038 let int_key = internal.clone();
1039 let on_change_key = self.on_value_change.clone();
1040 let focus_handle = snap.focus_handle.clone();
1041 let focus_for_center = snap.focus_handle;
1042
1043 let control = div()
1044 .id(ElementId::NamedChild(
1045 self.id.clone().into(),
1046 "control".into(),
1047 ))
1048 .test_support()
1049 .role(Role::SpinButton)
1050 .track_focus(&focus_handle)
1051 .on_hover(move |hovered, window, cx| {
1052 int_ctrl_hover.update(cx, |s, _| s.control_hovered = *hovered);
1053 window.refresh();
1054 })
1055 .on_key_down(move |event: &KeyDownEvent, window, cx| {
1056 if disabled {
1057 return;
1058 }
1059 let t_now = motion_now(cx);
1060 let shift = event.keystroke.modifiers.shift;
1061 let (toward, delta_opt): (i8, Option<f64>) = match event.keystroke.key.as_str() {
1062 "up" | "arrowup" => (1, Some(if shift { large_v } else { step_v })),
1063 "down" | "arrowdown" => (-1, Some(if shift { large_v } else { step_v })),
1064 "pageup" => (1, Some(large_v)),
1065 "pagedown" => (-1, Some(large_v)),
1066 "home" => (-1, Some(current - min_v)),
1067 "end" => (1, Some(max_v - current)),
1068 _ => (0, None),
1069 };
1070 if let Some(amount) = delta_opt {
1071 let steps = (amount / step_v).round().max(1.0) as i64 * (toward as i64);
1072 let next_raw = if event.keystroke.key.as_str() == "home" {
1073 min_v
1074 } else if event.keystroke.key.as_str() == "end" {
1075 max_v
1076 } else {
1077 number_field_step_from(current, min_v, step_v, steps, decimals)
1078 };
1079 let clamped = next_raw.clamp(min_v, max_v);
1080 let hit_limit = (next_raw - clamped).abs() > 1e-9;
1081 int_key.update(cx, |s, _| {
1082 if hit_limit {
1083 let same_window = s.pushed_edge == toward
1084 && (t_now - s.pushed_at_secs) < NUMBER_FIELD_PUSH_WINDOW_SECS;
1085 s.push_count = if same_window { s.push_count + 1 } else { 1 };
1086 s.pushed_edge = toward;
1087 s.pushed_at_secs = t_now;
1088 }
1089 if (clamped - current).abs() > 1e-9 {
1090 s.direction = toward;
1091 s.uncontrolled_value = clamped;
1092 s.last_value = clamped;
1093 }
1094 });
1095 if (clamped - current).abs() > 1e-9
1096 && let Some(cb) = &on_change_key
1097 {
1098 cb(&clamped, window, cx);
1099 }
1100 window.refresh();
1101 }
1102 })
1103 .w(shell_w)
1104 .min_h(self.size.control_height())
1105 .p(px(inset_px))
1106 .flex()
1107 .flex_row()
1108 .items_center()
1109 .gap(px(2.0))
1110 .rounded(Radii::CONTROL)
1111 .border_1()
1112 .border_color(shell_border)
1113 .bg(if disabled {
1114 colors.surface_muted
1115 } else {
1116 colors.surface
1117 })
1118 .opacity(if disabled { 0.5 } else { 1.0 })
1119 .child(minus_btn)
1120 .child(
1121 div()
1122 .id(ElementId::NamedChild(
1123 self.id.clone().into(),
1124 "value-wrap".into(),
1125 ))
1126 .flex_1()
1127 .min_w_0()
1128 .h_full()
1129 .flex()
1130 .items_center()
1131 .justify_center()
1132 .overflow_hidden()
1133 .when(!disabled, |this| this.cursor_pointer())
1134 .on_click(move |_, window, cx| {
1135 if !disabled {
1136 let _ = &int_focus_click;
1137 window.focus(&focus_for_center, cx);
1138 window.refresh();
1139 }
1140 })
1141 .child(
1142 div()
1143 .ml(px(scrub_x))
1144 .mt(px(bump_y))
1145 .flex()
1146 .flex_row()
1147 .items_center()
1148 .children(prefix_els)
1149 .children(number_cols)
1150 .children(suffix_els),
1151 ),
1152 )
1153 .child(plus_btn);
1154
1155 let desc_id = ElementId::NamedChild(self.id.clone().into(), "description".into());
1156
1157 div()
1158 .id(self.id)
1159 .test_support()
1160 .flex()
1161 .flex_col()
1162 .items_start()
1163 .child(head_row)
1164 .child(control)
1165 .child(render_field_message(
1166 desc_id,
1167 self.description,
1168 false,
1169 window,
1170 cx,
1171 ))
1172 }
1173}
1174
1175#[cfg(test)]
1176mod tests {
1177 use super::*;
1178
1179 #[test]
1180 fn number_field_rubber_approaches_10px_asymptote() {
1181 assert!(number_field_rubber(0.0, 10.0).abs() < 1e-5);
1182 let r20 = number_field_rubber(20.0, 10.0);
1183 let r100 = number_field_rubber(100.0, 10.0);
1184 assert!(r20 > 4.0 && r20 < 10.0);
1185 assert!(r100 > r20 && r100 < 10.0);
1186 assert!((number_field_rubber(-20.0, 10.0) + r20).abs() < 1e-5);
1187 }
1188
1189 #[test]
1190 fn number_field_bump_offset_compounds_with_push_count_and_decays() {
1191 let b1 = number_field_bump_offset(0.065, 1, 1, false);
1192 let b4 = number_field_bump_offset(0.065, 1, 4, false);
1193 assert!(b1 < -3.0);
1194 assert!(b4 < b1 * 1.5);
1195 assert!(number_field_bump_offset(0.50, 1, 4, false).abs() < 1e-4);
1196 assert!(number_field_bump_offset(0.065, 1, 4, true).abs() < 1e-4);
1197 }
1198
1199 #[test]
1200 fn number_field_step_from_snaps_off_grid_values_in_travel_direction() {
1201 assert!((number_field_step_from(2.3, 0.0, 1.0, 1, 0) - 3.0).abs() < 1e-6);
1203 assert!((number_field_step_from(2.3, 0.0, 1.0, -1, 0) - 2.0).abs() < 1e-6);
1204 assert!((number_field_step_from(1.25, 0.0, 0.25, 2, 2) - 1.75).abs() < 1e-6);
1206 }
1207}