use super::parts::{self, rem};
use crate::{
components::form,
density,
icons::{CarbonIcon, Icon},
theme::{LayerLevel, color},
tokens::ColorRole,
};
use gpui_kit::{
App, AppContext as _, Context, CursorStyle, ElementId, Entity, FocusHandle, Focusable as _,
Hsla, InteractiveElement, IntoElement, MouseButton, ParentElement, Rems, RenderOnce,
SharedString, StatefulInteractiveElement as _, Styled, Subscription, Window,
component::input::{InputEvent, InputState, MoveDown, MoveUp},
div,
prelude::FluentBuilder as _,
px,
};
use std::rc::Rc;
pub fn step_decimals(step: f64) -> usize {
let s = format_number(step);
s.split_once('.').map_or(0, |(_, frac)| frac.len())
}
pub fn clamp(n: f64, min: f64, max: f64, step: f64) -> f64 {
let v = n.max(min).min(max);
let dec = step_decimals(step) as i32;
let f = 10f64.powi(dec);
(v * f).round() / f
}
pub fn format_number(v: f64) -> String {
if v == v.trunc() && v.abs() < 1e15 {
format!("{}", v as i64)
} else {
format!("{v}")
}
}
pub fn parse_float(text: &str) -> Option<f64> {
let t = text.trim_start();
let bytes = t.as_bytes();
let mut end = 0;
let mut seen_dot = false;
let mut best = None;
if end < bytes.len() && (bytes[end] == b'-' || bytes[end] == b'+') {
end += 1;
}
while end < bytes.len() {
match bytes[end] {
b'0'..=b'9' => {
end += 1;
best = Some(end);
}
b'.' if !seen_dot => {
seen_dot = true;
end += 1;
}
_ => break,
}
}
best.and_then(|e| t[..e].parse().ok())
}
pub fn stepped(base: f64, dir: f64, min: f64, max: f64, step: f64) -> f64 {
clamp(base + dir * step, min, max, step)
}
pub fn box_look(focused: bool, invalid: bool, disabled: bool) -> (Hsla, Hsla, Hsla) {
box_look_on(LayerLevel::One, focused, invalid, disabled)
}
pub fn box_look_on(
level: LayerLevel,
focused: bool,
invalid: bool,
disabled: bool,
) -> (Hsla, Hsla, Hsla) {
let clear = Hsla::transparent_black();
let fill = color(level.field());
let rule = if disabled {
clear
} else {
color(level.border_strong())
};
let outline = if invalid {
color(ColorRole::SupportError)
} else if focused {
color(ColorRole::Focus)
} else {
clear
};
(fill, rule, outline)
}
pub fn readonly_box_look(focused: bool) -> (Hsla, Hsla, Hsla) {
readonly_box_look_on(LayerLevel::One, focused)
}
pub fn readonly_box_look_on(level: LayerLevel, focused: bool) -> (Hsla, Hsla, Hsla) {
let clear = Hsla::transparent_black();
let outline = if focused {
color(ColorRole::Focus)
} else {
clear
};
(clear, color(level.border_subtle()), outline)
}
pub const INPUT_WIDTH_PX: f32 = 5. * 0.6 * 14. + 20.;
type ValueHandler = Rc<dyn Fn(f64, &mut Window, &mut App)>;
struct Model {
value: f64,
input: Entity<InputState>,
editing: bool,
min: f64,
max: f64,
step: f64,
controlled: bool,
on_change: Option<ValueHandler>,
anchor: FocusHandle,
_subscription: Subscription,
}
impl Model {
fn set(&mut self, v: f64, window: &mut Window, cx: &mut Context<Self>) {
if !self.controlled {
self.value = v;
}
self.editing = false;
let text = format_number(if self.controlled { v } else { self.value });
self.input.update(cx, |s, cx| s.set_value(text, window, cx));
if let Some(f) = self.on_change.clone() {
f(v, window, cx);
}
cx.notify();
}
fn base(&self, cx: &App) -> f64 {
if self.editing {
parse_float(&self.input.read(cx).value()).unwrap_or(self.value)
} else {
self.value
}
}
fn commit(&mut self, window: &mut Window, cx: &mut Context<Self>) {
if !self.editing {
return;
}
match parse_float(&self.input.read(cx).value()) {
Some(n) => self.set(clamp(n, self.min, self.max, self.step), window, cx),
None => {
self.editing = false;
let text = format_number(self.value);
self.input.update(cx, |s, cx| s.set_value(text, window, cx));
cx.notify();
}
}
}
}
#[derive(IntoElement)]
pub struct Stepper {
id: ElementId,
label: Option<SharedString>,
value: Option<f64>,
default_value: f64,
min: f64,
max: f64,
step: f64,
unit: Option<SharedString>,
disabled: bool,
readonly: bool,
invalid: bool,
invalid_text: Option<SharedString>,
helper_text: Option<SharedString>,
width: Rems,
level: LayerLevel,
decrease_label: SharedString,
increase_label: SharedString,
on_value_change: Option<ValueHandler>,
}
impl Stepper {
pub fn new(id: impl Into<ElementId>) -> Self {
Self {
id: id.into(),
label: None,
value: None,
default_value: 0.,
min: f64::NEG_INFINITY,
max: f64::INFINITY,
step: 1.,
unit: None,
disabled: false,
readonly: false,
invalid: false,
invalid_text: None,
helper_text: None,
width: gpui_kit::rems(7.),
level: LayerLevel::One,
decrease_label: "Decrease".into(),
increase_label: "Increase".into(),
on_value_change: None,
}
}
pub fn level(mut self, level: LayerLevel) -> Self {
self.level = level;
self
}
pub fn label(mut self, label: impl Into<SharedString>) -> Self {
self.label = Some(label.into());
self
}
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 = step;
self
}
pub fn unit(mut self, unit: impl Into<SharedString>) -> Self {
self.unit = Some(unit.into());
self
}
pub fn disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled;
self
}
pub fn readonly(mut self, readonly: bool) -> Self {
self.readonly = readonly;
self
}
pub fn invalid(mut self, invalid: bool) -> Self {
self.invalid = invalid;
self
}
pub fn invalid_text(mut self, text: impl Into<SharedString>) -> Self {
self.invalid_text = Some(text.into());
self
}
pub fn helper_text(mut self, text: impl Into<SharedString>) -> Self {
self.helper_text = Some(text.into());
self
}
pub fn width(mut self, width: Rems) -> Self {
self.width = width;
self
}
pub fn button_labels(
mut self,
decrease: impl Into<SharedString>,
increase: impl Into<SharedString>,
) -> Self {
self.decrease_label = decrease.into();
self.increase_label = increase.into();
self
}
pub fn on_value_change(mut self, f: impl Fn(f64, &mut Window, &mut App) + 'static) -> Self {
self.on_value_change = Some(Rc::new(f));
self
}
}
impl RenderOnce for Stepper {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let id = self.id.clone();
let initial = self.value.unwrap_or(self.default_value);
let model = window.use_keyed_state((id.clone(), "stepper"), cx, |window, cx| {
let input =
cx.new(|cx| InputState::new(window, cx).default_value(format_number(initial)));
let subscription =
cx.subscribe_in(&input, window, |this: &mut Model, _, e, window, cx| {
match e {
InputEvent::Change => {
this.editing = true;
cx.notify();
}
InputEvent::Blur => this.commit(window, cx),
InputEvent::PressEnter { .. } => {
this.commit(window, cx);
this.anchor.focus(window, cx);
}
InputEvent::Focus => {}
}
});
Model {
value: initial,
input,
editing: false,
min: f64::NEG_INFINITY,
max: f64::INFINITY,
step: 1.,
controlled: false,
on_change: None,
anchor: cx.focus_handle(),
_subscription: subscription,
}
});
model.update(cx, |m, cx| {
m.min = self.min;
m.max = self.max;
m.step = self.step;
m.on_change = self.on_value_change.clone();
m.controlled = self.value.is_some();
if let Some(v) = self.value
&& (v != m.value)
{
m.value = v;
if !m.editing {
let text = format_number(v);
m.input.update(cx, |s, cx| s.set_value(text, window, cx));
}
}
});
let (value, input, anchor) = {
let m = model.read(cx);
(m.value, m.input.clone(), m.anchor.clone())
};
let focused = input.read(cx).focus_handle(cx).is_focused(window);
let level = self.level;
let (fill, rule, outline) = if self.readonly && !self.disabled {
readonly_box_look_on(level, focused)
} else {
box_look_on(level, focused, self.invalid, self.disabled)
};
let readonly = self.readonly;
let field_h = density::current().field().px_value();
let mut button =
|key: &'static str, icon: CarbonIcon, label: SharedString, dir: f64, at_bound: bool| {
let model = model.clone();
let inert = readonly && !self.disabled;
let disabled = self.disabled || at_bound || inert;
let hovered = window.use_keyed_state(
(ElementId::from((id.clone(), key)), "hover"),
cx,
|_, _| false,
);
let is_hovered = *hovered.read(cx) && !disabled;
gpui_kit::base::Button::new((id.clone(), key))
.tab_stop(false)
.disabled(disabled)
.accessibility_label(label)
.flex()
.flex_shrink(1.)
.min_w_0()
.items_center()
.justify_center()
.w(rem(field_h))
.h(rem(field_h))
.border_l(px(1.))
.border_color(color(level.border_subtle()))
.when(is_hovered, |b| b.bg(color(level.field_hover())))
.cursor(if inert {
CursorStyle::Arrow
} else if disabled {
CursorStyle::OperationNotAllowed
} else {
CursorStyle::PointingHand
})
.on_hover(move |h, _, cx| {
hovered.update(cx, |v, cx| {
if *v != *h {
*v = *h;
cx.notify();
}
})
})
.child(
Icon::carbon(icon)
.size_length(px(14.))
.color(color(if disabled {
ColorRole::IconDisabled
} else {
ColorRole::IconPrimary
})),
)
.on_click(move |_, window, cx| {
model.update(cx, |m, cx| {
let v = stepped(m.value, dir, m.min, m.max, m.step);
m.set(v, window, cx);
})
})
};
let dec = button(
"dec",
CarbonIcon::Subtract,
self.decrease_label.clone(),
-1.,
value <= self.min,
);
let inc = button(
"inc",
CarbonIcon::Add,
self.increase_label.clone(),
1.,
value >= self.max,
);
let key = |dir: f64| {
let model = model.clone();
move |window: &mut Window, cx: &mut App| {
model.update(cx, |m, cx| {
let v = stepped(m.base(cx), dir, m.min, m.max, m.step);
m.set(v, window, cx);
})
}
};
let up = key(1.);
let down = key(-1.);
let body = div()
.id((id.clone(), "box"))
.relative()
.flex()
.items_center()
.w(self.width)
.min_h(rem(field_h))
.bg(fill)
.when(self.disabled, |d| d.opacity(0.5))
.when(!self.disabled, |this| {
this.when(!readonly, |this| {
this.capture_action(move |_: &MoveUp, window, cx| {
up(window, cx);
cx.stop_propagation();
})
.capture_action(move |_: &MoveDown, window, cx| {
down(window, cx);
cx.stop_propagation();
})
})
.on_mouse_down(MouseButton::Left, {
let focus = input.read(cx).focus_handle(cx);
move |_, window, cx| focus.focus(window, cx)
})
})
.child(
div()
.flex()
.flex_none()
.w(rem(INPUT_WIDTH_PX))
.h(rem(field_h))
.pl(rem(12.))
.pr(rem(6.))
.items_center()
.cursor(if self.disabled {
CursorStyle::OperationNotAllowed
} else {
CursorStyle::IBeam
})
.child(
parts::editor(&input)
.disabled(self.disabled)
.readonly(self.readonly)
.when_some(self.label.clone(), |e, l| e.aria_label(l))
.text_right()
.text_color(color(ColorRole::TextPrimary)),
),
)
.child(parts::nav_anchor(
(id.clone(), "anchor"),
&anchor,
Some(input.read(cx).focus_handle(cx)),
cx,
))
.when_some(self.unit.clone(), |this, unit| {
this.child(
div()
.flex_none()
.pr(rem(8.))
.text_size(rem(12.))
.text_color(color(ColorRole::TextSecondary))
.child(unit),
)
})
.child(dec)
.child(inc)
.child(form::bottom_rule(rule))
.child(form::inset_outline(2., outline));
let message = if self.invalid && self.invalid_text.is_some() {
self.invalid_text.clone().map(parts::error)
} else {
self.helper_text.clone().map(parts::helper)
};
parts::field()
.when_some(self.label.clone(), |f, l| f.child(parts::label(l)))
.child(body)
.children(message)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{CarbonTheme, theme::color_in};
#[test]
fn clamp_rounds_to_the_step_decimals() {
assert_eq!(step_decimals(1.), 0);
assert_eq!(step_decimals(0.25), 2);
assert_eq!(clamp(12., f64::NEG_INFINITY, 10., 1.), 10.);
assert_eq!(clamp(0.1 + 0.2, 0., 1., 0.1), 0.3);
assert_eq!(clamp(-3., 1., 8., 1.), 1.);
assert_eq!(stepped(30., -1., 5., f64::INFINITY, 5.), 25.);
assert_eq!(stepped(5., -1., 5., f64::INFINITY, 5.), 5.);
}
#[test]
fn parse_float_matches_js() {
assert_eq!(parse_float("42"), Some(42.));
assert_eq!(parse_float(" 3.5kg"), Some(3.5));
assert_eq!(parse_float("-2"), Some(-2.));
assert_eq!(parse_float(".5"), Some(0.5));
assert_eq!(parse_float("abc"), None);
assert_eq!(parse_float(""), None);
assert_eq!(parse_float("-"), None);
assert_eq!(format_number(3.), "3");
assert_eq!(format_number(0.5), "0.5");
}
#[test]
fn input_is_five_ch_plus_twenty() {
assert_eq!(INPUT_WIDTH_PX, 62.);
}
#[test]
fn box_states_follow_g_stepper() {
crate::theme::tests_set(CarbonTheme::G10);
let c = |r| color_in(CarbonTheme::G10, r);
let (fill, rule, outline) = box_look(false, false, false);
assert_eq!(fill, c(ColorRole::Field01));
assert_eq!(rule, c(ColorRole::BorderStrong01));
assert_eq!(outline, Hsla::transparent_black());
assert_eq!(box_look(true, false, false).2, c(ColorRole::Focus));
assert_eq!(box_look(true, true, false).2, c(ColorRole::SupportError));
assert_eq!(box_look(false, false, true).1, Hsla::transparent_black());
let (fill, rule, outline) = readonly_box_look(false);
assert_eq!(fill, Hsla::transparent_black());
assert_eq!(rule, c(ColorRole::BorderSubtle01));
assert_eq!(outline, Hsla::transparent_black());
assert_eq!(readonly_box_look(true).2, c(ColorRole::Focus));
let (fill2, rule2, _) = box_look_on(LayerLevel::Two, false, false, false);
assert_eq!(fill2, c(ColorRole::Field02));
assert_eq!(rule2, c(ColorRole::BorderStrong02));
assert_eq!(
readonly_box_look_on(LayerLevel::Two, false).1,
c(ColorRole::BorderSubtle02)
);
}
}