use std::rc::Rc;
use arc_motion::{
BlurFallback, arc_spring, arc_spring_with_options, arc_transition, is_reduced_motion,
motion_now, spring::SpringOptions,
};
use arc_tokens::{ActiveArcTheme as _, ControlHeights, Radii, Spacing, Typography, oklab_mix};
use gpui_kit::{
App, ElementId, FocusHandle, Hsla, IntoElement, KeyDownEvent, MouseButton, MouseDownEvent,
MouseMoveEvent, MouseUpEvent, ParentElement, PathBuilder, Pixels, RenderOnce, Role,
SharedString, Styled, TestSupportExt as _, Window,
base::{Button as BaseButton, StyledExt as _},
canvas, div, point,
prelude::*,
px,
};
use super::field_message::render_field_message;
use crate::text::animated_counter::{CounterPart, counter_parts, glyph_alpha, wheel_offset};
type NumberFieldChangeHandler = Rc<dyn Fn(&f64, &mut Window, &mut App)>;
type DynamicAffixFn = Rc<dyn Fn(f64) -> SharedString>;
pub const NUMBER_FIELD_SCRUB_PX: f32 = 6.0;
pub const NUMBER_FIELD_RUBBER_LIMIT_PX: f32 = 10.0;
pub const NUMBER_FIELD_LIMIT_HINT_SECS: f64 = 1.5;
pub const NUMBER_FIELD_PUSH_WINDOW_SECS: f64 = 0.7;
pub const NUMBER_FIELD_PUSH_GAIN: f32 = 0.22;
pub const NUMBER_FIELD_PUSH_CAP: u32 = 4;
pub fn number_field_rubber(distance: f32, limit: f32) -> f32 {
if distance.abs() < 1e-5 || limit <= 0.0 {
return 0.0;
}
distance.signum() * (1.0 - 1.0 / (distance.abs() * 0.55 / limit + 1.0)) * limit
}
pub fn number_field_bump_offset(elapsed: f64, edge: i8, push_count: u32, reduced: bool) -> f32 {
if reduced || edge == 0 || !(0.0..0.42).contains(&elapsed) {
return 0.0;
}
let extra =
(push_count.saturating_sub(1).min(NUMBER_FIELD_PUSH_CAP) as f32) * NUMBER_FIELD_PUSH_GAIN;
let amp = 3.6 * (1.0 + extra);
let t = elapsed as f32;
let omega = 15.0_f32;
let env = (omega * t * std::f32::consts::E * (-omega * t).exp()).clamp(0.0, 1.0);
-(edge as f32) * amp * env
}
pub fn number_field_icon_shake_x(elapsed: f64, reduced: bool) -> f32 {
if reduced || !(0.0..0.32).contains(&elapsed) {
return 0.0;
}
let keyframes = [0.0_f32, -2.5, 2.5, -1.5, 1.0, 0.0];
let segments = (keyframes.len() - 1) as f32;
let pos = ((elapsed / 0.32).clamp(0.0, 1.0) as f32) * segments;
let idx = (pos.floor() as usize).min(keyframes.len() - 2);
let frac = pos - idx as f32;
keyframes[idx] + (keyframes[idx + 1] - keyframes[idx]) * frac
}
pub fn number_field_step_from(from: f64, base: f64, step: f64, steps: i64, decimals: usize) -> f64 {
let safe_step = if step > 0.0 { step } else { 1.0 };
let idx = (from - base) / safe_step;
let grid_idx = if steps > 0 {
(idx + 1e-7).floor()
} else if steps < 0 {
(idx - 1e-7).ceil()
} else {
idx.round()
};
let raw = base + (grid_idx + steps as f64) * safe_step;
let scale = 10_f64.powi(decimals as i32);
(raw * scale).round() / scale
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum NumberFieldSize {
Sm,
#[default]
Md,
Lg,
}
impl NumberFieldSize {
pub fn control_height(self) -> Pixels {
match self {
Self::Sm => ControlHeights::SM,
Self::Md => ControlHeights::MD,
Self::Lg => ControlHeights::LG,
}
}
pub const fn step_button_px(self) -> f32 {
match self {
Self::Sm => 24.0,
Self::Md => 28.0,
Self::Lg => 32.0,
}
}
pub const fn inset_px(self) -> f32 {
match self {
Self::Sm | Self::Md => 2.0,
Self::Lg => 3.0,
}
}
pub const fn default_width_px(self) -> f32 {
match self {
Self::Sm => 144.0,
Self::Md => 168.0,
Self::Lg => 196.0,
}
}
pub fn text_size(self) -> Pixels {
match self {
Self::Sm => Typography::TEXT_XS,
Self::Md => Typography::TEXT_SM,
Self::Lg => Typography::TEXT_BASE,
}
}
pub const fn digit_height_px(self) -> f32 {
match self {
Self::Sm => 18.0,
Self::Md => 20.0,
Self::Lg => 22.0,
}
}
pub const fn digit_width_px(self) -> f32 {
match self {
Self::Sm => 8.0,
Self::Md => 9.0,
Self::Lg => 10.0,
}
}
}
#[derive(Clone)]
pub enum NumberFieldAffix {
Static(SharedString),
Dynamic(DynamicAffixFn),
}
impl NumberFieldAffix {
pub fn evaluate(&self, value: f64) -> SharedString {
match self {
Self::Static(s) => s.clone(),
Self::Dynamic(f) => f(value),
}
}
}
impl From<&'static str> for NumberFieldAffix {
fn from(s: &'static str) -> Self {
Self::Static(s.into())
}
}
impl From<SharedString> for NumberFieldAffix {
fn from(s: SharedString) -> Self {
Self::Static(s)
}
}
#[derive(Clone)]
struct NumberFieldInternal {
uncontrolled_value: f64,
last_value: f64,
direction: i8,
pressed_step: i8,
hovered_step: i8,
control_hovered: bool,
label_hovered: bool,
pushed_edge: i8,
pushed_at_secs: f64,
push_count: u32,
scrub_active: bool,
scrub_pressing: bool,
scrub_start_x: f32,
scrub_from_value: f64,
scrub_rubber_x: f32,
focus_handle: FocusHandle,
}
impl NumberFieldInternal {
fn new(initial: f64, now: f64, focus_handle: FocusHandle) -> Self {
Self {
uncontrolled_value: initial,
last_value: initial,
direction: 1,
pressed_step: 0,
hovered_step: 0,
control_hovered: false,
label_hovered: false,
pushed_edge: 0,
pushed_at_secs: now - 10.0,
push_count: 0,
scrub_active: false,
scrub_pressing: false,
scrub_start_x: 0.0,
scrub_from_value: initial,
scrub_rubber_x: 0.0,
focus_handle,
}
}
}
fn paint_plus_or_minus(
cx: f32,
cy: f32,
is_plus: bool,
scale: f32,
color: Hsla,
window: &mut Window,
) {
let half = 4.5 * scale;
let mut builder = PathBuilder::stroke(px(1.75));
builder.move_to(point(px(cx - half), px(cy)));
builder.line_to(point(px(cx + half), px(cy)));
if is_plus {
builder.move_to(point(px(cx), px(cy - half)));
builder.line_to(point(px(cx), px(cy + half)));
}
if let Ok(path) = builder.build() {
window.paint_path(path, color);
}
}
#[derive(IntoElement)]
pub struct NumberField {
id: ElementId,
label: SharedString,
value: Option<f64>,
default_value: f64,
min: f64,
max: f64,
step: f64,
large_step: Option<f64>,
decimals: Option<usize>,
use_grouping: bool,
prefix: Option<NumberFieldAffix>,
suffix: Option<NumberFieldAffix>,
scrub: bool,
size: NumberFieldSize,
limit_hint: bool,
description: Option<SharedString>,
disabled: bool,
width: Option<Pixels>,
on_value_change: Option<NumberFieldChangeHandler>,
}
impl NumberField {
pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
Self {
id: id.into(),
label: label.into(),
value: None,
default_value: 0.0,
min: 0.0,
max: 1_000_000_000.0,
step: 1.0,
large_step: None,
decimals: None,
use_grouping: true,
prefix: None,
suffix: None,
scrub: false,
size: NumberFieldSize::Md,
limit_hint: true,
description: None,
disabled: false,
width: None,
on_value_change: None,
}
}
pub fn value(mut self, value: f64) -> Self {
self.value = Some(value);
self
}
pub fn default_value(mut self, value: f64) -> Self {
self.default_value = value;
self
}
pub fn min(mut self, min: f64) -> Self {
self.min = min;
self
}
pub fn max(mut self, max: f64) -> Self {
self.max = max;
self
}
pub fn step(mut self, step: f64) -> Self {
self.step = if step > 0.0 { step } else { 1.0 };
self
}
pub fn large_step(mut self, large_step: f64) -> Self {
self.large_step = Some(large_step.max(self.step));
self
}
pub fn decimals(mut self, decimals: usize) -> Self {
self.decimals = Some(decimals);
self
}
pub fn use_grouping(mut self, grouping: bool) -> Self {
self.use_grouping = grouping;
self
}
pub fn prefix(mut self, prefix: impl Into<NumberFieldAffix>) -> Self {
self.prefix = Some(prefix.into());
self
}
pub fn prefix_fn(mut self, f: impl Fn(f64) -> SharedString + 'static) -> Self {
self.prefix = Some(NumberFieldAffix::Dynamic(Rc::new(f)));
self
}
pub fn suffix(mut self, suffix: impl Into<NumberFieldAffix>) -> Self {
self.suffix = Some(suffix.into());
self
}
pub fn suffix_fn(mut self, f: impl Fn(f64) -> SharedString + 'static) -> Self {
self.suffix = Some(NumberFieldAffix::Dynamic(Rc::new(f)));
self
}
pub fn scrub(mut self, scrub: bool) -> Self {
self.scrub = scrub;
self
}
pub fn size(mut self, size: NumberFieldSize) -> Self {
self.size = size;
self
}
pub fn limit_hint(mut self, limit_hint: bool) -> Self {
self.limit_hint = limit_hint;
self
}
pub fn description(mut self, description: impl Into<SharedString>) -> Self {
self.description = Some(description.into());
self
}
pub fn disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled;
self
}
pub fn width(mut self, width: impl Into<Pixels>) -> Self {
self.width = Some(width.into());
self
}
pub fn on_value_change(
mut self,
handler: impl Fn(&f64, &mut Window, &mut App) + 'static,
) -> Self {
self.on_value_change = Some(Rc::new(handler));
self
}
}
fn infer_decimals(step: f64) -> usize {
let s = format!("{step}");
s.split('.').nth(1).map(|f| f.len()).unwrap_or(0)
}
impl RenderOnce for NumberField {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let theme = cx.arc_theme().clone();
let colors = theme.colors;
let motion = theme.motion;
let reduced = is_reduced_motion(cx);
let now = motion_now(cx);
let decimals = self.decimals.unwrap_or_else(|| infer_decimals(self.step));
let min_v = self.min;
let max_v = self.max.max(min_v);
let step_v = self.step;
let large_v = self.large_step.unwrap_or(step_v * 10.0);
let initial_val = self.value.unwrap_or(self.default_value).clamp(min_v, max_v);
let state_id =
ElementId::NamedChild(self.id.clone().into(), "__arc-number-field-state".into());
let internal = window.use_keyed_state(state_id, cx, |_, cx| {
NumberFieldInternal::new(initial_val, now, cx.focus_handle())
});
let current = self
.value
.unwrap_or_else(|| internal.read(cx).uncontrolled_value)
.clamp(min_v, max_v);
{
let prev = internal.read(cx).last_value;
if (current - prev).abs() > 1e-9 {
let dir = if current >= prev { 1 } else { -1 };
internal.update(cx, |s, _| {
s.last_value = current;
s.direction = dir;
});
}
}
let snap = internal.read(cx).clone();
let is_focused = snap.focus_handle.is_focused(window);
let at_min = current <= min_v + 1e-9;
let at_max = current >= max_v - 1e-9;
let push_elapsed = (now - snap.pushed_at_secs).max(0.0);
let active_limit_edge = if self.limit_hint && push_elapsed < NUMBER_FIELD_LIMIT_HINT_SECS {
window.request_animation_frame();
snap.pushed_edge
} else {
0
};
let strain_active = push_elapsed < 0.42 && snap.pushed_edge != 0;
if strain_active {
window.request_animation_frame();
}
let bump_y =
number_field_bump_offset(push_elapsed, snap.pushed_edge, snap.push_count, reduced);
let minus_shake_x = if snap.pushed_edge < 0 {
number_field_icon_shake_x(push_elapsed, reduced)
} else {
0.0
};
let plus_shake_x = if snap.pushed_edge > 0 {
number_field_icon_shake_x(push_elapsed, reduced)
} else {
0.0
};
let scrub_x = if snap.scrub_active {
let _ = arc_spring_with_options(
(self.id.clone(), "scrub-x"),
snap.scrub_rubber_x,
SpringOptions::new(motion.spring.snappy).with_initial_value(snap.scrub_rubber_x),
window,
cx,
);
snap.scrub_rubber_x
} else if reduced {
0.0
} else {
arc_spring(
(self.id.clone(), "scrub-x"),
0.0,
motion.spring.snappy,
window,
cx,
)
};
let limit_color = oklab_mix(
colors.warning,
colors.foreground,
if theme.mode.is_dark() { 0.12 } else { 0.28 },
);
let limit_op = arc_transition(
(self.id.clone(), "limit-op"),
if active_limit_edge != 0 { 1.0 } else { 0.0 },
if reduced {
motion.duration.instant
} else if active_limit_edge != 0 {
motion.duration.fast
} else {
motion.duration.standard
},
motion.ease.standard,
window,
cx,
);
let limit_y = if reduced {
0.0
} else {
arc_spring(
(self.id.clone(), "limit-y"),
if active_limit_edge != 0 {
0.0
} else {
(snap.pushed_edge as f32) * 5.4
},
motion.spring.snappy,
window,
cx,
)
};
let prefix_str = self
.prefix
.as_ref()
.map(|p| p.evaluate(current))
.unwrap_or_default();
let suffix_str = self
.suffix
.as_ref()
.map(|s| s.evaluate(current))
.unwrap_or_default();
let limit_val = if snap.pushed_edge >= 0 { max_v } else { min_v };
let limit_prefix = self
.prefix
.as_ref()
.map(|p| p.evaluate(limit_val))
.unwrap_or_default();
let limit_suffix = self
.suffix
.as_ref()
.map(|s| s.evaluate(limit_val))
.unwrap_or_default();
let limit_note_text = SharedString::from(format!(
"{} {limit_prefix}{limit_val:.*}{limit_suffix}",
if snap.pushed_edge >= 0 { "Max" } else { "Min" },
decimals
));
let digit_h = self.size.digit_height_px();
let digit_w = self.size.digit_width_px();
let font_sz = self.size.text_size();
let mut parts = counter_parts(current, decimals);
if !self.use_grouping {
parts.retain(|p| !matches!(p, CounterPart::Text { key, .. } if key.starts_with('g')));
}
let value_text_color = if reduced && strain_active {
limit_color
} else {
colors.foreground
};
let mut number_cols = Vec::with_capacity(parts.len());
for part in parts {
match part {
CounterPart::Text { key, text } => {
number_cols.push(
div()
.id(ElementId::NamedChild(
self.id.clone().into(),
SharedString::from(key),
))
.h(px(digit_h))
.flex()
.items_center()
.text_size(font_sz)
.font_medium()
.text_color(value_text_color)
.child(SharedString::from(text))
.into_any_element(),
);
}
CounterPart::Digit { key, digit, .. } => {
let pos = if reduced {
digit as f32
} else {
arc_spring(
(self.id.clone(), format!("wheel-{key}")),
digit as f32,
motion.spring.snappy,
window,
cx,
)
};
let mut col = div()
.id(ElementId::NamedChild(
self.id.clone().into(),
SharedString::from(key),
))
.relative()
.w(px(digit_w))
.h(px(digit_h))
.overflow_hidden();
for d in 0..=9_u8 {
let off = wheel_offset(d, pos);
let alpha = glyph_alpha(off);
if alpha > 0.01 {
let blur_px = if off.abs() < 0.02 {
0.0
} else {
off.abs() * 3.0
};
let blur = BlurFallback::evaluate(px(blur_px), reduced);
let y_px = off * digit_h * 1.05;
col = col.child(
div()
.absolute()
.left_0()
.right_0()
.top(px(y_px))
.h(px(digit_h))
.flex()
.items_center()
.justify_center()
.text_size(font_sz)
.font_medium()
.text_color(value_text_color)
.opacity((alpha * blur.opacity_multiplier).clamp(0.0, 1.0))
.child(SharedString::from(d.to_string())),
);
}
}
number_cols.push(col.into_any_element());
}
}
}
let render_affix_chars =
|tag: &'static str, text: &str, window: &mut Window, cx: &mut App| {
text.chars()
.enumerate()
.map(|(idx, ch)| {
let ch_str = SharedString::from(ch.to_string());
let slot_key = format!("affix-{tag}-{idx}-{ch}");
let p = arc_transition(
(self.id.clone(), slot_key),
1.0,
if reduced {
motion.duration.instant
} else {
motion.duration.fast
},
motion.ease.enter,
window,
cx,
);
let y = if reduced {
0.0
} else {
(snap.direction as f32) * 3.5 * (1.0 - p)
};
div()
.mt(px(y))
.opacity(p)
.text_size(font_sz)
.text_color(colors.text_secondary)
.child(ch_str)
.into_any_element()
})
.collect::<Vec<_>>()
};
let prefix_els = render_affix_chars("pre", &prefix_str, window, cx);
let suffix_els = render_affix_chars("suf", &suffix_str, window, cx);
let step_px = self.size.step_button_px();
let inset_px = self.size.inset_px();
let step_radius = (Radii::CONTROL - px(inset_px + 1.0)).max(px(4.0));
let disabled = self.disabled;
let make_step_button = |toward: i8, window: &mut Window, cx: &mut App| {
let is_plus = toward > 0;
let at_limit = if is_plus { at_max } else { at_min };
let is_pressed = snap.pressed_step == toward && !disabled;
let is_hovered = snap.hovered_step == toward && !disabled && !at_limit;
let is_strained = strain_active && snap.pushed_edge == toward;
let icon_scale = if reduced {
1.0
} else {
arc_spring(
(
self.id.clone(),
if is_plus { "plus-scale" } else { "minus-scale" },
),
if is_pressed && !at_limit { 0.82 } else { 1.0 },
motion.spring.snappy,
window,
cx,
)
};
let btn_bg = if is_pressed && !at_limit {
oklab_mix(colors.foreground, colors.surface, 0.10)
} else if is_hovered {
colors.surface_muted
} else {
Hsla::transparent_black()
};
let icon_color = if is_strained {
limit_color
} else if is_pressed || is_hovered {
colors.foreground
} else {
colors.text_secondary
};
let btn_opacity = if disabled {
0.35
} else if is_strained {
0.60
} else if at_limit {
0.32
} else {
1.0
};
let shake_x = if is_plus { plus_shake_x } else { minus_shake_x };
let int_hover = internal.clone();
let int_down = internal.clone();
let int_up = internal.clone();
let int_out = internal.clone();
let int_click = internal.clone();
let on_change = self.on_value_change.clone();
let focus_for_step = snap.focus_handle.clone();
let btn_id = ElementId::NamedChild(
self.id.clone().into(),
if is_plus {
"increase".into()
} else {
"decrease".into()
},
);
let aria_lbl = SharedString::from(format!(
"{} {}",
if is_plus { "Increase" } else { "Decrease" },
self.label
));
BaseButton::new(btn_id)
.accessibility_label(aria_lbl)
.disabled(disabled)
.on_click(move |_, window, cx| {
if disabled {
return;
}
window.focus(&focus_for_step, cx);
let t_now = motion_now(cx);
let next_raw =
number_field_step_from(current, min_v, step_v, toward as i64, decimals);
let clamped = next_raw.clamp(min_v, max_v);
let hit_limit = (next_raw - clamped).abs() > 1e-9;
int_click.update(cx, |s, _| {
s.pressed_step = 0;
if hit_limit {
let same_window = s.pushed_edge == toward
&& (t_now - s.pushed_at_secs) < NUMBER_FIELD_PUSH_WINDOW_SECS;
s.push_count = if same_window { s.push_count + 1 } else { 1 };
s.pushed_edge = toward;
s.pushed_at_secs = t_now;
}
if (clamped - current).abs() > 1e-9 {
s.direction = toward;
s.uncontrolled_value = clamped;
s.last_value = clamped;
}
});
if (clamped - current).abs() > 1e-9
&& let Some(cb) = &on_change
{
cb(&clamped, window, cx);
}
window.refresh();
})
.w(px(step_px))
.h(px(step_px))
.flex_none()
.flex()
.items_center()
.justify_center()
.rounded(step_radius)
.bg(btn_bg)
.opacity(btn_opacity)
.when(!disabled && !at_limit, |this| this.cursor_pointer())
.on_hover(move |hovered, window, cx| {
int_hover.update(cx, |s, _| {
if *hovered {
s.hovered_step = toward;
} else if s.hovered_step == toward {
s.hovered_step = 0;
}
});
window.refresh();
})
.on_mouse_down(MouseButton::Left, move |_, window, cx| {
if !disabled {
int_down.update(cx, |s, _| s.pressed_step = toward);
window.refresh();
}
})
.on_mouse_up(MouseButton::Left, move |_, window, cx| {
if int_up.read(cx).pressed_step == toward {
int_up.update(cx, |s, _| s.pressed_step = 0);
window.refresh();
}
})
.on_mouse_up_out(MouseButton::Left, move |_, window, cx| {
if int_out.read(cx).pressed_step == toward {
int_out.update(cx, |s, _| s.pressed_step = 0);
window.refresh();
}
})
.child(
div().ml(px(shake_x)).size(px(16.0)).child(
canvas(
|_, _, _| {},
move |rect, _, window, _| {
let cx_pt = f32::from(rect.origin.x + rect.size.width * 0.5);
let cy_pt = f32::from(rect.origin.y + rect.size.height * 0.5);
paint_plus_or_minus(
cx_pt, cy_pt, is_plus, icon_scale, icon_color, window,
);
},
)
.size_full(),
),
)
};
let minus_btn = make_step_button(-1, window, cx);
let plus_btn = make_step_button(1, window, cx);
let can_scrub = self.scrub && !disabled;
let int_lbl_hover = internal.clone();
let int_lbl_down = internal.clone();
let int_scrub_drag = internal.clone();
let on_change_scrub = self.on_value_change.clone();
let scrub_pressing = snap.scrub_pressing;
let scrub_listener = canvas(
|_, _, _| {},
move |_, _, window, _| {
if scrub_pressing {
let st_move = int_scrub_drag.clone();
let cb_move = on_change_scrub.clone();
window.on_mouse_event(move |event: &MouseMoveEvent, phase, window, cx| {
if !phase.bubble() {
return;
}
let (pressing, start_x, from_val, prev_uncontrolled) = {
let s = st_move.read(cx);
(
s.scrub_pressing,
s.scrub_start_x,
s.scrub_from_value,
s.uncontrolled_value,
)
};
if !pressing {
return;
}
let dx = f32::from(event.position.x) - start_x;
if dx.abs() < 3.0 && !st_move.read(cx).scrub_active {
return;
}
let travel = dx / NUMBER_FIELD_SCRUB_PX;
let steps = travel.trunc() as i64;
let stepped = if steps != 0 {
number_field_step_from(from_val, min_v, step_v, steps, decimals)
} else {
from_val
};
let clamped = stepped.clamp(min_v, max_v);
let raw = from_val + (travel as f64) * step_v;
let over_px = if raw > max_v {
((raw - max_v) / step_v) as f32 * NUMBER_FIELD_SCRUB_PX
} else if raw < min_v {
((raw - min_v) / step_v) as f32 * NUMBER_FIELD_SCRUB_PX
} else {
0.0
};
let rub = if reduced {
0.0
} else {
number_field_rubber(over_px, NUMBER_FIELD_RUBBER_LIMIT_PX)
};
st_move.update(cx, |s, _| {
s.scrub_active = true;
s.scrub_rubber_x = rub;
if (clamped - prev_uncontrolled).abs() > 1e-9 {
s.direction = if clamped >= prev_uncontrolled { 1 } else { -1 };
s.uncontrolled_value = clamped;
s.last_value = clamped;
}
});
if (clamped - prev_uncontrolled).abs() > 1e-9
&& let Some(cb) = &cb_move
{
cb(&clamped, window, cx);
}
window.refresh();
});
let st_up = int_scrub_drag.clone();
window.on_mouse_event(move |_: &MouseUpEvent, phase, window, cx| {
if !phase.bubble() {
return;
}
if st_up.read(cx).scrub_pressing {
st_up.update(cx, |s, _| {
s.scrub_pressing = false;
s.scrub_active = false;
s.scrub_rubber_x = 0.0;
});
window.refresh();
}
});
}
},
)
.absolute()
.inset_0();
let shell_w = self
.width
.unwrap_or_else(|| px(self.size.default_width_px()));
let label_font = if self.size == NumberFieldSize::Sm {
Typography::TEXT_XS
} else {
Typography::TEXT_SM
};
let head_row = div()
.w(shell_w)
.mb(Spacing::S2)
.flex()
.flex_row()
.items_center()
.justify_between()
.gap(Spacing::S3)
.child(
div()
.id(ElementId::NamedChild(
self.id.clone().into(),
"label".into(),
))
.test_support()
.relative()
.text_size(label_font)
.font_medium()
.text_color(colors.foreground)
.when(can_scrub, |this| this.cursor_ew_resize())
.on_hover(move |hovered, window, cx| {
int_lbl_hover.update(cx, |s, _| s.label_hovered = *hovered);
window.refresh();
})
.on_mouse_down(
MouseButton::Left,
move |event: &MouseDownEvent, window, cx| {
if !can_scrub {
return;
}
int_lbl_down.update(cx, |s, _| {
s.scrub_pressing = true;
s.scrub_active = false;
s.scrub_start_x = f32::from(event.position.x);
s.scrub_from_value = current;
s.scrub_rubber_x = 0.0;
});
window.refresh();
},
)
.child(scrub_listener)
.child(self.label),
)
.when(limit_op > 0.01, |this| {
this.child(
div()
.mt(px(limit_y))
.opacity(limit_op)
.text_size(Typography::TEXT_XS)
.font_medium()
.text_color(limit_color)
.child(limit_note_text),
)
});
let shell_border = if !disabled && (is_focused || snap.scrub_active) {
colors.foreground
} else if !disabled && (snap.control_hovered || (can_scrub && snap.label_hovered)) {
colors.border_strong
} else {
colors.border
};
let int_ctrl_hover = internal.clone();
let int_focus_click = internal.clone();
let int_key = internal.clone();
let on_change_key = self.on_value_change.clone();
let focus_handle = snap.focus_handle.clone();
let focus_for_center = snap.focus_handle;
let control = div()
.id(ElementId::NamedChild(
self.id.clone().into(),
"control".into(),
))
.test_support()
.role(Role::SpinButton)
.track_focus(&focus_handle)
.on_hover(move |hovered, window, cx| {
int_ctrl_hover.update(cx, |s, _| s.control_hovered = *hovered);
window.refresh();
})
.on_key_down(move |event: &KeyDownEvent, window, cx| {
if disabled {
return;
}
let t_now = motion_now(cx);
let shift = event.keystroke.modifiers.shift;
let (toward, delta_opt): (i8, Option<f64>) = match event.keystroke.key.as_str() {
"up" | "arrowup" => (1, Some(if shift { large_v } else { step_v })),
"down" | "arrowdown" => (-1, Some(if shift { large_v } else { step_v })),
"pageup" => (1, Some(large_v)),
"pagedown" => (-1, Some(large_v)),
"home" => (-1, Some(current - min_v)),
"end" => (1, Some(max_v - current)),
_ => (0, None),
};
if let Some(amount) = delta_opt {
let steps = (amount / step_v).round().max(1.0) as i64 * (toward as i64);
let next_raw = if event.keystroke.key.as_str() == "home" {
min_v
} else if event.keystroke.key.as_str() == "end" {
max_v
} else {
number_field_step_from(current, min_v, step_v, steps, decimals)
};
let clamped = next_raw.clamp(min_v, max_v);
let hit_limit = (next_raw - clamped).abs() > 1e-9;
int_key.update(cx, |s, _| {
if hit_limit {
let same_window = s.pushed_edge == toward
&& (t_now - s.pushed_at_secs) < NUMBER_FIELD_PUSH_WINDOW_SECS;
s.push_count = if same_window { s.push_count + 1 } else { 1 };
s.pushed_edge = toward;
s.pushed_at_secs = t_now;
}
if (clamped - current).abs() > 1e-9 {
s.direction = toward;
s.uncontrolled_value = clamped;
s.last_value = clamped;
}
});
if (clamped - current).abs() > 1e-9
&& let Some(cb) = &on_change_key
{
cb(&clamped, window, cx);
}
window.refresh();
}
})
.w(shell_w)
.min_h(self.size.control_height())
.p(px(inset_px))
.flex()
.flex_row()
.items_center()
.gap(px(2.0))
.rounded(Radii::CONTROL)
.border_1()
.border_color(shell_border)
.bg(if disabled {
colors.surface_muted
} else {
colors.surface
})
.opacity(if disabled { 0.5 } else { 1.0 })
.child(minus_btn)
.child(
div()
.id(ElementId::NamedChild(
self.id.clone().into(),
"value-wrap".into(),
))
.flex_1()
.min_w_0()
.h_full()
.flex()
.items_center()
.justify_center()
.overflow_hidden()
.when(!disabled, |this| this.cursor_pointer())
.on_click(move |_, window, cx| {
if !disabled {
let _ = &int_focus_click;
window.focus(&focus_for_center, cx);
window.refresh();
}
})
.child(
div()
.ml(px(scrub_x))
.mt(px(bump_y))
.flex()
.flex_row()
.items_center()
.children(prefix_els)
.children(number_cols)
.children(suffix_els),
),
)
.child(plus_btn);
let desc_id = ElementId::NamedChild(self.id.clone().into(), "description".into());
div()
.id(self.id)
.test_support()
.flex()
.flex_col()
.items_start()
.child(head_row)
.child(control)
.child(render_field_message(
desc_id,
self.description,
false,
window,
cx,
))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn number_field_rubber_approaches_10px_asymptote() {
assert!(number_field_rubber(0.0, 10.0).abs() < 1e-5);
let r20 = number_field_rubber(20.0, 10.0);
let r100 = number_field_rubber(100.0, 10.0);
assert!(r20 > 4.0 && r20 < 10.0);
assert!(r100 > r20 && r100 < 10.0);
assert!((number_field_rubber(-20.0, 10.0) + r20).abs() < 1e-5);
}
#[test]
fn number_field_bump_offset_compounds_with_push_count_and_decays() {
let b1 = number_field_bump_offset(0.065, 1, 1, false);
let b4 = number_field_bump_offset(0.065, 1, 4, false);
assert!(b1 < -3.0);
assert!(b4 < b1 * 1.5);
assert!(number_field_bump_offset(0.50, 1, 4, false).abs() < 1e-4);
assert!(number_field_bump_offset(0.065, 1, 4, true).abs() < 1e-4);
}
#[test]
fn number_field_step_from_snaps_off_grid_values_in_travel_direction() {
assert!((number_field_step_from(2.3, 0.0, 1.0, 1, 0) - 3.0).abs() < 1e-6);
assert!((number_field_step_from(2.3, 0.0, 1.0, -1, 0) - 2.0).abs() < 1e-6);
assert!((number_field_step_from(1.25, 0.0, 0.25, 2, 2) - 1.75).abs() < 1e-6);
}
}