use std::{cell::RefCell, rc::Rc, time::Duration};
use arc_motion::{
ArcPresence, ArcPresenceConfig, BlurFallback, CubicBezier, SpringSolver, arc_spring,
arc_spring_with_options, arc_transition, is_reduced_motion, motion_now, spring::SpringOptions,
};
use arc_tokens::{ActiveArcTheme as _, Radii, Shadows, Spacing, SpringSpec, Typography, oklab_mix};
use gpui_kit::{
App, Bounds, ElementId, FocusHandle, Hsla, IntoElement, KeyDownEvent, MouseButton,
MouseDownEvent, ParentElement, PathBuilder, Pixels, RenderOnce, Role, SharedString, Styled,
TestSupportExt as _, Window,
base::{Button as BaseButton, StyledExt as _},
canvas, deferred, div, point,
prelude::*,
px,
};
use super::field_message::render_field_message;
type MoneyValueChangeHandler = Rc<dyn Fn(&MoneyValueEvent, &mut Window, &mut App)>;
type MoneyCurrencyChangeHandler = Rc<dyn Fn(&SharedString, &mut Window, &mut App)>;
pub const MONEY_MAX_INTEGER_DIGITS: usize = 12;
pub const MONEY_LIMIT_FLASH_SECS: f64 = 1.4;
pub const MONEY_KICK_SETTLE_SECS: f64 = 1.2;
pub const fn money_glide_spring() -> SpringSpec {
SpringSpec::visual(0.28, 0.0)
}
pub const fn money_kick_spring() -> SpringSpec {
SpringSpec::visual(0.42, 0.0)
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct MoneyCurrencyInfo {
pub code: SharedString,
pub symbol: SharedString,
pub symbol_is_prefix: bool,
pub digits: usize,
pub name: SharedString,
}
pub fn money_currency_info(code: &str) -> MoneyCurrencyInfo {
let upper = code.trim().to_uppercase();
match upper.as_str() {
"USD" => MoneyCurrencyInfo {
code: "USD".into(),
symbol: "$".into(),
symbol_is_prefix: true,
digits: 2,
name: "US Dollar".into(),
},
"EUR" => MoneyCurrencyInfo {
code: "EUR".into(),
symbol: "€".into(),
symbol_is_prefix: true,
digits: 2,
name: "Euro".into(),
},
"GBP" => MoneyCurrencyInfo {
code: "GBP".into(),
symbol: "£".into(),
symbol_is_prefix: true,
digits: 2,
name: "British Pound".into(),
},
"JPY" => MoneyCurrencyInfo {
code: "JPY".into(),
symbol: "¥".into(),
symbol_is_prefix: true,
digits: 0,
name: "Japanese Yen".into(),
},
"CNY" | "RMB" => MoneyCurrencyInfo {
code: "CNY".into(),
symbol: "¥".into(),
symbol_is_prefix: true,
digits: 2,
name: "Chinese Yuan".into(),
},
"CAD" => MoneyCurrencyInfo {
code: "CAD".into(),
symbol: "CA$".into(),
symbol_is_prefix: true,
digits: 2,
name: "Canadian Dollar".into(),
},
"AUD" => MoneyCurrencyInfo {
code: "AUD".into(),
symbol: "A$".into(),
symbol_is_prefix: true,
digits: 2,
name: "Australian Dollar".into(),
},
"CHF" => MoneyCurrencyInfo {
code: "CHF".into(),
symbol: "CHF".into(),
symbol_is_prefix: false,
digits: 2,
name: "Swiss Franc".into(),
},
"INR" => MoneyCurrencyInfo {
code: "INR".into(),
symbol: "₹".into(),
symbol_is_prefix: true,
digits: 2,
name: "Indian Rupee".into(),
},
"HKD" => MoneyCurrencyInfo {
code: "HKD".into(),
symbol: "HK$".into(),
symbol_is_prefix: true,
digits: 2,
name: "Hong Kong Dollar".into(),
},
"SGD" => MoneyCurrencyInfo {
code: "SGD".into(),
symbol: "S$".into(),
symbol_is_prefix: true,
digits: 2,
name: "Singapore Dollar".into(),
},
"KRW" => MoneyCurrencyInfo {
code: "KRW".into(),
symbol: "₩".into(),
symbol_is_prefix: true,
digits: 0,
name: "South Korean Won".into(),
},
"SEK" => MoneyCurrencyInfo {
code: "SEK".into(),
symbol: "kr".into(),
symbol_is_prefix: false,
digits: 2,
name: "Swedish Krona".into(),
},
"NZD" => MoneyCurrencyInfo {
code: "NZD".into(),
symbol: "NZ$".into(),
symbol_is_prefix: true,
digits: 2,
name: "New Zealand Dollar".into(),
},
"MXN" => MoneyCurrencyInfo {
code: "MXN".into(),
symbol: "MX$".into(),
symbol_is_prefix: true,
digits: 2,
name: "Mexican Peso".into(),
},
"BRL" => MoneyCurrencyInfo {
code: "BRL".into(),
symbol: "R$".into(),
symbol_is_prefix: true,
digits: 2,
name: "Brazilian Real".into(),
},
_ => MoneyCurrencyInfo {
code: SharedString::from(upper.clone()),
symbol: SharedString::from(upper.clone()),
symbol_is_prefix: true,
digits: 2,
name: SharedString::from(upper),
},
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct MoneyInputDetails {
pub currency: SharedString,
pub major: Option<f64>,
pub formatted: SharedString,
}
#[derive(Clone, Debug, PartialEq)]
pub struct MoneyValueEvent {
pub minor: Option<i64>,
pub details: MoneyInputDetails,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct MoneyPart {
pub key: SharedString,
pub ch: char,
pub ghost: bool,
}
const fn pow10_i64(digits: usize) -> i64 {
10_i64.pow(digits as u32)
}
pub fn money_draft_to_minor(draft: &str, digits: usize) -> Option<i64> {
let trimmed = draft.trim();
if trimmed.is_empty() {
return None;
}
let (whole_str, frac_str) = match trimmed.split_once('.') {
Some((w, f)) => (w, f),
None => (trimmed, ""),
};
let whole: i64 = if whole_str.is_empty() {
0
} else {
whole_str.parse().ok()?
};
let frac: i64 = if digits == 0 {
0
} else {
let mut padded = frac_str.chars().take(digits).collect::<String>();
while padded.len() < digits {
padded.push('0');
}
padded.parse().ok()?
};
Some(whole.saturating_mul(pow10_i64(digits)).saturating_add(frac))
}
pub fn money_minor_to_draft(minor: Option<i64>, digits: usize) -> String {
let Some(m) = minor else {
return String::new();
};
let abs_m = m.unsigned_abs();
let scale = 10_u64.pow(digits as u32);
if digits == 0 {
format!("{abs_m}")
} else {
let whole = abs_m / scale;
let frac = abs_m % scale;
format!("{whole}.{frac:0>width$}", width = digits)
}
}
pub fn money_convert_draft(draft: &str, next_digits: usize) -> String {
if draft.is_empty() {
return String::new();
}
let (whole, frac_opt) = match draft.split_once('.') {
Some((w, f)) => (w, Some(f)),
None => (draft, None),
};
if next_digits == 0 {
if whole.is_empty() {
"0".to_string()
} else {
whole.to_string()
}
} else {
match frac_opt {
Some(f) => {
let clipped: String = f.chars().take(next_digits).collect();
let w = if whole.is_empty() { "0" } else { whole };
format!("{w}.{clipped}")
}
None => whole.to_string(),
}
}
}
pub fn format_money_minor(minor: i64, info: &MoneyCurrencyInfo) -> String {
let draft = money_minor_to_draft(Some(minor), info.digits);
let (whole, frac_opt) = match draft.split_once('.') {
Some((w, f)) => (w, Some(f)),
None => (draft.as_str(), None),
};
let grouped_whole = group_ascii_digits(whole);
let num_str = match frac_opt {
Some(f) => format!("{grouped_whole}.{f}"),
None => grouped_whole,
};
if info.symbol_is_prefix {
format!("{}{num_str}", info.symbol)
} else {
format!("{num_str} {}", info.symbol)
}
}
pub fn format_money_whole_major(major: i64, info: &MoneyCurrencyInfo) -> String {
let grouped = group_ascii_digits(&major.to_string());
if info.symbol_is_prefix {
format!("{}{grouped}", info.symbol)
} else {
format!("{grouped} {}", info.symbol)
}
}
fn group_ascii_digits(whole: &str) -> String {
let chars: Vec<char> = whole.chars().collect();
let len = chars.len();
let mut out = String::with_capacity(len + len / 3);
for (idx, &ch) in chars.iter().enumerate() {
out.push(ch);
let rem = len - 1 - idx;
if rem > 0 && rem.is_multiple_of(3) {
out.push(',');
}
}
out
}
pub fn money_parts_of(draft: &str, digits: usize) -> Vec<MoneyPart> {
let (whole, frac_opt) = if draft.is_empty() {
("", None)
} else {
match draft.split_once('.') {
Some((w, f)) => (w, Some(f)),
None => (draft, None),
}
};
let int_digits = if whole.is_empty() { "0" } else { whole };
let ghost_int = whole.is_empty();
let int_chars: Vec<char> = int_digits.chars().collect();
let int_len = int_chars.len();
let mut parts = Vec::with_capacity(int_len + digits + 4);
for (idx, &ch) in int_chars.iter().enumerate() {
let place = int_len - 1 - idx;
parts.push(MoneyPart {
key: SharedString::from(format!("i{place}")),
ch,
ghost: ghost_int,
});
if place > 0 && place.is_multiple_of(3) {
parts.push(MoneyPart {
key: SharedString::from(format!("g{place}")),
ch: ',',
ghost: ghost_int,
});
}
}
if digits > 0 {
parts.push(MoneyPart {
key: "d".into(),
ch: '.',
ghost: frac_opt.is_none(),
});
let frac_chars: Vec<char> = frac_opt.unwrap_or("").chars().collect();
for idx in 0..digits {
let ch = frac_chars.get(idx).copied().unwrap_or('0');
let is_ghost = frac_opt.is_none() || idx >= frac_chars.len();
parts.push(MoneyPart {
key: SharedString::from(format!("f{idx}")),
ch,
ghost: is_ghost,
});
}
}
parts
}
pub fn sanitize_money_draft(raw: &str, digits: usize) -> Option<String> {
let mut cleaned = String::new();
let mut seen_dot = false;
for ch in raw.chars() {
if ch.is_ascii_digit() {
cleaned.push(ch);
} else if ch == '.' && digits > 0 && !seen_dot {
cleaned.push('.');
seen_dot = true;
}
}
if cleaned.is_empty() {
return Some(String::new());
}
let (raw_whole, frac_opt) = match cleaned.split_once('.') {
Some((w, f)) => (w, Some(f)),
None => (cleaned.as_str(), None),
};
let had_leading_zero = !raw_whole.is_empty();
let mut whole = raw_whole.trim_start_matches('0').to_string();
if whole.is_empty() && (frac_opt.is_some() || had_leading_zero) {
whole.push('0');
}
if whole.len() > MONEY_MAX_INTEGER_DIGITS {
return None;
}
if let Some(f) = frac_opt {
if f.len() > digits {
return None;
}
Some(format!("{whole}.{f}"))
} else {
Some(whole)
}
}
pub fn money_parse_pasted(text: &str, digits: usize) -> Option<String> {
let trimmed = text.trim();
if trimmed.is_empty() {
return None;
}
let chars: Vec<char> = trimmed.chars().collect();
if !chars.iter().any(|&c| c.is_ascii_digit()) {
return None;
}
let mut decimal_at: Option<(usize, usize)> = None;
for (idx, &ch) in chars.iter().enumerate() {
if ch == '.' || ch == ',' {
let mut end = idx + 1;
let mut count = 0;
while end < chars.len() && chars[end].is_ascii_digit() && count < 2 {
end += 1;
count += 1;
}
if count >= 1 && chars[end..].iter().all(|&c| !c.is_ascii_digit()) {
decimal_at = Some((idx, count));
break;
}
}
}
let (whole, fraction) = match decimal_at {
Some((sep, count)) => (
chars[..sep]
.iter()
.filter(|&c| c.is_ascii_digit())
.collect::<String>(),
Some(chars[sep + 1..sep + 1 + count].iter().collect::<String>()),
),
None => (
chars
.iter()
.filter(|&c| c.is_ascii_digit())
.collect::<String>(),
None,
),
};
Some(match (digits, fraction) {
(0, _) => whole,
(_, Some(f)) => format!("{whole}.{f}"),
(_, None) => whole,
})
}
pub fn money_bump_x_offset(elapsed: f64, direction: i8, reduced: bool) -> f32 {
if reduced || direction == 0 || !(0.0..MONEY_KICK_SETTLE_SECS).contains(&elapsed) {
return 0.0;
}
let solver = SpringSolver::new(
money_kick_spring().as_physical(),
0.0,
0.0,
f64::from(direction) * 160.0,
);
solver.sample(elapsed).value
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum MoneyChangeSource {
Type,
Chip,
Key,
External,
}
#[derive(Clone)]
struct MoneyInputInternal {
uncontrolled_currency: SharedString,
previous_symbol: Option<SharedString>,
symbol_changed_at_secs: f64,
draft: String,
seen_external_value: Option<Option<i64>>,
source: MoneyChangeSource,
direction: i8,
value_changed_at_secs: f64,
menu_open: bool,
active_code: SharedString,
highlight_seeded: bool,
bump_dir: i8,
bump_at_secs: f64,
limit_flash_until_secs: f64,
control_hovered: bool,
currency_btn_hovered: bool,
pressed_chip: Option<i64>,
touched: bool,
control_bounds: Rc<RefCell<Option<Bounds<Pixels>>>>,
menu_bounds: Rc<RefCell<Option<Bounds<Pixels>>>>,
focus_handle: FocusHandle,
}
impl MoneyInputInternal {
fn new(
initial_currency: SharedString,
initial_draft: String,
seen_external_value: Option<Option<i64>>,
now: f64,
focus_handle: FocusHandle,
) -> Self {
Self {
active_code: initial_currency.clone(),
uncontrolled_currency: initial_currency,
previous_symbol: None,
symbol_changed_at_secs: now - 10.0,
draft: initial_draft,
seen_external_value,
source: MoneyChangeSource::External,
direction: 1,
value_changed_at_secs: now - 10.0,
menu_open: false,
highlight_seeded: false,
bump_dir: 0,
bump_at_secs: now - 10.0,
limit_flash_until_secs: f64::NEG_INFINITY,
control_hovered: false,
currency_btn_hovered: false,
pressed_chip: None,
touched: false,
control_bounds: Rc::new(RefCell::new(None)),
menu_bounds: Rc::new(RefCell::new(None)),
focus_handle,
}
}
}
fn paint_rotated_chevron(cx: f32, cy: f32, angle_deg: f32, color: Hsla, window: &mut Window) {
let rad = angle_deg.to_radians();
let cos_a = rad.cos();
let sin_a = rad.sin();
let pts = [(-4.0_f32, -2.0_f32), (0.0, 2.0), (4.0, -2.0)];
let mut builder = PathBuilder::stroke(px(1.75));
for (i, (lx, ly)) in pts.iter().enumerate() {
let rx = cx + lx * cos_a - ly * sin_a;
let ry = cy + lx * sin_a + ly * cos_a;
let p = point(px(rx), px(ry));
if i == 0 {
builder.move_to(p);
} else {
builder.line_to(p);
}
}
if let Ok(path) = builder.build() {
window.paint_path(path, color);
}
}
fn paint_scaled_check(
cx: f32,
cy: f32,
scale: f32,
opacity: f32,
color: Hsla,
window: &mut Window,
) {
if opacity <= 0.01 {
return;
}
let pts = [(-4.5_f32, 0.2_f32), (-1.4, 3.3), (4.8, -3.2)];
let mut builder = PathBuilder::stroke(px(1.75));
for (i, (lx, ly)) in pts.iter().enumerate() {
let p = point(px(cx + lx * scale), px(cy + ly * scale));
if i == 0 {
builder.move_to(p);
} else {
builder.line_to(p);
}
}
let c = Hsla {
a: color.a * opacity.clamp(0.0, 1.0),
..color
};
if let Ok(path) = builder.build() {
window.paint_path(path, c);
}
}
#[derive(IntoElement)]
pub struct MoneyInput {
id: ElementId,
label: SharedString,
hide_label: bool,
value: Option<Option<i64>>,
default_value: Option<i64>,
currency: Option<SharedString>,
default_currency: SharedString,
currencies: Vec<SharedString>,
min: Option<i64>,
max: Option<i64>,
quick_add: Vec<i64>,
step: Option<i64>,
description: Option<SharedString>,
error: Option<SharedString>,
disabled: bool,
width: Option<Pixels>,
on_value_change: Option<MoneyValueChangeHandler>,
on_currency_change: Option<MoneyCurrencyChangeHandler>,
}
impl MoneyInput {
pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
Self {
id: id.into(),
label: label.into(),
hide_label: false,
value: None,
default_value: None,
currency: None,
default_currency: "USD".into(),
currencies: vec![
"USD".into(),
"EUR".into(),
"GBP".into(),
"JPY".into(),
"CNY".into(),
"CAD".into(),
"AUD".into(),
"CHF".into(),
"INR".into(),
"HKD".into(),
"SGD".into(),
"KRW".into(),
"SEK".into(),
"NZD".into(),
"MXN".into(),
"BRL".into(),
],
min: None,
max: None,
quick_add: vec![10, 50, 100],
step: None,
description: None,
error: None,
disabled: false,
width: None,
on_value_change: None,
on_currency_change: None,
}
}
pub fn hide_label(mut self, hide: bool) -> Self {
self.hide_label = hide;
self
}
pub fn value(mut self, minor: Option<i64>) -> Self {
self.value = Some(minor);
self
}
pub fn default_value(mut self, minor: Option<i64>) -> Self {
self.default_value = minor;
self
}
pub fn currency(mut self, code: impl Into<SharedString>) -> Self {
self.currency = Some(code.into());
self
}
pub fn default_currency(mut self, code: impl Into<SharedString>) -> Self {
self.default_currency = code.into();
self
}
pub fn currencies<I, S>(mut self, codes: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<SharedString>,
{
self.currencies = codes.into_iter().map(Into::into).collect();
self
}
pub fn min(mut self, min_minor: i64) -> Self {
self.min = Some(min_minor);
self
}
pub fn max(mut self, max_minor: i64) -> Self {
self.max = Some(max_minor);
self
}
pub fn quick_add<I>(mut self, amounts_major: I) -> Self
where
I: IntoIterator<Item = i64>,
{
self.quick_add = amounts_major.into_iter().filter(|&a| a > 0).collect();
self
}
pub fn step(mut self, step_minor: i64) -> Self {
self.step = Some(step_minor.max(1));
self
}
pub fn description(mut self, description: impl Into<SharedString>) -> Self {
self.description = Some(description.into());
self
}
pub fn error(mut self, error: impl Into<SharedString>) -> Self {
self.error = Some(error.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(&MoneyValueEvent, &mut Window, &mut App) + 'static,
) -> Self {
self.on_value_change = Some(Rc::new(handler));
self
}
pub fn on_currency_change(
mut self,
handler: impl Fn(&SharedString, &mut Window, &mut App) + 'static,
) -> Self {
self.on_currency_change = Some(Rc::new(handler));
self
}
}
fn build_money_details(minor: Option<i64>, info: &MoneyCurrencyInfo) -> MoneyInputDetails {
let scale = pow10_i64(info.digits) as f64;
MoneyInputDetails {
currency: info.code.clone(),
major: minor.map(|m| (m as f64) / scale),
formatted: minor
.map(|m| SharedString::from(format_money_minor(m, info)))
.unwrap_or_default(),
}
}
impl RenderOnce for MoneyInput {
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 init_code = self
.currency
.clone()
.unwrap_or_else(|| self.default_currency.clone());
let init_info = money_currency_info(&init_code);
let init_minor = self.value.unwrap_or(self.default_value);
let init_draft = money_minor_to_draft(init_minor, init_info.digits);
let state_id =
ElementId::NamedChild(self.id.clone().into(), "__arc-money-input-state".into());
let internal = window.use_keyed_state(state_id, cx, |_, cx| {
MoneyInputInternal::new(
init_code.clone(),
init_draft,
self.value,
now,
cx.focus_handle(),
)
});
let code = self
.currency
.clone()
.unwrap_or_else(|| internal.read(cx).uncontrolled_currency.clone());
let info = money_currency_info(&code);
let step_minor = self.step.unwrap_or_else(|| pow10_i64(info.digits));
if self.value != internal.read(cx).seen_external_value {
let cur_minor = money_draft_to_minor(&internal.read(cx).draft, info.digits);
internal.update(cx, |s, _| {
s.seen_external_value = self.value;
if let Some(ext_minor) = self.value
&& ext_minor != cur_minor
{
s.direction = if ext_minor.unwrap_or(0) >= cur_minor.unwrap_or(0) {
1
} else {
-1
};
s.draft = money_minor_to_draft(ext_minor, info.digits);
s.source = MoneyChangeSource::External;
s.value_changed_at_secs = now;
}
});
}
let snap = internal.read(cx).clone();
let minor = money_draft_to_minor(&snap.draft, info.digits);
let is_focused = snap.focus_handle.is_focused(window);
let menu_open = snap.menu_open && !self.disabled;
let display_draft = if info.digits > 0 && snap.source != MoneyChangeSource::Type {
let zero_frac = format!(".{}", "0".repeat(info.digits));
if let Some(int_only) = snap.draft.strip_suffix(&zero_frac)
&& !int_only.is_empty()
{
int_only.to_string()
} else {
snap.draft.clone()
}
} else {
snap.draft.clone()
};
let parts = money_parts_of(&display_draft, info.digits);
let currency_options: Vec<MoneyCurrencyInfo> = if self.currencies.is_empty() {
vec![info.clone()]
} else {
self.currencies
.iter()
.map(|c| money_currency_info(c))
.collect()
};
let can_switch_currency = currency_options.len() > 1;
let bump_elapsed = (now - snap.bump_at_secs).max(0.0);
let bump_x = money_bump_x_offset(bump_elapsed, snap.bump_dir, reduced);
if !reduced && snap.bump_dir != 0 && bump_elapsed < MONEY_KICK_SETTLE_SECS {
window.request_animation_frame();
}
let flash_active = now < snap.limit_flash_until_secs;
if flash_active {
window.request_animation_frame();
}
let total_chars = parts.len() + info.symbol.chars().count();
let display_font_px = if total_chars <= 10 {
30.0_f32
} else if total_chars <= 14 {
24.0_f32
} else {
19.5_f32
};
let instant = snap.source == MoneyChangeSource::Type;
let val_elapsed = (now - snap.value_changed_at_secs).max(0.0);
let (glyph_op, glyph_y) = if instant || val_elapsed >= 0.22 {
(1.0_f32, 0.0_f32)
} else {
window.request_animation_frame();
let t = (val_elapsed / 0.20).clamp(0.0, 1.0) as f32;
let e = if reduced {
t
} else {
CubicBezier::new(0.16, 1.0, 0.3, 1.0).sample(t)
};
let blur = BlurFallback::evaluate(px(4.0 * (1.0 - e)), reduced);
let op = (e * blur.opacity_multiplier).clamp(0.0, 1.0);
let y = if reduced {
0.0
} else {
(snap.direction as f32) * (0.45 * display_font_px) * (1.0 - e)
};
(op, y)
};
let sym_natural_w = (info.symbol.chars().count() as f32) * (display_font_px * 0.62) + 2.0;
let sym_w = if reduced {
sym_natural_w
} else {
arc_spring(
(self.id.clone(), "sym-w"),
sym_natural_w,
motion.spring.morph,
window,
cx,
)
};
let sym_elapsed = (now - snap.symbol_changed_at_secs).max(0.0);
let (sym_op, sym_y) = if sym_elapsed >= 0.22 {
(1.0_f32, 0.0_f32)
} else {
window.request_animation_frame();
let t = (sym_elapsed / 0.20).clamp(0.0, 1.0) as f32;
let e = if reduced {
t
} else {
CubicBezier::new(0.16, 1.0, 0.3, 1.0).sample(t)
};
let blur = BlurFallback::evaluate(px(4.0 * (1.0 - e)), reduced);
(
(e * blur.opacity_multiplier).clamp(0.0, 1.0),
if reduced {
0.0
} else {
0.35 * display_font_px * (1.0 - e)
},
)
};
let make_symbol_el = || {
div()
.w(px(sym_w))
.overflow_hidden()
.mt(px(sym_y))
.opacity(sym_op)
.text_size(px(display_font_px))
.font_medium()
.text_color(colors.text_secondary)
.child(info.symbol.clone())
};
let ghost_color = oklab_mix(colors.text_muted, colors.surface, 0.45);
let show_caret = is_focused && !menu_open && !self.disabled;
let last_non_ghost_idx = parts.iter().rposition(|p| !p.ghost);
let make_caret_el = || {
div()
.mx(px(1.5))
.w(px(2.0))
.h(px(display_font_px * 0.72))
.rounded_full()
.bg(colors.accent)
.into_any_element()
};
let mut part_els = Vec::with_capacity(parts.len() + 1);
if show_caret && last_non_ghost_idx.is_none() {
part_els.push(make_caret_el());
}
for (idx, part) in parts.into_iter().enumerate() {
let col_fg = if part.ghost {
ghost_color
} else {
colors.foreground
};
let is_fraction_or_int = part.key.starts_with('i') || part.key.starts_with('f');
let dy = if is_fraction_or_int && !part.ghost {
glyph_y
} else {
0.0
};
let op = if is_fraction_or_int && !part.ghost {
glyph_op
} else {
1.0
};
part_els.push(
div()
.id(ElementId::NamedChild(self.id.clone().into(), part.key))
.mt(px(dy))
.opacity(op)
.text_size(px(display_font_px))
.font_medium()
.text_color(col_fg)
.child(SharedString::from(part.ch.to_string()))
.into_any_element(),
);
if show_caret && last_non_ghost_idx == Some(idx) {
part_els.push(make_caret_el());
}
}
let glide_spec = money_glide_spring();
let chevron_deg = if reduced {
if menu_open { 180.0 } else { 0.0 }
} else {
arc_spring(
(self.id.clone(), "chevron-deg"),
if menu_open { 180.0 } else { 0.0 },
glide_spec,
window,
cx,
)
};
let menu_presence = ArcPresence::new((self.id.clone(), "menu-presence"), menu_open)
.animate_initial(false)
.config(ArcPresenceConfig {
enter_duration: motion.duration.fast,
exit_duration: motion.duration.instant,
enter_ease: motion.ease.enter,
exit_ease: motion.ease.standard,
fade_on_reduced_motion: true,
})
.sample(window, cx);
let control_bounds_ref = snap.control_bounds.clone();
let control_bounds_outside = snap.control_bounds.clone();
let menu_bounds_outside = snap.menu_bounds.clone();
let internal_outside = internal.clone();
let control_probe = canvas(
move |rect, _, _| {
*control_bounds_ref.borrow_mut() = Some(rect);
},
move |_, _, window, _| {
if menu_open {
let c_ref = control_bounds_outside.clone();
let m_ref = menu_bounds_outside.clone();
let st = internal_outside.clone();
window.on_mouse_event(move |event: &MouseDownEvent, phase, window, cx| {
if !phase.bubble() {
return;
}
let in_ctrl = c_ref.borrow().is_some_and(|b| b.contains(&event.position));
let in_menu = m_ref.borrow().is_some_and(|b| b.contains(&event.position));
if !in_ctrl && !in_menu {
st.update(cx, |s, _| {
s.menu_open = false;
s.highlight_seeded = false;
});
window.refresh();
}
});
}
},
)
.absolute()
.inset_0();
let disabled = self.disabled;
let chevron_color = colors.text_muted;
let currency_slot = if can_switch_currency {
let int_c_hover = internal.clone();
let int_c_click = internal.clone();
let cur_code_for_open = code.clone();
let focus_for_menu = snap.focus_handle.clone();
let btn_bg = if menu_open || (snap.currency_btn_hovered && !disabled) {
colors.surface_muted
} else {
Hsla::transparent_black()
};
let trigger_btn = BaseButton::new(ElementId::NamedChild(
self.id.clone().into(),
"currency-button".into(),
))
.accessibility_label(SharedString::from(format!("Currency, {}", info.name)))
.disabled(disabled)
.on_click(move |_, window, cx| {
if disabled {
return;
}
window.focus(&focus_for_menu, cx);
int_c_click.update(cx, |s, _| {
s.menu_open = !s.menu_open;
if s.menu_open {
s.active_code = cur_code_for_open.clone();
s.highlight_seeded = false;
} else {
s.highlight_seeded = false;
}
});
window.refresh();
})
.h(px(36.0))
.pl(px(12.0))
.pr(px(8.0))
.flex()
.flex_row()
.items_center()
.gap(px(4.0))
.rounded(Radii::PILL)
.bg(btn_bg)
.text_size(Typography::TEXT_SM)
.font_medium()
.text_color(colors.foreground)
.when(!disabled, |this| this.cursor_pointer())
.on_hover(move |hovered, window, cx| {
int_c_hover.update(cx, |s, _| s.currency_btn_hovered = *hovered);
window.refresh();
})
.child(code.clone())
.child(
div().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_rotated_chevron(cx_pt, cy_pt, chevron_deg, chevron_color, window);
},
)
.size_full(),
),
);
let menu_el = if menu_presence.should_render() {
let p = menu_presence.progress.clamp(0.0, 1.0);
let menu_y = if reduced { 0.0 } else { -4.0 * (1.0 - p) };
let active_idx = currency_options
.iter()
.position(|o| o.code == snap.active_code)
.unwrap_or(0);
let target_hy = active_idx as f32 * 38.0;
let pill_y = if reduced || !snap.highlight_seeded {
let _ = arc_spring_with_options(
(self.id.clone(), "hi-y"),
target_hy,
SpringOptions::new(glide_spec).with_initial_value(target_hy),
window,
cx,
);
if menu_open && !snap.highlight_seeded {
internal.update(cx, |s, _| s.highlight_seeded = true);
}
target_hy
} else {
arc_spring((self.id.clone(), "hi-y"), target_hy, glide_spec, window, cx)
};
let hi_bg = oklab_mix(colors.foreground, colors.surface_raised, 0.065);
let menu_bounds_ref = snap.menu_bounds.clone();
let menu_probe = canvas(
move |rect, _, _| {
*menu_bounds_ref.borrow_mut() = Some(rect);
},
|_, _, _, _| {},
)
.absolute()
.inset_0();
let option_rows = currency_options
.iter()
.map(|opt| {
let is_selected = opt.code == code;
let is_active = opt.code == snap.active_code;
let check_op = arc_transition(
(self.id.clone(), format!("cur-chk-op-{}", opt.code)),
if is_selected { 1.0 } else { 0.0 },
if reduced {
Duration::ZERO
} else {
motion.duration.fast
},
motion.ease.standard,
window,
cx,
);
let check_scale = if reduced {
if is_selected { 1.0 } else { 0.6 }
} else {
arc_spring(
(self.id.clone(), format!("cur-chk-sc-{}", opt.code)),
if is_selected { 1.0 } else { 0.6 },
glide_spec,
window,
cx,
)
};
let row_fg = if is_active || is_selected {
colors.foreground
} else {
colors.text_secondary
};
let check_color = colors.foreground;
let int_hi = internal.clone();
let int_choose = internal.clone();
let on_v_change = self.on_value_change.clone();
let on_c_change = self.on_currency_change.clone();
let cur_sym = info.symbol.clone();
let opt_clone = opt.clone();
let code_hi = opt.code.clone();
div()
.id(ElementId::NamedChild(
self.id.clone().into(),
SharedString::from(format!("currency-{}", opt.code)),
))
.test_support()
.role(Role::ListBoxOption)
.aria_label(opt.name.clone())
.w_full()
.flex_none()
.h(px(36.0))
.min_h(px(36.0))
.px(px(10.0))
.flex()
.flex_row()
.items_center()
.gap(px(10.0))
.rounded(Radii::CONTROL)
.text_size(Typography::TEXT_SM)
.text_color(row_fg)
.cursor_pointer()
.on_hover(move |hovered, window, cx| {
if *hovered {
int_hi.update(cx, |s, _| {
s.active_code = code_hi.clone();
});
window.refresh();
}
})
.on_click(move |_, window, cx| {
let t_now = motion_now(cx);
let next_info = opt_clone.clone();
let cur_draft = int_choose.read(cx).draft.clone();
let converted = money_convert_draft(&cur_draft, next_info.digits);
let next_minor = money_draft_to_minor(&converted, next_info.digits);
let settled = money_minor_to_draft(next_minor, next_info.digits);
int_choose.update(cx, |s, _| {
s.menu_open = false;
s.highlight_seeded = false;
if next_info.code != s.uncontrolled_currency {
s.previous_symbol = Some(cur_sym.clone());
s.symbol_changed_at_secs = t_now;
s.uncontrolled_currency = next_info.code.clone();
}
s.draft = settled;
s.source = MoneyChangeSource::External;
});
if let Some(cb_c) = &on_c_change {
cb_c(&next_info.code, window, cx);
}
if let Some(cb_v) = &on_v_change {
let event = MoneyValueEvent {
minor: next_minor,
details: build_money_details(next_minor, &next_info),
};
cb_v(&event, window, cx);
}
window.refresh();
})
.child(
div()
.w(px(22.0))
.flex_none()
.text_color(colors.text_muted)
.child(opt.symbol.clone()),
)
.child(div().flex_none().font_medium().child(opt.code.clone()))
.child(
div()
.flex_1()
.min_w_0()
.text_size(Typography::TEXT_XS)
.text_color(colors.text_muted)
.truncate()
.child(opt.name.clone()),
)
.child(
div().size(px(16.0)).flex_none().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_scaled_check(
cx_pt,
cy_pt,
check_scale,
check_op,
check_color,
window,
);
},
)
.size_full(),
),
)
.into_any_element()
})
.collect::<Vec<_>>();
Some(
deferred(
div()
.id(ElementId::NamedChild(
self.id.clone().into(),
"currency-menu".into(),
))
.test_support()
.role(Role::ListBox)
.absolute()
.top_full()
.right(px(-8.0))
.mt(px(28.0 + menu_y))
.w(px(256.0))
.p(px(6.0))
.rounded(Radii::PANEL)
.border_1()
.border_color(colors.border)
.bg(colors.surface_raised)
.shadow(Shadows::floating(theme.mode))
.opacity(p)
.overflow_hidden()
.child(menu_probe)
.child(
div()
.id(ElementId::NamedChild(
self.id.clone().into(),
"currency-list".into(),
))
.relative()
.w_full()
.max_h(px(288.0))
.overflow_y_scroll()
.on_scroll(|_, _, cx| cx.stop_propagation())
.flex()
.flex_col()
.gap(px(2.0))
.child(
div()
.absolute()
.left_0()
.right_0()
.top(px(pill_y))
.h(px(36.0))
.rounded(Radii::CONTROL)
.bg(hi_bg),
)
.children(option_rows),
),
)
.with_priority(25),
)
} else {
None
};
div()
.relative()
.flex_none()
.child(trigger_btn)
.when_some(menu_el, |this, m| this.child(m))
.into_any_element()
} else {
div()
.px(px(10.0))
.flex_none()
.text_size(Typography::TEXT_SM)
.font_medium()
.text_color(colors.text_secondary)
.child(code.clone())
.into_any_element()
};
let range_text: Option<SharedString> = match (self.min, self.max) {
(Some(lo), Some(hi)) => Some(SharedString::from(format!(
"{} to {}",
format_money_minor(lo, &info),
format_money_minor(hi, &info)
))),
(None, Some(hi)) => Some(SharedString::from(format!(
"Up to {}",
format_money_minor(hi, &info)
))),
(Some(lo), None) => Some(SharedString::from(format!(
"At least {}",
format_money_minor(lo, &info)
))),
(None, None) => None,
};
let below_min = minor.is_some_and(|m| self.min.is_some_and(|lo| m < lo));
let above_max = minor.is_some_and(|m| self.max.is_some_and(|hi| m > hi));
let built_in_error: Option<SharedString> =
if snap.touched && !is_focused && (below_min || above_max) {
if below_min {
Some(SharedString::from(format!(
"The minimum is {}",
format_money_minor(self.min.unwrap_or(0), &info)
)))
} else {
Some(SharedString::from(format!(
"The maximum is {}",
format_money_minor(self.max.unwrap_or(0), &info)
)))
}
} else {
None
};
let effective_error = self.error.clone().or(built_in_error);
let is_invalid = effective_error.is_some();
let control_border = if is_invalid {
colors.danger
} else if !disabled && (is_focused || snap.control_hovered) {
colors.foreground
} else {
colors.border_strong
};
let int_ctrl_hover = internal.clone();
let int_focus_wrap = internal.clone();
let int_key = internal.clone();
let info_for_key = info.clone();
let options_for_key = currency_options;
let min_opt = self.min;
let max_opt = self.max;
let on_v_change_key = self.on_value_change.clone();
let on_c_change_key = self.on_currency_change.clone();
let focus_handle = snap.focus_handle.clone();
let focus_for_wrap = 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);
if int_key.read(cx).menu_open {
let cur_active = int_key.read(cx).active_code.clone();
let at = options_for_key
.iter()
.position(|o| o.code == cur_active)
.unwrap_or(0);
match event.keystroke.key.as_str() {
"down" | "arrowdown" => {
let next_idx = (at + 1).min(options_for_key.len() - 1);
let next_c = options_for_key[next_idx].code.clone();
int_key.update(cx, |s, _| s.active_code = next_c);
window.refresh();
return;
}
"up" | "arrowup" => {
let prev_idx = at.saturating_sub(1);
let prev_c = options_for_key[prev_idx].code.clone();
int_key.update(cx, |s, _| s.active_code = prev_c);
window.refresh();
return;
}
"escape" => {
int_key.update(cx, |s, _| {
s.menu_open = false;
s.highlight_seeded = false;
});
window.refresh();
return;
}
"enter" | " " | "space" => {
let chosen = options_for_key[at].clone();
let cur_draft = int_key.read(cx).draft.clone();
let converted = money_convert_draft(&cur_draft, chosen.digits);
let next_m = money_draft_to_minor(&converted, chosen.digits);
let settled = money_minor_to_draft(next_m, chosen.digits);
let old_sym = info_for_key.symbol.clone();
int_key.update(cx, |s, _| {
s.menu_open = false;
s.highlight_seeded = false;
if chosen.code != s.uncontrolled_currency {
s.previous_symbol = Some(old_sym);
s.symbol_changed_at_secs = t_now;
s.uncontrolled_currency = chosen.code.clone();
}
s.draft = settled;
s.source = MoneyChangeSource::External;
});
if let Some(cb_c) = &on_c_change_key {
cb_c(&chosen.code, window, cx);
}
if let Some(cb_v) = &on_v_change_key {
let event = MoneyValueEvent {
minor: next_m,
details: build_money_details(next_m, &chosen),
};
cb_v(&event, window, cx);
}
window.refresh();
return;
}
_ => {}
}
}
let (cur_draft_raw, cur_source) = {
let s = int_key.read(cx);
(s.draft.clone(), s.source)
};
let cur_draft = if cur_source != MoneyChangeSource::Type
&& let Some((w, f)) = cur_draft_raw.split_once('.')
&& f.chars().all(|c| c == '0')
{
if w == "0" {
String::new()
} else {
w.to_string()
}
} else {
cur_draft_raw
};
let cur_minor = money_draft_to_minor(&cur_draft, info_for_key.digits);
let shift = event.keystroke.modifiers.shift;
match event.keystroke.key.as_str() {
"up" | "arrowup" | "down" | "arrowdown" | "pageup" | "pagedown" => {
let mult: i64 = match event.keystroke.key.as_str() {
"up" | "arrowup" => {
if shift {
10
} else {
1
}
}
"down" | "arrowdown" => {
if shift {
-10
} else {
-1
}
}
"pageup" => 10,
"pagedown" => -10,
_ => 1,
};
let delta = mult.saturating_mul(step_minor);
let from = cur_minor.unwrap_or(0);
let floor = min_opt.unwrap_or(0);
let ceiling = max_opt.unwrap_or(i64::MAX / 2);
let mut next_m = from.saturating_add(delta);
let mut refused_dir: i8 = 0;
if next_m > ceiling {
refused_dir = 1;
next_m = ceiling;
} else if next_m < floor {
refused_dir = -1;
next_m = floor;
}
let next_draft = money_minor_to_draft(Some(next_m), info_for_key.digits);
int_key.update(cx, |s, _| {
s.touched = true;
if refused_dir != 0 {
s.bump_dir = refused_dir;
s.bump_at_secs = t_now;
s.limit_flash_until_secs = t_now + MONEY_LIMIT_FLASH_SECS;
}
if Some(next_m) != cur_minor {
s.direction = if next_m >= from { 1 } else { -1 };
s.draft = next_draft;
s.source = MoneyChangeSource::Key;
s.value_changed_at_secs = t_now;
}
});
if Some(next_m) != cur_minor
&& let Some(cb) = &on_v_change_key
{
let event = MoneyValueEvent {
minor: Some(next_m),
details: build_money_details(Some(next_m), &info_for_key),
};
cb(&event, window, cx);
}
window.refresh();
}
"backspace" => {
if !cur_draft.is_empty() {
let mut next_raw = cur_draft.clone();
next_raw.pop();
if let Some(san) = sanitize_money_draft(&next_raw, info_for_key.digits)
{
let next_m = money_draft_to_minor(&san, info_for_key.digits);
int_key.update(cx, |s, _| {
s.touched = true;
s.draft = san;
s.source = MoneyChangeSource::Type;
});
if next_m != cur_minor
&& let Some(cb) = &on_v_change_key
{
let event = MoneyValueEvent {
minor: next_m,
details: build_money_details(next_m, &info_for_key),
};
cb(&event, window, cx);
}
window.refresh();
}
}
}
"enter" => {
let settled = money_minor_to_draft(cur_minor, info_for_key.digits);
int_key.update(cx, |s, _| {
s.touched = true;
s.draft = settled;
});
window.refresh();
}
"v" if event.keystroke.modifiers.control
|| event.keystroke.modifiers.platform =>
{
let pasted = cx
.read_from_clipboard()
.and_then(|item| item.text())
.unwrap_or_default();
if let Some(parsed) = money_parse_pasted(&pasted, info_for_key.digits)
&& let Some(san) = sanitize_money_draft(&parsed, info_for_key.digits)
{
let next_m = money_draft_to_minor(&san, info_for_key.digits);
if let Some(hi) = max_opt
&& let Some(nm) = next_m
&& nm > hi
{
int_key.update(cx, |s, _| {
s.bump_dir = 1;
s.bump_at_secs = t_now;
s.limit_flash_until_secs = t_now + MONEY_LIMIT_FLASH_SECS;
});
window.refresh();
return;
}
int_key.update(cx, |s, _| {
s.touched = true;
s.draft = san;
s.source = MoneyChangeSource::Type;
});
if next_m != cur_minor
&& let Some(cb) = &on_v_change_key
{
let event = MoneyValueEvent {
minor: next_m,
details: build_money_details(next_m, &info_for_key),
};
cb(&event, window, cx);
}
window.refresh();
}
}
k => {
let ch_opt = event
.keystroke
.key_char
.as_deref()
.and_then(|kc| (kc.len() == 1).then(|| kc.chars().next()).flatten())
.or_else(|| (k.len() == 1).then(|| k.chars().next()).flatten());
let ch = ch_opt.unwrap_or(' ');
if !event.keystroke.modifiers.control
&& !event.keystroke.modifiers.platform
&& (ch.is_ascii_digit() || (ch == '.' && info_for_key.digits > 0))
{
let candidate = format!("{cur_draft}{ch}");
let Some(san) = sanitize_money_draft(&candidate, info_for_key.digits)
else {
return;
};
let next_m = money_draft_to_minor(&san, info_for_key.digits);
if let Some(hi) = max_opt
&& let Some(nm) = next_m
&& nm > hi
{
int_key.update(cx, |s, _| {
s.bump_dir = 1;
s.bump_at_secs = t_now;
s.limit_flash_until_secs = t_now + MONEY_LIMIT_FLASH_SECS;
});
window.refresh();
return;
}
int_key.update(cx, |s, _| {
s.touched = true;
s.draft = san;
s.source = MoneyChangeSource::Type;
});
if next_m != cur_minor
&& let Some(cb) = &on_v_change_key
{
let event = MoneyValueEvent {
minor: next_m,
details: build_money_details(next_m, &info_for_key),
};
cb(&event, window, cx);
}
window.refresh();
}
}
}
})
.relative()
.w_full()
.h(px(76.0))
.pl(px(18.0))
.pr(px(8.0))
.flex()
.flex_row()
.items_center()
.gap(Spacing::S2)
.rounded(Radii::PANEL)
.border_1()
.border_color(control_border)
.bg(if disabled {
colors.surface_muted
} else {
colors.surface
})
.opacity(if disabled { 0.5 } else { 1.0 })
.child(control_probe)
.child(
div()
.id(ElementId::NamedChild(
self.id.clone().into(),
"amount-wrap".into(),
))
.flex_1()
.min_w_0()
.h_full()
.flex()
.items_center()
.overflow_hidden()
.when(!disabled, |this| {
let focus_down = focus_for_wrap.clone();
this.cursor_pointer().on_mouse_down(
MouseButton::Left,
move |_, window, cx| {
window.focus(&focus_down, cx);
window.refresh();
},
)
})
.on_click(move |_, window, cx| {
if !disabled {
let _ = &int_focus_wrap;
window.focus(&focus_for_wrap, cx);
window.refresh();
}
})
.child(
div()
.ml(px(bump_x))
.flex()
.flex_row()
.items_center()
.when(info.symbol_is_prefix, |this| {
this.child(div().mr(px(2.0)).child(make_symbol_el()))
})
.children(part_els)
.when(!info.symbol_is_prefix, |this| {
this.child(div().ml(px(5.0)).child(make_symbol_el()))
}),
),
)
.child(currency_slot);
let show_toolbar = !self.quick_add.is_empty() || range_text.is_some();
let toolbar_el = if show_toolbar {
let chip_buttons = self
.quick_add
.iter()
.copied()
.map(|major_amt| {
let add_minor = major_amt.saturating_mul(pow10_i64(info.digits));
let at_max = self.max.is_some_and(|hi| minor.unwrap_or(0) >= hi);
let is_pressed = snap.pressed_chip == Some(major_amt) && !disabled;
let chip_text = SharedString::from(format!(
"+{}",
format_money_whole_major(major_amt, &info)
));
let int_down = internal.clone();
let int_up = internal.clone();
let int_out = internal.clone();
let int_click = internal.clone();
let info_for_chip = info.clone();
let on_v_change = self.on_value_change.clone();
let hover_bg = colors.surface_muted;
let hover_fg = colors.foreground;
BaseButton::new(ElementId::NamedChild(
self.id.clone().into(),
SharedString::from(format!("quick-add-{major_amt}")),
))
.accessibility_label(SharedString::from(format!(
"Add {}",
format_money_whole_major(major_amt, &info)
)))
.disabled(disabled)
.on_click(move |_, window, cx| {
if disabled {
return;
}
let t_now = motion_now(cx);
let cur_draft = int_click.read(cx).draft.clone();
let cur_m = money_draft_to_minor(&cur_draft, info_for_chip.digits);
let from = cur_m.unwrap_or(0);
let floor = min_opt.unwrap_or(0);
let ceiling = max_opt.unwrap_or(i64::MAX / 2);
let mut next_m = from.saturating_add(add_minor);
let mut refused = false;
if next_m > ceiling {
refused = true;
next_m = ceiling;
} else if next_m < floor {
next_m = floor;
}
let next_draft = money_minor_to_draft(Some(next_m), info_for_chip.digits);
int_click.update(cx, |s, _| {
s.pressed_chip = None;
s.touched = true;
if refused {
s.bump_dir = 1;
s.bump_at_secs = t_now;
s.limit_flash_until_secs = t_now + MONEY_LIMIT_FLASH_SECS;
}
if Some(next_m) != cur_m {
s.direction = 1;
s.draft = next_draft;
s.source = MoneyChangeSource::Chip;
s.value_changed_at_secs = t_now;
}
});
if Some(next_m) != cur_m
&& let Some(cb) = &on_v_change
{
let event = MoneyValueEvent {
minor: Some(next_m),
details: build_money_details(Some(next_m), &info_for_chip),
};
cb(&event, window, cx);
}
window.refresh();
})
.h(px(if is_pressed && !reduced { 29.0 } else { 30.0 }))
.px(px(12.0))
.flex()
.items_center()
.justify_center()
.rounded(Radii::PILL)
.border_1()
.border_color(colors.border)
.bg(colors.surface)
.opacity(if disabled || at_max { 0.45 } else { 1.0 })
.text_size(Typography::TEXT_XS)
.font_medium()
.text_color(colors.text_secondary)
.when(!disabled && !at_max, |this| {
this.cursor_pointer()
.hover(move |s| s.bg(hover_bg).text_color(hover_fg))
})
.on_mouse_down(MouseButton::Left, move |_, window, cx| {
int_down.update(cx, |s, _| s.pressed_chip = Some(major_amt));
window.refresh();
})
.on_mouse_up(MouseButton::Left, move |_, window, cx| {
int_up.update(cx, |s, _| s.pressed_chip = None);
window.refresh();
})
.on_mouse_up_out(MouseButton::Left, move |_, window, cx| {
int_out.update(cx, |s, _| s.pressed_chip = None);
window.refresh();
})
.child(chip_text)
.into_any_element()
})
.collect::<Vec<_>>();
let range_fg = if flash_active {
colors.warning
} else {
colors.text_muted
};
Some(
div()
.w_full()
.pt(Spacing::S3)
.flex()
.flex_row()
.flex_wrap()
.items_center()
.justify_between()
.gap(Spacing::S2)
.child(
div()
.flex()
.flex_row()
.flex_wrap()
.gap(px(6.0))
.children(chip_buttons),
)
.when_some(range_text, |this, rt| {
this.child(
div()
.text_size(Typography::TEXT_XS)
.text_color(range_fg)
.child(rt),
)
}),
)
} else {
None
};
let msg_id = ElementId::NamedChild(self.id.clone().into(), "message".into());
let msg_text = effective_error.clone().or(self.description);
div()
.id(self.id)
.test_support()
.when_some(self.width, |this, w| this.w(w))
.when(self.width.is_none(), |this| this.w_full())
.flex()
.flex_col()
.when(!self.hide_label, |this| {
this.child(
div()
.mb(Spacing::S2)
.text_size(Typography::TEXT_SM)
.font_medium()
.text_color(colors.foreground)
.child(self.label),
)
})
.child(control)
.when_some(toolbar_el, |this, tb| this.child(tb))
.child(render_field_message(
msg_id, msg_text, is_invalid, window, cx,
))
}
}
#[cfg(test)]
mod tests {
use arc_motion::{CurveTrace, max_curve_error_pct};
use arc_tokens::{Accent, ThemeMode, install_arc_theme};
use gpui_kit::{ClipboardItem, Context, Render, TestAppContext, test::TestWindowExt as _};
use super::*;
#[test]
fn money_draft_and_minor_conversions_handle_cents_and_zero_decimal_currencies() {
assert_eq!(money_draft_to_minor("", 2), None);
assert_eq!(money_draft_to_minor("12.5", 2), Some(1250));
assert_eq!(money_draft_to_minor("12.50", 2), Some(1250));
assert_eq!(money_draft_to_minor("1250", 0), Some(1250));
assert_eq!(money_minor_to_draft(Some(1250), 2), "12.50");
assert_eq!(money_minor_to_draft(Some(5), 2), "0.05");
assert_eq!(money_minor_to_draft(Some(1250), 0), "1250");
}
#[test]
fn money_parts_of_marks_missing_cents_as_ghosts_and_keys_by_place_value() {
let empty_parts = money_parts_of("", 2);
assert_eq!(empty_parts.len(), 4); assert!(empty_parts.iter().all(|p| p.ghost));
let partial = money_parts_of("12.5", 2);
assert_eq!(partial.len(), 5);
assert!(!partial[0].ghost);
assert!(!partial[3].ghost);
assert!(partial[4].ghost);
}
#[test]
fn sanitize_money_draft_strips_leading_zeroes_and_enforces_precision() {
assert_eq!(sanitize_money_draft("0012.3", 2), Some("12.3".to_string()));
assert_eq!(sanitize_money_draft(".5", 2), Some("0.5".to_string()));
assert_eq!(sanitize_money_draft("12.345", 2), None);
}
#[test]
fn money_parse_pasted_applies_arc_decimal_heuristic() {
assert_eq!(
money_parse_pasted("$1,234.56", 2).as_deref(),
Some("1234.56")
);
assert_eq!(
money_parse_pasted("1.234,56 €", 2).as_deref(),
Some("1234.56")
);
assert_eq!(money_parse_pasted("1234.5", 2).as_deref(), Some("1234.5"));
assert_eq!(money_parse_pasted("12", 2).as_deref(), Some("12"));
assert_eq!(money_parse_pasted("abc", 2), None);
assert_eq!(money_parse_pasted("$1,234.56", 0).as_deref(), Some("1234"));
}
#[test]
fn money_bump_kick_follows_motion_explicit_velocity_critical_spring() {
let omega = std::f64::consts::TAU / (0.42 * 1.2);
let mut expected = CurveTrace::new("money_input", "bump_x");
let mut actual = CurveTrace::new("money_input", "bump_x");
for frame in 0..=70usize {
let t_ms = frame as f64 * 16.0;
let t = t_ms / 1000.0;
expected.push(t_ms, 160.0 * t * (-omega * t).exp());
actual.push(t_ms, f64::from(money_bump_x_offset(t, 1, false)));
}
let err = max_curve_error_pct(&actual, &expected);
assert!(err < 5.0, "bump kick error {err:.3}% >= 5%");
assert_eq!(money_bump_x_offset(0.08, 1, true), 0.0);
assert_eq!(money_bump_x_offset(0.08, 0, false), 0.0);
assert_eq!(money_bump_x_offset(-1.0, 1, false), 0.0);
}
struct MoneyHost {
minor: Option<i64>,
currency: SharedString,
disabled: bool,
values: Rc<RefCell<Vec<Option<i64>>>>,
currencies: Rc<RefCell<Vec<SharedString>>>,
}
impl Render for MoneyHost {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let values = self.values.clone();
let currencies = self.currencies.clone();
div().w(px(520.0)).p(px(16.0)).child(
MoneyInput::new("money-test", "Amount")
.min(500)
.max(3_000)
.value(self.minor)
.currency(self.currency.clone())
.quick_add([10, 50])
.disabled(self.disabled)
.on_value_change(cx.listener({
let values = values.clone();
move |this, event: &MoneyValueEvent, _, cx| {
values.borrow_mut().push(event.minor);
this.minor = event.minor;
cx.notify();
}
}))
.on_currency_change(cx.listener({
let currencies = currencies.clone();
move |this, code: &SharedString, _, cx| {
currencies.borrow_mut().push(code.clone());
this.currency = code.clone();
cx.notify();
}
})),
)
}
}
fn money_element(name: &str) -> ElementId {
ElementId::NamedChild(ElementId::Name("money-test".into()).into(), name.into())
}
#[gpui_kit::test]
fn money_input_types_steps_pastes_switches_currency_and_refuses_limits(
cx: &mut TestAppContext,
) {
cx.update(|cx| {
gpui_kit::init(cx);
install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
});
let host = MoneyHost {
minor: None,
currency: "USD".into(),
disabled: false,
values: Rc::new(RefCell::new(Vec::new())),
currencies: Rc::new(RefCell::new(Vec::new())),
};
let values = host.values.clone();
let currencies = host.currencies.clone();
let (view, cx) = cx.add_window_view(|_, _| host);
cx.update(|window, cx| {
window.render_frame(cx);
let control = window.find(money_element("control"));
assert_eq!(control.role(), Some(Role::SpinButton));
window.click(money_element("control"), cx);
window.input("25", cx);
});
assert_eq!(values.borrow().as_slice(), [Some(200), Some(2_500)]);
cx.update(|window, cx| {
window.press("up", cx);
});
assert_eq!(values.borrow().last(), Some(&Some(2_600)));
cx.update(|window, cx| {
window.press("shift-down", cx);
});
assert_eq!(values.borrow().last(), Some(&Some(1_600)));
cx.update(|window, cx| {
window.click(money_element("quick-add-10"), cx);
});
assert_eq!(values.borrow().last(), Some(&Some(2_600)));
cx.update(|window, cx| {
window.click(money_element("currency-button"), cx);
window.render_frame(cx);
let menu = window.find(money_element("currency-menu"));
assert_eq!(menu.role(), Some(Role::ListBox));
let row = window.find(money_element("currency-JPY"));
assert_eq!(row.role(), Some(Role::ListBoxOption));
window.click(money_element("currency-JPY"), cx);
});
assert_eq!(
currencies.borrow().last().map(|code| code.to_string()),
Some("JPY".to_string())
);
assert_eq!(values.borrow().last(), Some(&Some(26)));
cx.update(|_window, cx| {
cx.write_to_clipboard(ClipboardItem::new_string("$1,234.56".to_string()));
});
cx.update(|window, cx| {
window.press(
if cfg!(target_os = "macos") {
"cmd-v"
} else {
"ctrl-v"
},
cx,
);
});
assert_eq!(values.borrow().last(), Some(&Some(1_234)));
cx.update(|window, cx| {
window.input("5", cx);
});
assert_eq!(values.borrow().last(), Some(&Some(1_234)));
view.update(cx, |host, cx| {
host.disabled = true;
cx.notify();
});
cx.update(|window, cx| {
window.render_frame(cx);
window.click(money_element("control"), cx);
window.input("7", cx);
window.click(money_element("currency-button"), cx);
window.render_frame(cx);
assert!(window.try_find(money_element("currency-menu")).is_none());
});
assert_eq!(values.borrow().last(), Some(&Some(1_234)));
}
#[gpui_kit::test]
fn money_input_reduced_motion_keeps_interactions_instant(cx: &mut TestAppContext) {
cx.update(|cx| {
gpui_kit::init(cx);
install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
arc_motion::set_reduced_motion(arc_motion::ReducedMotionChoice::Reduce, cx);
});
let host = MoneyHost {
minor: None,
currency: "USD".into(),
disabled: false,
values: Rc::new(RefCell::new(Vec::new())),
currencies: Rc::new(RefCell::new(Vec::new())),
};
let values = host.values.clone();
let (_view, cx) = cx.add_window_view(|_, _| host);
cx.update(|window, cx| {
window.render_frame(cx);
window.click(money_element("control"), cx);
window.input("25", cx);
window.press("up", cx);
});
assert_eq!(
values.borrow().as_slice(),
[Some(200), Some(2_500), Some(2_600)]
);
}
}