1use std::{cell::RefCell, rc::Rc, time::Duration};
39
40use arc_motion::{
41 ArcPresence, ArcPresenceConfig, BlurFallback, CubicBezier, SpringSolver, arc_spring,
42 arc_spring_with_options, arc_transition, is_reduced_motion, motion_now, spring::SpringOptions,
43};
44use arc_tokens::{ActiveArcTheme as _, Radii, Shadows, Spacing, SpringSpec, Typography, oklab_mix};
45use gpui_kit::{
46 App, Bounds, ElementId, FocusHandle, Hsla, IntoElement, KeyDownEvent, MouseButton,
47 MouseDownEvent, ParentElement, PathBuilder, Pixels, RenderOnce, Role, SharedString, Styled,
48 TestSupportExt as _, Window,
49 base::{Button as BaseButton, StyledExt as _},
50 canvas, deferred, div, point,
51 prelude::*,
52 px,
53};
54
55use super::field_message::render_field_message;
56
57type MoneyValueChangeHandler = Rc<dyn Fn(&MoneyValueEvent, &mut Window, &mut App)>;
58type MoneyCurrencyChangeHandler = Rc<dyn Fn(&SharedString, &mut Window, &mut App)>;
59
60pub const MONEY_MAX_INTEGER_DIGITS: usize = 12;
62pub const MONEY_LIMIT_FLASH_SECS: f64 = 1.4;
64
65pub const MONEY_KICK_SETTLE_SECS: f64 = 1.2;
68
69pub const fn money_glide_spring() -> SpringSpec {
71 SpringSpec::visual(0.28, 0.0)
72}
73
74pub const fn money_kick_spring() -> SpringSpec {
76 SpringSpec::visual(0.42, 0.0)
77}
78
79#[derive(Clone, Debug, PartialEq, Eq)]
81pub struct MoneyCurrencyInfo {
82 pub code: SharedString,
83 pub symbol: SharedString,
84 pub symbol_is_prefix: bool,
85 pub digits: usize,
86 pub name: SharedString,
87}
88
89pub fn money_currency_info(code: &str) -> MoneyCurrencyInfo {
92 let upper = code.trim().to_uppercase();
93 match upper.as_str() {
94 "USD" => MoneyCurrencyInfo {
95 code: "USD".into(),
96 symbol: "$".into(),
97 symbol_is_prefix: true,
98 digits: 2,
99 name: "US Dollar".into(),
100 },
101 "EUR" => MoneyCurrencyInfo {
102 code: "EUR".into(),
103 symbol: "€".into(),
104 symbol_is_prefix: true,
105 digits: 2,
106 name: "Euro".into(),
107 },
108 "GBP" => MoneyCurrencyInfo {
109 code: "GBP".into(),
110 symbol: "£".into(),
111 symbol_is_prefix: true,
112 digits: 2,
113 name: "British Pound".into(),
114 },
115 "JPY" => MoneyCurrencyInfo {
116 code: "JPY".into(),
117 symbol: "¥".into(),
118 symbol_is_prefix: true,
119 digits: 0,
120 name: "Japanese Yen".into(),
121 },
122 "CNY" | "RMB" => MoneyCurrencyInfo {
123 code: "CNY".into(),
124 symbol: "¥".into(),
125 symbol_is_prefix: true,
126 digits: 2,
127 name: "Chinese Yuan".into(),
128 },
129 "CAD" => MoneyCurrencyInfo {
130 code: "CAD".into(),
131 symbol: "CA$".into(),
132 symbol_is_prefix: true,
133 digits: 2,
134 name: "Canadian Dollar".into(),
135 },
136 "AUD" => MoneyCurrencyInfo {
137 code: "AUD".into(),
138 symbol: "A$".into(),
139 symbol_is_prefix: true,
140 digits: 2,
141 name: "Australian Dollar".into(),
142 },
143 "CHF" => MoneyCurrencyInfo {
144 code: "CHF".into(),
145 symbol: "CHF".into(),
146 symbol_is_prefix: false,
147 digits: 2,
148 name: "Swiss Franc".into(),
149 },
150 "INR" => MoneyCurrencyInfo {
151 code: "INR".into(),
152 symbol: "₹".into(),
153 symbol_is_prefix: true,
154 digits: 2,
155 name: "Indian Rupee".into(),
156 },
157 "HKD" => MoneyCurrencyInfo {
158 code: "HKD".into(),
159 symbol: "HK$".into(),
160 symbol_is_prefix: true,
161 digits: 2,
162 name: "Hong Kong Dollar".into(),
163 },
164 "SGD" => MoneyCurrencyInfo {
165 code: "SGD".into(),
166 symbol: "S$".into(),
167 symbol_is_prefix: true,
168 digits: 2,
169 name: "Singapore Dollar".into(),
170 },
171 "KRW" => MoneyCurrencyInfo {
172 code: "KRW".into(),
173 symbol: "₩".into(),
174 symbol_is_prefix: true,
175 digits: 0,
176 name: "South Korean Won".into(),
177 },
178 "SEK" => MoneyCurrencyInfo {
179 code: "SEK".into(),
180 symbol: "kr".into(),
181 symbol_is_prefix: false,
182 digits: 2,
183 name: "Swedish Krona".into(),
184 },
185 "NZD" => MoneyCurrencyInfo {
186 code: "NZD".into(),
187 symbol: "NZ$".into(),
188 symbol_is_prefix: true,
189 digits: 2,
190 name: "New Zealand Dollar".into(),
191 },
192 "MXN" => MoneyCurrencyInfo {
193 code: "MXN".into(),
194 symbol: "MX$".into(),
195 symbol_is_prefix: true,
196 digits: 2,
197 name: "Mexican Peso".into(),
198 },
199 "BRL" => MoneyCurrencyInfo {
200 code: "BRL".into(),
201 symbol: "R$".into(),
202 symbol_is_prefix: true,
203 digits: 2,
204 name: "Brazilian Real".into(),
205 },
206 _ => MoneyCurrencyInfo {
207 code: SharedString::from(upper.clone()),
208 symbol: SharedString::from(upper.clone()),
209 symbol_is_prefix: true,
210 digits: 2,
211 name: SharedString::from(upper),
212 },
213 }
214}
215
216#[derive(Clone, Debug, PartialEq)]
218pub struct MoneyInputDetails {
219 pub currency: SharedString,
220 pub major: Option<f64>,
221 pub formatted: SharedString,
222}
223
224#[derive(Clone, Debug, PartialEq)]
228pub struct MoneyValueEvent {
229 pub minor: Option<i64>,
230 pub details: MoneyInputDetails,
231}
232
233#[derive(Clone, Debug, PartialEq, Eq)]
235pub struct MoneyPart {
236 pub key: SharedString,
237 pub ch: char,
238 pub ghost: bool,
239}
240
241const fn pow10_i64(digits: usize) -> i64 {
242 10_i64.pow(digits as u32)
243}
244
245pub fn money_draft_to_minor(draft: &str, digits: usize) -> Option<i64> {
248 let trimmed = draft.trim();
249 if trimmed.is_empty() {
250 return None;
251 }
252 let (whole_str, frac_str) = match trimmed.split_once('.') {
253 Some((w, f)) => (w, f),
254 None => (trimmed, ""),
255 };
256 let whole: i64 = if whole_str.is_empty() {
257 0
258 } else {
259 whole_str.parse().ok()?
260 };
261 let frac: i64 = if digits == 0 {
262 0
263 } else {
264 let mut padded = frac_str.chars().take(digits).collect::<String>();
265 while padded.len() < digits {
266 padded.push('0');
267 }
268 padded.parse().ok()?
269 };
270 Some(whole.saturating_mul(pow10_i64(digits)).saturating_add(frac))
271}
272
273pub fn money_minor_to_draft(minor: Option<i64>, digits: usize) -> String {
275 let Some(m) = minor else {
276 return String::new();
277 };
278 let abs_m = m.unsigned_abs();
279 let scale = 10_u64.pow(digits as u32);
280 if digits == 0 {
281 format!("{abs_m}")
282 } else {
283 let whole = abs_m / scale;
284 let frac = abs_m % scale;
285 format!("{whole}.{frac:0>width$}", width = digits)
286 }
287}
288
289pub fn money_convert_draft(draft: &str, next_digits: usize) -> String {
292 if draft.is_empty() {
293 return String::new();
294 }
295 let (whole, frac_opt) = match draft.split_once('.') {
296 Some((w, f)) => (w, Some(f)),
297 None => (draft, None),
298 };
299 if next_digits == 0 {
300 if whole.is_empty() {
301 "0".to_string()
302 } else {
303 whole.to_string()
304 }
305 } else {
306 match frac_opt {
307 Some(f) => {
308 let clipped: String = f.chars().take(next_digits).collect();
309 let w = if whole.is_empty() { "0" } else { whole };
310 format!("{w}.{clipped}")
311 }
312 None => whole.to_string(),
313 }
314 }
315}
316
317pub fn format_money_minor(minor: i64, info: &MoneyCurrencyInfo) -> String {
319 let draft = money_minor_to_draft(Some(minor), info.digits);
320 let (whole, frac_opt) = match draft.split_once('.') {
321 Some((w, f)) => (w, Some(f)),
322 None => (draft.as_str(), None),
323 };
324 let grouped_whole = group_ascii_digits(whole);
325 let num_str = match frac_opt {
326 Some(f) => format!("{grouped_whole}.{f}"),
327 None => grouped_whole,
328 };
329 if info.symbol_is_prefix {
330 format!("{}{num_str}", info.symbol)
331 } else {
332 format!("{num_str} {}", info.symbol)
333 }
334}
335
336pub fn format_money_whole_major(major: i64, info: &MoneyCurrencyInfo) -> String {
339 let grouped = group_ascii_digits(&major.to_string());
340 if info.symbol_is_prefix {
341 format!("{}{grouped}", info.symbol)
342 } else {
343 format!("{grouped} {}", info.symbol)
344 }
345}
346
347fn group_ascii_digits(whole: &str) -> String {
348 let chars: Vec<char> = whole.chars().collect();
349 let len = chars.len();
350 let mut out = String::with_capacity(len + len / 3);
351 for (idx, &ch) in chars.iter().enumerate() {
352 out.push(ch);
353 let rem = len - 1 - idx;
354 if rem > 0 && rem.is_multiple_of(3) {
355 out.push(',');
356 }
357 }
358 out
359}
360
361pub fn money_parts_of(draft: &str, digits: usize) -> Vec<MoneyPart> {
364 let (whole, frac_opt) = if draft.is_empty() {
365 ("", None)
366 } else {
367 match draft.split_once('.') {
368 Some((w, f)) => (w, Some(f)),
369 None => (draft, None),
370 }
371 };
372 let int_digits = if whole.is_empty() { "0" } else { whole };
373 let ghost_int = whole.is_empty();
374 let int_chars: Vec<char> = int_digits.chars().collect();
375 let int_len = int_chars.len();
376
377 let mut parts = Vec::with_capacity(int_len + digits + 4);
378 for (idx, &ch) in int_chars.iter().enumerate() {
379 let place = int_len - 1 - idx;
380 parts.push(MoneyPart {
381 key: SharedString::from(format!("i{place}")),
382 ch,
383 ghost: ghost_int,
384 });
385 if place > 0 && place.is_multiple_of(3) {
386 parts.push(MoneyPart {
387 key: SharedString::from(format!("g{place}")),
388 ch: ',',
389 ghost: ghost_int,
390 });
391 }
392 }
393 if digits > 0 {
394 parts.push(MoneyPart {
395 key: "d".into(),
396 ch: '.',
397 ghost: frac_opt.is_none(),
398 });
399 let frac_chars: Vec<char> = frac_opt.unwrap_or("").chars().collect();
400 for idx in 0..digits {
401 let ch = frac_chars.get(idx).copied().unwrap_or('0');
402 let is_ghost = frac_opt.is_none() || idx >= frac_chars.len();
403 parts.push(MoneyPart {
404 key: SharedString::from(format!("f{idx}")),
405 ch,
406 ghost: is_ghost,
407 });
408 }
409 }
410 parts
411}
412
413pub fn sanitize_money_draft(raw: &str, digits: usize) -> Option<String> {
416 let mut cleaned = String::new();
417 let mut seen_dot = false;
418 for ch in raw.chars() {
419 if ch.is_ascii_digit() {
420 cleaned.push(ch);
421 } else if ch == '.' && digits > 0 && !seen_dot {
422 cleaned.push('.');
423 seen_dot = true;
424 }
425 }
426 if cleaned.is_empty() {
427 return Some(String::new());
428 }
429 let (raw_whole, frac_opt) = match cleaned.split_once('.') {
430 Some((w, f)) => (w, Some(f)),
431 None => (cleaned.as_str(), None),
432 };
433 let had_leading_zero = !raw_whole.is_empty();
434 let mut whole = raw_whole.trim_start_matches('0').to_string();
435 if whole.is_empty() && (frac_opt.is_some() || had_leading_zero) {
436 whole.push('0');
437 }
438 if whole.len() > MONEY_MAX_INTEGER_DIGITS {
439 return None;
440 }
441 if let Some(f) = frac_opt {
442 if f.len() > digits {
443 return None;
444 }
445 Some(format!("{whole}.{f}"))
446 } else {
447 Some(whole)
448 }
449}
450
451pub fn money_parse_pasted(text: &str, digits: usize) -> Option<String> {
457 let trimmed = text.trim();
458 if trimmed.is_empty() {
459 return None;
460 }
461 let chars: Vec<char> = trimmed.chars().collect();
462 if !chars.iter().any(|&c| c.is_ascii_digit()) {
463 return None;
464 }
465 let mut decimal_at: Option<(usize, usize)> = None;
468 for (idx, &ch) in chars.iter().enumerate() {
469 if ch == '.' || ch == ',' {
470 let mut end = idx + 1;
471 let mut count = 0;
472 while end < chars.len() && chars[end].is_ascii_digit() && count < 2 {
473 end += 1;
474 count += 1;
475 }
476 if count >= 1 && chars[end..].iter().all(|&c| !c.is_ascii_digit()) {
477 decimal_at = Some((idx, count));
478 break;
479 }
480 }
481 }
482 let (whole, fraction) = match decimal_at {
483 Some((sep, count)) => (
484 chars[..sep]
485 .iter()
486 .filter(|&c| c.is_ascii_digit())
487 .collect::<String>(),
488 Some(chars[sep + 1..sep + 1 + count].iter().collect::<String>()),
489 ),
490 None => (
491 chars
492 .iter()
493 .filter(|&c| c.is_ascii_digit())
494 .collect::<String>(),
495 None,
496 ),
497 };
498 Some(match (digits, fraction) {
499 (0, _) => whole,
500 (_, Some(f)) => format!("{whole}.{f}"),
501 (_, None) => whole,
502 })
503}
504
505pub fn money_bump_x_offset(elapsed: f64, direction: i8, reduced: bool) -> f32 {
510 if reduced || direction == 0 || !(0.0..MONEY_KICK_SETTLE_SECS).contains(&elapsed) {
511 return 0.0;
512 }
513 let solver = SpringSolver::new(
517 money_kick_spring().as_physical(),
518 0.0,
519 0.0,
520 f64::from(direction) * 160.0,
521 );
522 solver.sample(elapsed).value
523}
524
525#[derive(Clone, Copy, Debug, PartialEq, Eq)]
526enum MoneyChangeSource {
527 Type,
528 Chip,
529 Key,
530 External,
531}
532
533#[derive(Clone)]
534struct MoneyInputInternal {
535 uncontrolled_currency: SharedString,
536 previous_symbol: Option<SharedString>,
537 symbol_changed_at_secs: f64,
538 draft: String,
539 seen_external_value: Option<Option<i64>>,
540 source: MoneyChangeSource,
541 direction: i8,
542 value_changed_at_secs: f64,
543 menu_open: bool,
544 active_code: SharedString,
545 highlight_seeded: bool,
546 bump_dir: i8,
547 bump_at_secs: f64,
548 limit_flash_until_secs: f64,
549 control_hovered: bool,
550 currency_btn_hovered: bool,
551 pressed_chip: Option<i64>,
552 touched: bool,
553 control_bounds: Rc<RefCell<Option<Bounds<Pixels>>>>,
554 menu_bounds: Rc<RefCell<Option<Bounds<Pixels>>>>,
555 focus_handle: FocusHandle,
556}
557
558impl MoneyInputInternal {
559 fn new(
560 initial_currency: SharedString,
561 initial_draft: String,
562 seen_external_value: Option<Option<i64>>,
563 now: f64,
564 focus_handle: FocusHandle,
565 ) -> Self {
566 Self {
567 active_code: initial_currency.clone(),
568 uncontrolled_currency: initial_currency,
569 previous_symbol: None,
570 symbol_changed_at_secs: now - 10.0,
571 draft: initial_draft,
572 seen_external_value,
573 source: MoneyChangeSource::External,
574 direction: 1,
575 value_changed_at_secs: now - 10.0,
576 menu_open: false,
577 highlight_seeded: false,
578 bump_dir: 0,
579 bump_at_secs: now - 10.0,
580 limit_flash_until_secs: f64::NEG_INFINITY,
581 control_hovered: false,
582 currency_btn_hovered: false,
583 pressed_chip: None,
584 touched: false,
585 control_bounds: Rc::new(RefCell::new(None)),
586 menu_bounds: Rc::new(RefCell::new(None)),
587 focus_handle,
588 }
589 }
590}
591
592fn paint_rotated_chevron(cx: f32, cy: f32, angle_deg: f32, color: Hsla, window: &mut Window) {
593 let rad = angle_deg.to_radians();
594 let cos_a = rad.cos();
595 let sin_a = rad.sin();
596 let pts = [(-4.0_f32, -2.0_f32), (0.0, 2.0), (4.0, -2.0)];
597 let mut builder = PathBuilder::stroke(px(1.75));
598 for (i, (lx, ly)) in pts.iter().enumerate() {
599 let rx = cx + lx * cos_a - ly * sin_a;
600 let ry = cy + lx * sin_a + ly * cos_a;
601 let p = point(px(rx), px(ry));
602 if i == 0 {
603 builder.move_to(p);
604 } else {
605 builder.line_to(p);
606 }
607 }
608 if let Ok(path) = builder.build() {
609 window.paint_path(path, color);
610 }
611}
612
613fn paint_scaled_check(
614 cx: f32,
615 cy: f32,
616 scale: f32,
617 opacity: f32,
618 color: Hsla,
619 window: &mut Window,
620) {
621 if opacity <= 0.01 {
622 return;
623 }
624 let pts = [(-4.5_f32, 0.2_f32), (-1.4, 3.3), (4.8, -3.2)];
625 let mut builder = PathBuilder::stroke(px(1.75));
626 for (i, (lx, ly)) in pts.iter().enumerate() {
627 let p = point(px(cx + lx * scale), px(cy + ly * scale));
628 if i == 0 {
629 builder.move_to(p);
630 } else {
631 builder.line_to(p);
632 }
633 }
634 let c = Hsla {
635 a: color.a * opacity.clamp(0.0, 1.0),
636 ..color
637 };
638 if let Ok(path) = builder.build() {
639 window.paint_path(path, c);
640 }
641}
642
643#[derive(IntoElement)]
646pub struct MoneyInput {
647 id: ElementId,
648 label: SharedString,
649 hide_label: bool,
650 value: Option<Option<i64>>,
651 default_value: Option<i64>,
652 currency: Option<SharedString>,
653 default_currency: SharedString,
654 currencies: Vec<SharedString>,
655 min: Option<i64>,
656 max: Option<i64>,
657 quick_add: Vec<i64>,
658 step: Option<i64>,
659 description: Option<SharedString>,
660 error: Option<SharedString>,
661 disabled: bool,
662 width: Option<Pixels>,
663 on_value_change: Option<MoneyValueChangeHandler>,
664 on_currency_change: Option<MoneyCurrencyChangeHandler>,
665}
666
667impl MoneyInput {
668 pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
669 Self {
670 id: id.into(),
671 label: label.into(),
672 hide_label: false,
673 value: None,
674 default_value: None,
675 currency: None,
676 default_currency: "USD".into(),
677 currencies: vec![
678 "USD".into(),
679 "EUR".into(),
680 "GBP".into(),
681 "JPY".into(),
682 "CNY".into(),
683 "CAD".into(),
684 "AUD".into(),
685 "CHF".into(),
686 "INR".into(),
687 "HKD".into(),
688 "SGD".into(),
689 "KRW".into(),
690 "SEK".into(),
691 "NZD".into(),
692 "MXN".into(),
693 "BRL".into(),
694 ],
695 min: None,
696 max: None,
697 quick_add: vec![10, 50, 100],
698 step: None,
699 description: None,
700 error: None,
701 disabled: false,
702 width: None,
703 on_value_change: None,
704 on_currency_change: None,
705 }
706 }
707
708 pub fn hide_label(mut self, hide: bool) -> Self {
709 self.hide_label = hide;
710 self
711 }
712
713 pub fn value(mut self, minor: Option<i64>) -> Self {
714 self.value = Some(minor);
715 self
716 }
717
718 pub fn default_value(mut self, minor: Option<i64>) -> Self {
719 self.default_value = minor;
720 self
721 }
722
723 pub fn currency(mut self, code: impl Into<SharedString>) -> Self {
724 self.currency = Some(code.into());
725 self
726 }
727
728 pub fn default_currency(mut self, code: impl Into<SharedString>) -> Self {
729 self.default_currency = code.into();
730 self
731 }
732
733 pub fn currencies<I, S>(mut self, codes: I) -> Self
734 where
735 I: IntoIterator<Item = S>,
736 S: Into<SharedString>,
737 {
738 self.currencies = codes.into_iter().map(Into::into).collect();
739 self
740 }
741
742 pub fn min(mut self, min_minor: i64) -> Self {
743 self.min = Some(min_minor);
744 self
745 }
746
747 pub fn max(mut self, max_minor: i64) -> Self {
748 self.max = Some(max_minor);
749 self
750 }
751
752 pub fn quick_add<I>(mut self, amounts_major: I) -> Self
753 where
754 I: IntoIterator<Item = i64>,
755 {
756 self.quick_add = amounts_major.into_iter().filter(|&a| a > 0).collect();
757 self
758 }
759
760 pub fn step(mut self, step_minor: i64) -> Self {
761 self.step = Some(step_minor.max(1));
762 self
763 }
764
765 pub fn description(mut self, description: impl Into<SharedString>) -> Self {
766 self.description = Some(description.into());
767 self
768 }
769
770 pub fn error(mut self, error: impl Into<SharedString>) -> Self {
771 self.error = Some(error.into());
772 self
773 }
774
775 pub fn disabled(mut self, disabled: bool) -> Self {
776 self.disabled = disabled;
777 self
778 }
779
780 pub fn width(mut self, width: impl Into<Pixels>) -> Self {
781 self.width = Some(width.into());
782 self
783 }
784
785 pub fn on_value_change(
786 mut self,
787 handler: impl Fn(&MoneyValueEvent, &mut Window, &mut App) + 'static,
788 ) -> Self {
789 self.on_value_change = Some(Rc::new(handler));
790 self
791 }
792
793 pub fn on_currency_change(
794 mut self,
795 handler: impl Fn(&SharedString, &mut Window, &mut App) + 'static,
796 ) -> Self {
797 self.on_currency_change = Some(Rc::new(handler));
798 self
799 }
800}
801
802fn build_money_details(minor: Option<i64>, info: &MoneyCurrencyInfo) -> MoneyInputDetails {
803 let scale = pow10_i64(info.digits) as f64;
804 MoneyInputDetails {
805 currency: info.code.clone(),
806 major: minor.map(|m| (m as f64) / scale),
807 formatted: minor
808 .map(|m| SharedString::from(format_money_minor(m, info)))
809 .unwrap_or_default(),
810 }
811}
812
813impl RenderOnce for MoneyInput {
814 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
815 let theme = cx.arc_theme().clone();
816 let colors = theme.colors;
817 let motion = theme.motion;
818 let reduced = is_reduced_motion(cx);
819 let now = motion_now(cx);
820
821 let init_code = self
822 .currency
823 .clone()
824 .unwrap_or_else(|| self.default_currency.clone());
825 let init_info = money_currency_info(&init_code);
826 let init_minor = self.value.unwrap_or(self.default_value);
827 let init_draft = money_minor_to_draft(init_minor, init_info.digits);
828
829 let state_id =
830 ElementId::NamedChild(self.id.clone().into(), "__arc-money-input-state".into());
831 let internal = window.use_keyed_state(state_id, cx, |_, cx| {
832 MoneyInputInternal::new(
833 init_code.clone(),
834 init_draft,
835 self.value,
836 now,
837 cx.focus_handle(),
838 )
839 });
840
841 let code = self
842 .currency
843 .clone()
844 .unwrap_or_else(|| internal.read(cx).uncontrolled_currency.clone());
845 let info = money_currency_info(&code);
846 let step_minor = self.step.unwrap_or_else(|| pow10_i64(info.digits));
847
848 if self.value != internal.read(cx).seen_external_value {
850 let cur_minor = money_draft_to_minor(&internal.read(cx).draft, info.digits);
851 internal.update(cx, |s, _| {
852 s.seen_external_value = self.value;
853 if let Some(ext_minor) = self.value
854 && ext_minor != cur_minor
855 {
856 s.direction = if ext_minor.unwrap_or(0) >= cur_minor.unwrap_or(0) {
857 1
858 } else {
859 -1
860 };
861 s.draft = money_minor_to_draft(ext_minor, info.digits);
862 s.source = MoneyChangeSource::External;
863 s.value_changed_at_secs = now;
864 }
865 });
866 }
867
868 let snap = internal.read(cx).clone();
869 let minor = money_draft_to_minor(&snap.draft, info.digits);
870 let is_focused = snap.focus_handle.is_focused(window);
871 let menu_open = snap.menu_open && !self.disabled;
872
873 let display_draft = if info.digits > 0 && snap.source != MoneyChangeSource::Type {
874 let zero_frac = format!(".{}", "0".repeat(info.digits));
875 if let Some(int_only) = snap.draft.strip_suffix(&zero_frac)
876 && !int_only.is_empty()
877 {
878 int_only.to_string()
879 } else {
880 snap.draft.clone()
881 }
882 } else {
883 snap.draft.clone()
884 };
885 let parts = money_parts_of(&display_draft, info.digits);
886 let currency_options: Vec<MoneyCurrencyInfo> = if self.currencies.is_empty() {
887 vec![info.clone()]
888 } else {
889 self.currencies
890 .iter()
891 .map(|c| money_currency_info(c))
892 .collect()
893 };
894 let can_switch_currency = currency_options.len() > 1;
895
896 let bump_elapsed = (now - snap.bump_at_secs).max(0.0);
898 let bump_x = money_bump_x_offset(bump_elapsed, snap.bump_dir, reduced);
899 if !reduced && snap.bump_dir != 0 && bump_elapsed < MONEY_KICK_SETTLE_SECS {
900 window.request_animation_frame();
901 }
902 let flash_active = now < snap.limit_flash_until_secs;
903 if flash_active {
904 window.request_animation_frame();
905 }
906
907 let total_chars = parts.len() + info.symbol.chars().count();
909 let display_font_px = if total_chars <= 10 {
910 30.0_f32
911 } else if total_chars <= 14 {
912 24.0_f32
913 } else {
914 19.5_f32
915 };
916
917 let instant = snap.source == MoneyChangeSource::Type;
919 let val_elapsed = (now - snap.value_changed_at_secs).max(0.0);
920 let (glyph_op, glyph_y) = if instant || val_elapsed >= 0.22 {
921 (1.0_f32, 0.0_f32)
922 } else {
923 window.request_animation_frame();
924 let t = (val_elapsed / 0.20).clamp(0.0, 1.0) as f32;
925 let e = if reduced {
926 t
927 } else {
928 CubicBezier::new(0.16, 1.0, 0.3, 1.0).sample(t)
929 };
930 let blur = BlurFallback::evaluate(px(4.0 * (1.0 - e)), reduced);
931 let op = (e * blur.opacity_multiplier).clamp(0.0, 1.0);
932 let y = if reduced {
933 0.0
934 } else {
935 (snap.direction as f32) * (0.45 * display_font_px) * (1.0 - e)
936 };
937 (op, y)
938 };
939
940 let sym_natural_w = (info.symbol.chars().count() as f32) * (display_font_px * 0.62) + 2.0;
942 let sym_w = if reduced {
943 sym_natural_w
944 } else {
945 arc_spring(
946 (self.id.clone(), "sym-w"),
947 sym_natural_w,
948 motion.spring.morph,
949 window,
950 cx,
951 )
952 };
953 let sym_elapsed = (now - snap.symbol_changed_at_secs).max(0.0);
954 let (sym_op, sym_y) = if sym_elapsed >= 0.22 {
955 (1.0_f32, 0.0_f32)
956 } else {
957 window.request_animation_frame();
958 let t = (sym_elapsed / 0.20).clamp(0.0, 1.0) as f32;
959 let e = if reduced {
960 t
961 } else {
962 CubicBezier::new(0.16, 1.0, 0.3, 1.0).sample(t)
963 };
964 let blur = BlurFallback::evaluate(px(4.0 * (1.0 - e)), reduced);
965 (
966 (e * blur.opacity_multiplier).clamp(0.0, 1.0),
967 if reduced {
968 0.0
969 } else {
970 0.35 * display_font_px * (1.0 - e)
971 },
972 )
973 };
974
975 let make_symbol_el = || {
976 div()
977 .w(px(sym_w))
978 .overflow_hidden()
979 .mt(px(sym_y))
980 .opacity(sym_op)
981 .text_size(px(display_font_px))
982 .font_medium()
983 .text_color(colors.text_secondary)
984 .child(info.symbol.clone())
985 };
986
987 let ghost_color = oklab_mix(colors.text_muted, colors.surface, 0.45);
988 let show_caret = is_focused && !menu_open && !self.disabled;
989 let last_non_ghost_idx = parts.iter().rposition(|p| !p.ghost);
990 let make_caret_el = || {
991 div()
992 .mx(px(1.5))
993 .w(px(2.0))
994 .h(px(display_font_px * 0.72))
995 .rounded_full()
996 .bg(colors.accent)
997 .into_any_element()
998 };
999 let mut part_els = Vec::with_capacity(parts.len() + 1);
1000 if show_caret && last_non_ghost_idx.is_none() {
1001 part_els.push(make_caret_el());
1002 }
1003 for (idx, part) in parts.into_iter().enumerate() {
1004 let col_fg = if part.ghost {
1005 ghost_color
1006 } else {
1007 colors.foreground
1008 };
1009 let is_fraction_or_int = part.key.starts_with('i') || part.key.starts_with('f');
1010 let dy = if is_fraction_or_int && !part.ghost {
1011 glyph_y
1012 } else {
1013 0.0
1014 };
1015 let op = if is_fraction_or_int && !part.ghost {
1016 glyph_op
1017 } else {
1018 1.0
1019 };
1020
1021 part_els.push(
1022 div()
1023 .id(ElementId::NamedChild(self.id.clone().into(), part.key))
1024 .mt(px(dy))
1025 .opacity(op)
1026 .text_size(px(display_font_px))
1027 .font_medium()
1028 .text_color(col_fg)
1029 .child(SharedString::from(part.ch.to_string()))
1030 .into_any_element(),
1031 );
1032 if show_caret && last_non_ghost_idx == Some(idx) {
1033 part_els.push(make_caret_el());
1034 }
1035 }
1036
1037 let glide_spec = money_glide_spring();
1039 let chevron_deg = if reduced {
1040 if menu_open { 180.0 } else { 0.0 }
1041 } else {
1042 arc_spring(
1043 (self.id.clone(), "chevron-deg"),
1044 if menu_open { 180.0 } else { 0.0 },
1045 glide_spec,
1046 window,
1047 cx,
1048 )
1049 };
1050
1051 let menu_presence = ArcPresence::new((self.id.clone(), "menu-presence"), menu_open)
1053 .animate_initial(false)
1054 .config(ArcPresenceConfig {
1055 enter_duration: motion.duration.fast,
1056 exit_duration: motion.duration.instant,
1057 enter_ease: motion.ease.enter,
1058 exit_ease: motion.ease.standard,
1059 fade_on_reduced_motion: true,
1060 })
1061 .sample(window, cx);
1062
1063 let control_bounds_ref = snap.control_bounds.clone();
1064 let control_bounds_outside = snap.control_bounds.clone();
1065 let menu_bounds_outside = snap.menu_bounds.clone();
1066 let internal_outside = internal.clone();
1067 let control_probe = canvas(
1068 move |rect, _, _| {
1069 *control_bounds_ref.borrow_mut() = Some(rect);
1070 },
1071 move |_, _, window, _| {
1072 if menu_open {
1073 let c_ref = control_bounds_outside.clone();
1074 let m_ref = menu_bounds_outside.clone();
1075 let st = internal_outside.clone();
1076 window.on_mouse_event(move |event: &MouseDownEvent, phase, window, cx| {
1077 if !phase.bubble() {
1078 return;
1079 }
1080 let in_ctrl = c_ref.borrow().is_some_and(|b| b.contains(&event.position));
1081 let in_menu = m_ref.borrow().is_some_and(|b| b.contains(&event.position));
1082 if !in_ctrl && !in_menu {
1083 st.update(cx, |s, _| {
1084 s.menu_open = false;
1085 s.highlight_seeded = false;
1086 });
1087 window.refresh();
1088 }
1089 });
1090 }
1091 },
1092 )
1093 .absolute()
1094 .inset_0();
1095
1096 let disabled = self.disabled;
1097 let chevron_color = colors.text_muted;
1098
1099 let currency_slot = if can_switch_currency {
1101 let int_c_hover = internal.clone();
1102 let int_c_click = internal.clone();
1103 let cur_code_for_open = code.clone();
1104 let focus_for_menu = snap.focus_handle.clone();
1105 let btn_bg = if menu_open || (snap.currency_btn_hovered && !disabled) {
1106 colors.surface_muted
1107 } else {
1108 Hsla::transparent_black()
1109 };
1110
1111 let trigger_btn = BaseButton::new(ElementId::NamedChild(
1112 self.id.clone().into(),
1113 "currency-button".into(),
1114 ))
1115 .accessibility_label(SharedString::from(format!("Currency, {}", info.name)))
1116 .disabled(disabled)
1117 .on_click(move |_, window, cx| {
1118 if disabled {
1119 return;
1120 }
1121 window.focus(&focus_for_menu, cx);
1122 int_c_click.update(cx, |s, _| {
1123 s.menu_open = !s.menu_open;
1124 if s.menu_open {
1125 s.active_code = cur_code_for_open.clone();
1126 s.highlight_seeded = false;
1127 } else {
1128 s.highlight_seeded = false;
1129 }
1130 });
1131 window.refresh();
1132 })
1133 .h(px(36.0))
1134 .pl(px(12.0))
1135 .pr(px(8.0))
1136 .flex()
1137 .flex_row()
1138 .items_center()
1139 .gap(px(4.0))
1140 .rounded(Radii::PILL)
1141 .bg(btn_bg)
1142 .text_size(Typography::TEXT_SM)
1143 .font_medium()
1144 .text_color(colors.foreground)
1145 .when(!disabled, |this| this.cursor_pointer())
1146 .on_hover(move |hovered, window, cx| {
1147 int_c_hover.update(cx, |s, _| s.currency_btn_hovered = *hovered);
1148 window.refresh();
1149 })
1150 .child(code.clone())
1151 .child(
1152 div().size(px(16.0)).child(
1153 canvas(
1154 |_, _, _| {},
1155 move |rect, _, window, _| {
1156 let cx_pt = f32::from(rect.origin.x + rect.size.width * 0.5);
1157 let cy_pt = f32::from(rect.origin.y + rect.size.height * 0.5);
1158 paint_rotated_chevron(cx_pt, cy_pt, chevron_deg, chevron_color, window);
1159 },
1160 )
1161 .size_full(),
1162 ),
1163 );
1164
1165 let menu_el = if menu_presence.should_render() {
1166 let p = menu_presence.progress.clamp(0.0, 1.0);
1167 let menu_y = if reduced { 0.0 } else { -4.0 * (1.0 - p) };
1168 let active_idx = currency_options
1169 .iter()
1170 .position(|o| o.code == snap.active_code)
1171 .unwrap_or(0);
1172 let target_hy = active_idx as f32 * 38.0;
1174 let pill_y = if reduced || !snap.highlight_seeded {
1175 let _ = arc_spring_with_options(
1176 (self.id.clone(), "hi-y"),
1177 target_hy,
1178 SpringOptions::new(glide_spec).with_initial_value(target_hy),
1179 window,
1180 cx,
1181 );
1182 if menu_open && !snap.highlight_seeded {
1183 internal.update(cx, |s, _| s.highlight_seeded = true);
1184 }
1185 target_hy
1186 } else {
1187 arc_spring((self.id.clone(), "hi-y"), target_hy, glide_spec, window, cx)
1188 };
1189 let hi_bg = oklab_mix(colors.foreground, colors.surface_raised, 0.065);
1190
1191 let menu_bounds_ref = snap.menu_bounds.clone();
1192 let menu_probe = canvas(
1193 move |rect, _, _| {
1194 *menu_bounds_ref.borrow_mut() = Some(rect);
1195 },
1196 |_, _, _, _| {},
1197 )
1198 .absolute()
1199 .inset_0();
1200
1201 let option_rows = currency_options
1202 .iter()
1203 .map(|opt| {
1204 let is_selected = opt.code == code;
1205 let is_active = opt.code == snap.active_code;
1206 let check_op = arc_transition(
1207 (self.id.clone(), format!("cur-chk-op-{}", opt.code)),
1208 if is_selected { 1.0 } else { 0.0 },
1209 if reduced {
1210 Duration::ZERO
1211 } else {
1212 motion.duration.fast
1213 },
1214 motion.ease.standard,
1215 window,
1216 cx,
1217 );
1218 let check_scale = if reduced {
1219 if is_selected { 1.0 } else { 0.6 }
1220 } else {
1221 arc_spring(
1222 (self.id.clone(), format!("cur-chk-sc-{}", opt.code)),
1223 if is_selected { 1.0 } else { 0.6 },
1224 glide_spec,
1225 window,
1226 cx,
1227 )
1228 };
1229
1230 let row_fg = if is_active || is_selected {
1231 colors.foreground
1232 } else {
1233 colors.text_secondary
1234 };
1235 let check_color = colors.foreground;
1236 let int_hi = internal.clone();
1237 let int_choose = internal.clone();
1238 let on_v_change = self.on_value_change.clone();
1239 let on_c_change = self.on_currency_change.clone();
1240 let cur_sym = info.symbol.clone();
1241 let opt_clone = opt.clone();
1242 let code_hi = opt.code.clone();
1243
1244 div()
1245 .id(ElementId::NamedChild(
1246 self.id.clone().into(),
1247 SharedString::from(format!("currency-{}", opt.code)),
1248 ))
1249 .test_support()
1250 .role(Role::ListBoxOption)
1251 .aria_label(opt.name.clone())
1252 .w_full()
1253 .flex_none()
1254 .h(px(36.0))
1255 .min_h(px(36.0))
1256 .px(px(10.0))
1257 .flex()
1258 .flex_row()
1259 .items_center()
1260 .gap(px(10.0))
1261 .rounded(Radii::CONTROL)
1262 .text_size(Typography::TEXT_SM)
1263 .text_color(row_fg)
1264 .cursor_pointer()
1265 .on_hover(move |hovered, window, cx| {
1266 if *hovered {
1267 int_hi.update(cx, |s, _| {
1268 s.active_code = code_hi.clone();
1269 });
1270 window.refresh();
1271 }
1272 })
1273 .on_click(move |_, window, cx| {
1274 let t_now = motion_now(cx);
1275 let next_info = opt_clone.clone();
1276 let cur_draft = int_choose.read(cx).draft.clone();
1277 let converted = money_convert_draft(&cur_draft, next_info.digits);
1278 let next_minor = money_draft_to_minor(&converted, next_info.digits);
1279 let settled = money_minor_to_draft(next_minor, next_info.digits);
1280 int_choose.update(cx, |s, _| {
1281 s.menu_open = false;
1282 s.highlight_seeded = false;
1283 if next_info.code != s.uncontrolled_currency {
1284 s.previous_symbol = Some(cur_sym.clone());
1285 s.symbol_changed_at_secs = t_now;
1286 s.uncontrolled_currency = next_info.code.clone();
1287 }
1288 s.draft = settled;
1289 s.source = MoneyChangeSource::External;
1290 });
1291 if let Some(cb_c) = &on_c_change {
1292 cb_c(&next_info.code, window, cx);
1293 }
1294 if let Some(cb_v) = &on_v_change {
1295 let event = MoneyValueEvent {
1296 minor: next_minor,
1297 details: build_money_details(next_minor, &next_info),
1298 };
1299 cb_v(&event, window, cx);
1300 }
1301 window.refresh();
1302 })
1303 .child(
1304 div()
1305 .w(px(22.0))
1306 .flex_none()
1307 .text_color(colors.text_muted)
1308 .child(opt.symbol.clone()),
1309 )
1310 .child(div().flex_none().font_medium().child(opt.code.clone()))
1311 .child(
1312 div()
1313 .flex_1()
1314 .min_w_0()
1315 .text_size(Typography::TEXT_XS)
1316 .text_color(colors.text_muted)
1317 .truncate()
1318 .child(opt.name.clone()),
1319 )
1320 .child(
1321 div().size(px(16.0)).flex_none().child(
1322 canvas(
1323 |_, _, _| {},
1324 move |rect, _, window, _| {
1325 let cx_pt =
1326 f32::from(rect.origin.x + rect.size.width * 0.5);
1327 let cy_pt =
1328 f32::from(rect.origin.y + rect.size.height * 0.5);
1329 paint_scaled_check(
1330 cx_pt,
1331 cy_pt,
1332 check_scale,
1333 check_op,
1334 check_color,
1335 window,
1336 );
1337 },
1338 )
1339 .size_full(),
1340 ),
1341 )
1342 .into_any_element()
1343 })
1344 .collect::<Vec<_>>();
1345
1346 Some(
1349 deferred(
1350 div()
1351 .id(ElementId::NamedChild(
1352 self.id.clone().into(),
1353 "currency-menu".into(),
1354 ))
1355 .test_support()
1356 .role(Role::ListBox)
1357 .absolute()
1358 .top_full()
1359 .right(px(-8.0))
1360 .mt(px(28.0 + menu_y))
1361 .w(px(256.0))
1362 .p(px(6.0))
1363 .rounded(Radii::PANEL)
1364 .border_1()
1365 .border_color(colors.border)
1366 .bg(colors.surface_raised)
1367 .shadow(Shadows::floating(theme.mode))
1368 .opacity(p)
1369 .overflow_hidden()
1370 .child(menu_probe)
1371 .child(
1372 div()
1373 .id(ElementId::NamedChild(
1374 self.id.clone().into(),
1375 "currency-list".into(),
1376 ))
1377 .relative()
1378 .w_full()
1379 .max_h(px(288.0))
1380 .overflow_y_scroll()
1381 .on_scroll(|_, _, cx| cx.stop_propagation())
1382 .flex()
1383 .flex_col()
1384 .gap(px(2.0))
1385 .child(
1386 div()
1387 .absolute()
1388 .left_0()
1389 .right_0()
1390 .top(px(pill_y))
1391 .h(px(36.0))
1392 .rounded(Radii::CONTROL)
1393 .bg(hi_bg),
1394 )
1395 .children(option_rows),
1396 ),
1397 )
1398 .with_priority(25),
1399 )
1400 } else {
1401 None
1402 };
1403
1404 div()
1405 .relative()
1406 .flex_none()
1407 .child(trigger_btn)
1408 .when_some(menu_el, |this, m| this.child(m))
1409 .into_any_element()
1410 } else {
1411 div()
1412 .px(px(10.0))
1413 .flex_none()
1414 .text_size(Typography::TEXT_SM)
1415 .font_medium()
1416 .text_color(colors.text_secondary)
1417 .child(code.clone())
1418 .into_any_element()
1419 };
1420
1421 let range_text: Option<SharedString> = match (self.min, self.max) {
1423 (Some(lo), Some(hi)) => Some(SharedString::from(format!(
1424 "{} to {}",
1425 format_money_minor(lo, &info),
1426 format_money_minor(hi, &info)
1427 ))),
1428 (None, Some(hi)) => Some(SharedString::from(format!(
1429 "Up to {}",
1430 format_money_minor(hi, &info)
1431 ))),
1432 (Some(lo), None) => Some(SharedString::from(format!(
1433 "At least {}",
1434 format_money_minor(lo, &info)
1435 ))),
1436 (None, None) => None,
1437 };
1438
1439 let below_min = minor.is_some_and(|m| self.min.is_some_and(|lo| m < lo));
1440 let above_max = minor.is_some_and(|m| self.max.is_some_and(|hi| m > hi));
1441 let built_in_error: Option<SharedString> =
1442 if snap.touched && !is_focused && (below_min || above_max) {
1443 if below_min {
1444 Some(SharedString::from(format!(
1445 "The minimum is {}",
1446 format_money_minor(self.min.unwrap_or(0), &info)
1447 )))
1448 } else {
1449 Some(SharedString::from(format!(
1450 "The maximum is {}",
1451 format_money_minor(self.max.unwrap_or(0), &info)
1452 )))
1453 }
1454 } else {
1455 None
1456 };
1457 let effective_error = self.error.clone().or(built_in_error);
1458 let is_invalid = effective_error.is_some();
1459
1460 let control_border = if is_invalid {
1461 colors.danger
1462 } else if !disabled && (is_focused || snap.control_hovered) {
1463 colors.foreground
1464 } else {
1465 colors.border_strong
1466 };
1467
1468 let int_ctrl_hover = internal.clone();
1469 let int_focus_wrap = internal.clone();
1470 let int_key = internal.clone();
1471 let info_for_key = info.clone();
1472 let options_for_key = currency_options;
1473 let min_opt = self.min;
1474 let max_opt = self.max;
1475 let on_v_change_key = self.on_value_change.clone();
1476 let on_c_change_key = self.on_currency_change.clone();
1477 let focus_handle = snap.focus_handle.clone();
1478 let focus_for_wrap = snap.focus_handle;
1479
1480 let control = div()
1481 .id(ElementId::NamedChild(
1482 self.id.clone().into(),
1483 "control".into(),
1484 ))
1485 .test_support()
1486 .role(Role::SpinButton)
1487 .track_focus(&focus_handle)
1488 .on_hover(move |hovered, window, cx| {
1489 int_ctrl_hover.update(cx, |s, _| s.control_hovered = *hovered);
1490 window.refresh();
1491 })
1492 .on_key_down(move |event: &KeyDownEvent, window, cx| {
1493 if disabled {
1494 return;
1495 }
1496 let t_now = motion_now(cx);
1497
1498 if int_key.read(cx).menu_open {
1500 let cur_active = int_key.read(cx).active_code.clone();
1501 let at = options_for_key
1502 .iter()
1503 .position(|o| o.code == cur_active)
1504 .unwrap_or(0);
1505 match event.keystroke.key.as_str() {
1506 "down" | "arrowdown" => {
1507 let next_idx = (at + 1).min(options_for_key.len() - 1);
1508 let next_c = options_for_key[next_idx].code.clone();
1509 int_key.update(cx, |s, _| s.active_code = next_c);
1510 window.refresh();
1511 return;
1512 }
1513 "up" | "arrowup" => {
1514 let prev_idx = at.saturating_sub(1);
1515 let prev_c = options_for_key[prev_idx].code.clone();
1516 int_key.update(cx, |s, _| s.active_code = prev_c);
1517 window.refresh();
1518 return;
1519 }
1520 "escape" => {
1521 int_key.update(cx, |s, _| {
1522 s.menu_open = false;
1523 s.highlight_seeded = false;
1524 });
1525 window.refresh();
1526 return;
1527 }
1528 "enter" | " " | "space" => {
1529 let chosen = options_for_key[at].clone();
1530 let cur_draft = int_key.read(cx).draft.clone();
1531 let converted = money_convert_draft(&cur_draft, chosen.digits);
1532 let next_m = money_draft_to_minor(&converted, chosen.digits);
1533 let settled = money_minor_to_draft(next_m, chosen.digits);
1534 let old_sym = info_for_key.symbol.clone();
1535 int_key.update(cx, |s, _| {
1536 s.menu_open = false;
1537 s.highlight_seeded = false;
1538 if chosen.code != s.uncontrolled_currency {
1539 s.previous_symbol = Some(old_sym);
1540 s.symbol_changed_at_secs = t_now;
1541 s.uncontrolled_currency = chosen.code.clone();
1542 }
1543 s.draft = settled;
1544 s.source = MoneyChangeSource::External;
1545 });
1546 if let Some(cb_c) = &on_c_change_key {
1547 cb_c(&chosen.code, window, cx);
1548 }
1549 if let Some(cb_v) = &on_v_change_key {
1550 let event = MoneyValueEvent {
1551 minor: next_m,
1552 details: build_money_details(next_m, &chosen),
1553 };
1554 cb_v(&event, window, cx);
1555 }
1556 window.refresh();
1557 return;
1558 }
1559 _ => {}
1560 }
1561 }
1562
1563 let (cur_draft_raw, cur_source) = {
1564 let s = int_key.read(cx);
1565 (s.draft.clone(), s.source)
1566 };
1567 let cur_draft = if cur_source != MoneyChangeSource::Type
1572 && let Some((w, f)) = cur_draft_raw.split_once('.')
1573 && f.chars().all(|c| c == '0')
1574 {
1575 if w == "0" {
1576 String::new()
1577 } else {
1578 w.to_string()
1579 }
1580 } else {
1581 cur_draft_raw
1582 };
1583 let cur_minor = money_draft_to_minor(&cur_draft, info_for_key.digits);
1584 let shift = event.keystroke.modifiers.shift;
1585
1586 match event.keystroke.key.as_str() {
1587 "up" | "arrowup" | "down" | "arrowdown" | "pageup" | "pagedown" => {
1588 let mult: i64 = match event.keystroke.key.as_str() {
1589 "up" | "arrowup" => {
1590 if shift {
1591 10
1592 } else {
1593 1
1594 }
1595 }
1596 "down" | "arrowdown" => {
1597 if shift {
1598 -10
1599 } else {
1600 -1
1601 }
1602 }
1603 "pageup" => 10,
1604 "pagedown" => -10,
1605 _ => 1,
1606 };
1607 let delta = mult.saturating_mul(step_minor);
1608 let from = cur_minor.unwrap_or(0);
1609 let floor = min_opt.unwrap_or(0);
1610 let ceiling = max_opt.unwrap_or(i64::MAX / 2);
1611 let mut next_m = from.saturating_add(delta);
1612 let mut refused_dir: i8 = 0;
1613 if next_m > ceiling {
1614 refused_dir = 1;
1615 next_m = ceiling;
1616 } else if next_m < floor {
1617 refused_dir = -1;
1618 next_m = floor;
1619 }
1620 let next_draft = money_minor_to_draft(Some(next_m), info_for_key.digits);
1621 int_key.update(cx, |s, _| {
1622 s.touched = true;
1623 if refused_dir != 0 {
1624 s.bump_dir = refused_dir;
1625 s.bump_at_secs = t_now;
1626 s.limit_flash_until_secs = t_now + MONEY_LIMIT_FLASH_SECS;
1627 }
1628 if Some(next_m) != cur_minor {
1629 s.direction = if next_m >= from { 1 } else { -1 };
1630 s.draft = next_draft;
1631 s.source = MoneyChangeSource::Key;
1632 s.value_changed_at_secs = t_now;
1633 }
1634 });
1635 if Some(next_m) != cur_minor
1636 && let Some(cb) = &on_v_change_key
1637 {
1638 let event = MoneyValueEvent {
1639 minor: Some(next_m),
1640 details: build_money_details(Some(next_m), &info_for_key),
1641 };
1642 cb(&event, window, cx);
1643 }
1644 window.refresh();
1645 }
1646 "backspace" => {
1647 if !cur_draft.is_empty() {
1648 let mut next_raw = cur_draft.clone();
1649 next_raw.pop();
1650 if let Some(san) = sanitize_money_draft(&next_raw, info_for_key.digits)
1651 {
1652 let next_m = money_draft_to_minor(&san, info_for_key.digits);
1653 int_key.update(cx, |s, _| {
1654 s.touched = true;
1655 s.draft = san;
1656 s.source = MoneyChangeSource::Type;
1657 });
1658 if next_m != cur_minor
1659 && let Some(cb) = &on_v_change_key
1660 {
1661 let event = MoneyValueEvent {
1662 minor: next_m,
1663 details: build_money_details(next_m, &info_for_key),
1664 };
1665 cb(&event, window, cx);
1666 }
1667 window.refresh();
1668 }
1669 }
1670 }
1671 "enter" => {
1672 let settled = money_minor_to_draft(cur_minor, info_for_key.digits);
1673 int_key.update(cx, |s, _| {
1674 s.touched = true;
1675 s.draft = settled;
1676 });
1677 window.refresh();
1678 }
1679 "v" if event.keystroke.modifiers.control
1680 || event.keystroke.modifiers.platform =>
1681 {
1682 let pasted = cx
1686 .read_from_clipboard()
1687 .and_then(|item| item.text())
1688 .unwrap_or_default();
1689 if let Some(parsed) = money_parse_pasted(&pasted, info_for_key.digits)
1690 && let Some(san) = sanitize_money_draft(&parsed, info_for_key.digits)
1691 {
1692 let next_m = money_draft_to_minor(&san, info_for_key.digits);
1693 if let Some(hi) = max_opt
1694 && let Some(nm) = next_m
1695 && nm > hi
1696 {
1697 int_key.update(cx, |s, _| {
1698 s.bump_dir = 1;
1699 s.bump_at_secs = t_now;
1700 s.limit_flash_until_secs = t_now + MONEY_LIMIT_FLASH_SECS;
1701 });
1702 window.refresh();
1703 return;
1704 }
1705 int_key.update(cx, |s, _| {
1706 s.touched = true;
1707 s.draft = san;
1708 s.source = MoneyChangeSource::Type;
1709 });
1710 if next_m != cur_minor
1711 && let Some(cb) = &on_v_change_key
1712 {
1713 let event = MoneyValueEvent {
1714 minor: next_m,
1715 details: build_money_details(next_m, &info_for_key),
1716 };
1717 cb(&event, window, cx);
1718 }
1719 window.refresh();
1720 }
1721 }
1722 k => {
1723 let ch_opt = event
1724 .keystroke
1725 .key_char
1726 .as_deref()
1727 .and_then(|kc| (kc.len() == 1).then(|| kc.chars().next()).flatten())
1728 .or_else(|| (k.len() == 1).then(|| k.chars().next()).flatten());
1729 let ch = ch_opt.unwrap_or(' ');
1730 if !event.keystroke.modifiers.control
1731 && !event.keystroke.modifiers.platform
1732 && (ch.is_ascii_digit() || (ch == '.' && info_for_key.digits > 0))
1733 {
1734 let candidate = format!("{cur_draft}{ch}");
1735 let Some(san) = sanitize_money_draft(&candidate, info_for_key.digits)
1736 else {
1737 return;
1738 };
1739 let next_m = money_draft_to_minor(&san, info_for_key.digits);
1740 if let Some(hi) = max_opt
1741 && let Some(nm) = next_m
1742 && nm > hi
1743 {
1744 int_key.update(cx, |s, _| {
1745 s.bump_dir = 1;
1746 s.bump_at_secs = t_now;
1747 s.limit_flash_until_secs = t_now + MONEY_LIMIT_FLASH_SECS;
1748 });
1749 window.refresh();
1750 return;
1751 }
1752 int_key.update(cx, |s, _| {
1753 s.touched = true;
1754 s.draft = san;
1755 s.source = MoneyChangeSource::Type;
1756 });
1757 if next_m != cur_minor
1758 && let Some(cb) = &on_v_change_key
1759 {
1760 let event = MoneyValueEvent {
1761 minor: next_m,
1762 details: build_money_details(next_m, &info_for_key),
1763 };
1764 cb(&event, window, cx);
1765 }
1766 window.refresh();
1767 }
1768 }
1769 }
1770 })
1771 .relative()
1772 .w_full()
1773 .h(px(76.0))
1774 .pl(px(18.0))
1775 .pr(px(8.0))
1776 .flex()
1777 .flex_row()
1778 .items_center()
1779 .gap(Spacing::S2)
1780 .rounded(Radii::PANEL)
1781 .border_1()
1782 .border_color(control_border)
1783 .bg(if disabled {
1784 colors.surface_muted
1785 } else {
1786 colors.surface
1787 })
1788 .opacity(if disabled { 0.5 } else { 1.0 })
1789 .child(control_probe)
1790 .child(
1791 div()
1792 .id(ElementId::NamedChild(
1793 self.id.clone().into(),
1794 "amount-wrap".into(),
1795 ))
1796 .flex_1()
1797 .min_w_0()
1798 .h_full()
1799 .flex()
1800 .items_center()
1801 .overflow_hidden()
1802 .when(!disabled, |this| {
1803 let focus_down = focus_for_wrap.clone();
1804 this.cursor_pointer().on_mouse_down(
1805 MouseButton::Left,
1806 move |_, window, cx| {
1807 window.focus(&focus_down, cx);
1808 window.refresh();
1809 },
1810 )
1811 })
1812 .on_click(move |_, window, cx| {
1813 if !disabled {
1814 let _ = &int_focus_wrap;
1815 window.focus(&focus_for_wrap, cx);
1816 window.refresh();
1817 }
1818 })
1819 .child(
1820 div()
1821 .ml(px(bump_x))
1822 .flex()
1823 .flex_row()
1824 .items_center()
1825 .when(info.symbol_is_prefix, |this| {
1826 this.child(div().mr(px(2.0)).child(make_symbol_el()))
1827 })
1828 .children(part_els)
1829 .when(!info.symbol_is_prefix, |this| {
1830 this.child(div().ml(px(5.0)).child(make_symbol_el()))
1831 }),
1832 ),
1833 )
1834 .child(currency_slot);
1835
1836 let show_toolbar = !self.quick_add.is_empty() || range_text.is_some();
1838 let toolbar_el = if show_toolbar {
1839 let chip_buttons = self
1840 .quick_add
1841 .iter()
1842 .copied()
1843 .map(|major_amt| {
1844 let add_minor = major_amt.saturating_mul(pow10_i64(info.digits));
1845 let at_max = self.max.is_some_and(|hi| minor.unwrap_or(0) >= hi);
1846 let is_pressed = snap.pressed_chip == Some(major_amt) && !disabled;
1847 let chip_text = SharedString::from(format!(
1848 "+{}",
1849 format_money_whole_major(major_amt, &info)
1850 ));
1851 let int_down = internal.clone();
1852 let int_up = internal.clone();
1853 let int_out = internal.clone();
1854 let int_click = internal.clone();
1855 let info_for_chip = info.clone();
1856 let on_v_change = self.on_value_change.clone();
1857 let hover_bg = colors.surface_muted;
1858 let hover_fg = colors.foreground;
1859
1860 BaseButton::new(ElementId::NamedChild(
1861 self.id.clone().into(),
1862 SharedString::from(format!("quick-add-{major_amt}")),
1863 ))
1864 .accessibility_label(SharedString::from(format!(
1865 "Add {}",
1866 format_money_whole_major(major_amt, &info)
1867 )))
1868 .disabled(disabled)
1869 .on_click(move |_, window, cx| {
1870 if disabled {
1871 return;
1872 }
1873 let t_now = motion_now(cx);
1874 let cur_draft = int_click.read(cx).draft.clone();
1875 let cur_m = money_draft_to_minor(&cur_draft, info_for_chip.digits);
1876 let from = cur_m.unwrap_or(0);
1877 let floor = min_opt.unwrap_or(0);
1878 let ceiling = max_opt.unwrap_or(i64::MAX / 2);
1879 let mut next_m = from.saturating_add(add_minor);
1880 let mut refused = false;
1881 if next_m > ceiling {
1882 refused = true;
1883 next_m = ceiling;
1884 } else if next_m < floor {
1885 next_m = floor;
1886 }
1887 let next_draft = money_minor_to_draft(Some(next_m), info_for_chip.digits);
1888 int_click.update(cx, |s, _| {
1889 s.pressed_chip = None;
1890 s.touched = true;
1891 if refused {
1892 s.bump_dir = 1;
1893 s.bump_at_secs = t_now;
1894 s.limit_flash_until_secs = t_now + MONEY_LIMIT_FLASH_SECS;
1895 }
1896 if Some(next_m) != cur_m {
1897 s.direction = 1;
1898 s.draft = next_draft;
1899 s.source = MoneyChangeSource::Chip;
1900 s.value_changed_at_secs = t_now;
1901 }
1902 });
1903 if Some(next_m) != cur_m
1904 && let Some(cb) = &on_v_change
1905 {
1906 let event = MoneyValueEvent {
1907 minor: Some(next_m),
1908 details: build_money_details(Some(next_m), &info_for_chip),
1909 };
1910 cb(&event, window, cx);
1911 }
1912 window.refresh();
1913 })
1914 .h(px(if is_pressed && !reduced { 29.0 } else { 30.0 }))
1915 .px(px(12.0))
1916 .flex()
1917 .items_center()
1918 .justify_center()
1919 .rounded(Radii::PILL)
1920 .border_1()
1921 .border_color(colors.border)
1922 .bg(colors.surface)
1923 .opacity(if disabled || at_max { 0.45 } else { 1.0 })
1924 .text_size(Typography::TEXT_XS)
1925 .font_medium()
1926 .text_color(colors.text_secondary)
1927 .when(!disabled && !at_max, |this| {
1928 this.cursor_pointer()
1929 .hover(move |s| s.bg(hover_bg).text_color(hover_fg))
1930 })
1931 .on_mouse_down(MouseButton::Left, move |_, window, cx| {
1932 int_down.update(cx, |s, _| s.pressed_chip = Some(major_amt));
1933 window.refresh();
1934 })
1935 .on_mouse_up(MouseButton::Left, move |_, window, cx| {
1936 int_up.update(cx, |s, _| s.pressed_chip = None);
1937 window.refresh();
1938 })
1939 .on_mouse_up_out(MouseButton::Left, move |_, window, cx| {
1940 int_out.update(cx, |s, _| s.pressed_chip = None);
1941 window.refresh();
1942 })
1943 .child(chip_text)
1944 .into_any_element()
1945 })
1946 .collect::<Vec<_>>();
1947
1948 let range_fg = if flash_active {
1949 colors.warning
1950 } else {
1951 colors.text_muted
1952 };
1953
1954 Some(
1955 div()
1956 .w_full()
1957 .pt(Spacing::S3)
1958 .flex()
1959 .flex_row()
1960 .flex_wrap()
1961 .items_center()
1962 .justify_between()
1963 .gap(Spacing::S2)
1964 .child(
1965 div()
1966 .flex()
1967 .flex_row()
1968 .flex_wrap()
1969 .gap(px(6.0))
1970 .children(chip_buttons),
1971 )
1972 .when_some(range_text, |this, rt| {
1973 this.child(
1974 div()
1975 .text_size(Typography::TEXT_XS)
1976 .text_color(range_fg)
1977 .child(rt),
1978 )
1979 }),
1980 )
1981 } else {
1982 None
1983 };
1984
1985 let msg_id = ElementId::NamedChild(self.id.clone().into(), "message".into());
1986 let msg_text = effective_error.clone().or(self.description);
1987
1988 div()
1989 .id(self.id)
1990 .test_support()
1991 .when_some(self.width, |this, w| this.w(w))
1992 .when(self.width.is_none(), |this| this.w_full())
1993 .flex()
1994 .flex_col()
1995 .when(!self.hide_label, |this| {
1996 this.child(
1997 div()
1998 .mb(Spacing::S2)
1999 .text_size(Typography::TEXT_SM)
2000 .font_medium()
2001 .text_color(colors.foreground)
2002 .child(self.label),
2003 )
2004 })
2005 .child(control)
2006 .when_some(toolbar_el, |this, tb| this.child(tb))
2007 .child(render_field_message(
2008 msg_id, msg_text, is_invalid, window, cx,
2009 ))
2010 }
2011}
2012
2013#[cfg(test)]
2014mod tests {
2015 use arc_motion::{CurveTrace, max_curve_error_pct};
2016 use arc_tokens::{Accent, ThemeMode, install_arc_theme};
2017 use gpui_kit::{ClipboardItem, Context, Render, TestAppContext, test::TestWindowExt as _};
2018
2019 use super::*;
2020
2021 #[test]
2022 fn money_draft_and_minor_conversions_handle_cents_and_zero_decimal_currencies() {
2023 assert_eq!(money_draft_to_minor("", 2), None);
2024 assert_eq!(money_draft_to_minor("12.5", 2), Some(1250));
2025 assert_eq!(money_draft_to_minor("12.50", 2), Some(1250));
2026 assert_eq!(money_draft_to_minor("1250", 0), Some(1250));
2027
2028 assert_eq!(money_minor_to_draft(Some(1250), 2), "12.50");
2029 assert_eq!(money_minor_to_draft(Some(5), 2), "0.05");
2030 assert_eq!(money_minor_to_draft(Some(1250), 0), "1250");
2031 }
2032
2033 #[test]
2034 fn money_parts_of_marks_missing_cents_as_ghosts_and_keys_by_place_value() {
2035 let empty_parts = money_parts_of("", 2);
2036 assert_eq!(empty_parts.len(), 4); assert!(empty_parts.iter().all(|p| p.ghost));
2038
2039 let partial = money_parts_of("12.5", 2);
2040 assert_eq!(partial.len(), 5);
2042 assert!(!partial[0].ghost);
2043 assert!(!partial[3].ghost);
2044 assert!(partial[4].ghost);
2045 }
2046
2047 #[test]
2048 fn sanitize_money_draft_strips_leading_zeroes_and_enforces_precision() {
2049 assert_eq!(sanitize_money_draft("0012.3", 2), Some("12.3".to_string()));
2050 assert_eq!(sanitize_money_draft(".5", 2), Some("0.5".to_string()));
2051 assert_eq!(sanitize_money_draft("12.345", 2), None);
2052 }
2053
2054 #[test]
2055 fn money_parse_pasted_applies_arc_decimal_heuristic() {
2056 assert_eq!(
2057 money_parse_pasted("$1,234.56", 2).as_deref(),
2058 Some("1234.56")
2059 );
2060 assert_eq!(
2061 money_parse_pasted("1.234,56 €", 2).as_deref(),
2062 Some("1234.56")
2063 );
2064 assert_eq!(money_parse_pasted("1234.5", 2).as_deref(), Some("1234.5"));
2065 assert_eq!(money_parse_pasted("12", 2).as_deref(), Some("12"));
2066 assert_eq!(money_parse_pasted("abc", 2), None);
2067 assert_eq!(money_parse_pasted("$1,234.56", 0).as_deref(), Some("1234"));
2069 }
2070
2071 #[test]
2072 fn money_bump_kick_follows_motion_explicit_velocity_critical_spring() {
2073 let omega = std::f64::consts::TAU / (0.42 * 1.2);
2076 let mut expected = CurveTrace::new("money_input", "bump_x");
2077 let mut actual = CurveTrace::new("money_input", "bump_x");
2078 for frame in 0..=70usize {
2079 let t_ms = frame as f64 * 16.0;
2080 let t = t_ms / 1000.0;
2081 expected.push(t_ms, 160.0 * t * (-omega * t).exp());
2082 actual.push(t_ms, f64::from(money_bump_x_offset(t, 1, false)));
2083 }
2084 let err = max_curve_error_pct(&actual, &expected);
2085 assert!(err < 5.0, "bump kick error {err:.3}% >= 5%");
2086
2087 assert_eq!(money_bump_x_offset(0.08, 1, true), 0.0);
2089 assert_eq!(money_bump_x_offset(0.08, 0, false), 0.0);
2090 assert_eq!(money_bump_x_offset(-1.0, 1, false), 0.0);
2091 }
2092
2093 struct MoneyHost {
2094 minor: Option<i64>,
2095 currency: SharedString,
2096 disabled: bool,
2097 values: Rc<RefCell<Vec<Option<i64>>>>,
2098 currencies: Rc<RefCell<Vec<SharedString>>>,
2099 }
2100
2101 impl Render for MoneyHost {
2102 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
2103 let values = self.values.clone();
2104 let currencies = self.currencies.clone();
2105 div().w(px(520.0)).p(px(16.0)).child(
2106 MoneyInput::new("money-test", "Amount")
2107 .min(500)
2108 .max(3_000)
2109 .value(self.minor)
2110 .currency(self.currency.clone())
2111 .quick_add([10, 50])
2112 .disabled(self.disabled)
2113 .on_value_change(cx.listener({
2114 let values = values.clone();
2115 move |this, event: &MoneyValueEvent, _, cx| {
2116 values.borrow_mut().push(event.minor);
2117 this.minor = event.minor;
2118 cx.notify();
2119 }
2120 }))
2121 .on_currency_change(cx.listener({
2122 let currencies = currencies.clone();
2123 move |this, code: &SharedString, _, cx| {
2124 currencies.borrow_mut().push(code.clone());
2125 this.currency = code.clone();
2126 cx.notify();
2127 }
2128 })),
2129 )
2130 }
2131 }
2132
2133 fn money_element(name: &str) -> ElementId {
2134 ElementId::NamedChild(ElementId::Name("money-test".into()).into(), name.into())
2135 }
2136
2137 #[gpui_kit::test]
2138 fn money_input_types_steps_pastes_switches_currency_and_refuses_limits(
2139 cx: &mut TestAppContext,
2140 ) {
2141 cx.update(|cx| {
2142 gpui_kit::init(cx);
2143 install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
2144 });
2145
2146 let host = MoneyHost {
2147 minor: None,
2148 currency: "USD".into(),
2149 disabled: false,
2150 values: Rc::new(RefCell::new(Vec::new())),
2151 currencies: Rc::new(RefCell::new(Vec::new())),
2152 };
2153 let values = host.values.clone();
2154 let currencies = host.currencies.clone();
2155 let (view, cx) = cx.add_window_view(|_, _| host);
2156
2157 cx.update(|window, cx| {
2158 window.render_frame(cx);
2159 let control = window.find(money_element("control"));
2160 assert_eq!(control.role(), Some(Role::SpinButton));
2161
2162 window.click(money_element("control"), cx);
2165 window.input("25", cx);
2166 });
2167 assert_eq!(values.borrow().as_slice(), [Some(200), Some(2_500)]);
2168
2169 cx.update(|window, cx| {
2171 window.press("up", cx);
2172 });
2173 assert_eq!(values.borrow().last(), Some(&Some(2_600)));
2174 cx.update(|window, cx| {
2175 window.press("shift-down", cx);
2176 });
2177 assert_eq!(values.borrow().last(), Some(&Some(1_600)));
2178
2179 cx.update(|window, cx| {
2181 window.click(money_element("quick-add-10"), cx);
2182 });
2183 assert_eq!(values.borrow().last(), Some(&Some(2_600)));
2184
2185 cx.update(|window, cx| {
2188 window.click(money_element("currency-button"), cx);
2189 window.render_frame(cx);
2190 let menu = window.find(money_element("currency-menu"));
2191 assert_eq!(menu.role(), Some(Role::ListBox));
2192 let row = window.find(money_element("currency-JPY"));
2193 assert_eq!(row.role(), Some(Role::ListBoxOption));
2194 window.click(money_element("currency-JPY"), cx);
2195 });
2196 assert_eq!(
2197 currencies.borrow().last().map(|code| code.to_string()),
2198 Some("JPY".to_string())
2199 );
2200 assert_eq!(values.borrow().last(), Some(&Some(26)));
2201
2202 cx.update(|_window, cx| {
2204 cx.write_to_clipboard(ClipboardItem::new_string("$1,234.56".to_string()));
2205 });
2206 cx.update(|window, cx| {
2207 window.press(
2208 if cfg!(target_os = "macos") {
2209 "cmd-v"
2210 } else {
2211 "ctrl-v"
2212 },
2213 cx,
2214 );
2215 });
2216 assert_eq!(values.borrow().last(), Some(&Some(1_234)));
2217
2218 cx.update(|window, cx| {
2220 window.input("5", cx);
2221 });
2222 assert_eq!(values.borrow().last(), Some(&Some(1_234)));
2223
2224 view.update(cx, |host, cx| {
2226 host.disabled = true;
2227 cx.notify();
2228 });
2229 cx.update(|window, cx| {
2230 window.render_frame(cx);
2231 window.click(money_element("control"), cx);
2232 window.input("7", cx);
2233 window.click(money_element("currency-button"), cx);
2234 window.render_frame(cx);
2235 assert!(window.try_find(money_element("currency-menu")).is_none());
2236 });
2237 assert_eq!(values.borrow().last(), Some(&Some(1_234)));
2238 }
2239
2240 #[gpui_kit::test]
2241 fn money_input_reduced_motion_keeps_interactions_instant(cx: &mut TestAppContext) {
2242 cx.update(|cx| {
2243 gpui_kit::init(cx);
2244 install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
2245 arc_motion::set_reduced_motion(arc_motion::ReducedMotionChoice::Reduce, cx);
2246 });
2247
2248 let host = MoneyHost {
2249 minor: None,
2250 currency: "USD".into(),
2251 disabled: false,
2252 values: Rc::new(RefCell::new(Vec::new())),
2253 currencies: Rc::new(RefCell::new(Vec::new())),
2254 };
2255 let values = host.values.clone();
2256 let (_view, cx) = cx.add_window_view(|_, _| host);
2257
2258 cx.update(|window, cx| {
2259 window.render_frame(cx);
2260 window.click(money_element("control"), cx);
2261 window.input("25", cx);
2262 window.press("up", cx);
2263 });
2264 assert_eq!(
2265 values.borrow().as_slice(),
2266 [Some(200), Some(2_500), Some(2_600)]
2267 );
2268 }
2269}