Skip to main content

agent86_ui/runtime/
format.rs

1//! Formatting for the basic catalog's functions, in the `en-US` locale every
2//! reference SDK defaults to: numbers and currency as `Intl.NumberFormat`
3//! writes them, dates by TR35 pattern, plural categories, and the string forms
4//! JavaScript gives values (`String(value)`), so output is the same on every
5//! renderer.
6
7use serde_json::Value;
8
9/// A number as JavaScript's `String(number)` writes it: shortest round-trip
10/// digits, fixed notation between 1e-7 and 1e21, exponential outside.
11pub fn number_string(value: f64) -> String {
12    if value.is_nan() {
13        return "NaN".into();
14    }
15    if value.is_infinite() {
16        return if value > 0.0 { "Infinity" } else { "-Infinity" }.into();
17    }
18    if value == 0.0 {
19        return "0".into();
20    }
21    let (negative, digits, exponent) = decompose(value);
22    let sign = if negative { "-" } else { "" };
23    let n = exponent + 1; // position of the decimal point after the first digit
24    let k = digits.len() as i32;
25    let body = if (-5..=21).contains(&n) && n <= 21 && n > -6 {
26        if k <= n {
27            format!("{digits}{}", "0".repeat((n - k) as usize))
28        } else if n > 0 {
29            format!("{}.{}", &digits[..n as usize], &digits[n as usize..])
30        } else {
31            format!("0.{}{digits}", "0".repeat((-n) as usize))
32        }
33    } else {
34        let mantissa = if k == 1 {
35            digits.clone()
36        } else {
37            format!("{}.{}", &digits[..1], &digits[1..])
38        };
39        let e = n - 1;
40        format!("{mantissa}e{}{}", if e < 0 { "-" } else { "+" }, e.abs())
41    };
42    format!("{sign}{body}")
43}
44
45/// A finite, nonzero float's sign, shortest decimal digits, and decimal
46/// exponent of its first digit (`1234.5` is `("12345", 3)`).
47fn decompose(value: f64) -> (bool, String, i32) {
48    let text = format!("{:e}", value.abs());
49    let (mantissa, exponent) = text.split_once('e').unwrap_or((&text, "0"));
50    let digits: String = mantissa.chars().filter(char::is_ascii_digit).collect();
51    let digits = digits.trim_end_matches('0');
52    let digits = if digits.is_empty() { "0" } else { digits };
53    (
54        value < 0.0,
55        digits.to_string(),
56        exponent.parse().unwrap_or(0),
57    )
58}
59
60/// A value as JavaScript's `String(value)` writes it, with objects and arrays
61/// as JSON and `null` as `""` (the specification's type conversion rule).
62pub fn to_string(value: &Value) -> String {
63    match value {
64        Value::Null => String::new(),
65        Value::String(s) => s.clone(),
66        Value::Bool(b) => b.to_string(),
67        Value::Number(n) => n.as_f64().map(number_string).unwrap_or_default(),
68        Value::Array(_) | Value::Object(_) => value.to_string(),
69    }
70}
71
72/// A value as JavaScript's `Number(value)` reads it (`NaN` when it is not a
73/// number).
74pub fn to_number(value: &Value) -> f64 {
75    match value {
76        Value::Null => 0.0,
77        Value::Bool(b) => f64::from(u8::from(*b)),
78        Value::Number(n) => n.as_f64().unwrap_or(f64::NAN),
79        Value::String(s) => {
80            let s = s.trim();
81            if s.is_empty() {
82                return 0.0;
83            }
84            match s {
85                "Infinity" | "+Infinity" => f64::INFINITY,
86                "-Infinity" => f64::NEG_INFINITY,
87                _ => {
88                    let decimal = s
89                        .bytes()
90                        .all(|b| b.is_ascii_digit() || b"+-.eE".contains(&b));
91                    if decimal {
92                        s.parse().unwrap_or(f64::NAN)
93                    } else if let Some(hex) = s.strip_prefix("0x").or_else(|| s.strip_prefix("0X"))
94                    {
95                        u64::from_str_radix(hex, 16).map_or(f64::NAN, |n| n as f64)
96                    } else {
97                        f64::NAN
98                    }
99                }
100            }
101        }
102        Value::Array(items) => match items.as_slice() {
103            [] => 0.0,
104            [one] => to_number(&Value::String(to_string(one))),
105            _ => f64::NAN,
106        },
107        Value::Object(_) => f64::NAN,
108    }
109}
110
111/// Round a decimal digit string half away from zero (as `Intl` does) to
112/// `places` fraction digits, from a float's shortest representation.
113fn fixed(value: f64, places: usize) -> String {
114    let (_, digits, exponent) = decompose(value);
115    // The digits as an integer and the position of the decimal point.
116    let point = exponent + 1;
117    let mut int: Vec<u8> = Vec::new();
118    let mut frac: Vec<u8> = Vec::new();
119    for (i, d) in digits.bytes().enumerate() {
120        if (i as i32) < point {
121            int.push(d - b'0');
122        } else {
123            frac.push(d - b'0');
124        }
125    }
126    if point > digits.len() as i32 {
127        int.extend(std::iter::repeat_n(
128            0,
129            (point - digits.len() as i32) as usize,
130        ));
131    }
132    if point < 0 {
133        let mut padded = vec![0u8; (-point) as usize];
134        padded.extend(frac);
135        frac = padded;
136    }
137    if int.is_empty() {
138        int.push(0);
139    }
140    let round_up = frac.get(places).is_some_and(|&d| d >= 5);
141    frac.resize(places.max(frac.len()), 0);
142    frac.truncate(places);
143    if round_up {
144        let mut carry = true;
145        for d in frac.iter_mut().rev().chain(int.iter_mut().rev()) {
146            if !carry {
147                break;
148            }
149            if *d == 9 {
150                *d = 0;
151            } else {
152                *d += 1;
153                carry = false;
154            }
155        }
156        if carry {
157            int.insert(0, 1);
158        }
159    }
160    let int: String = int.iter().map(|d| char::from(b'0' + d)).collect();
161    let int = int.trim_start_matches('0');
162    let int = if int.is_empty() { "0" } else { int };
163    let frac: String = frac.iter().map(|d| char::from(b'0' + d)).collect();
164    if frac.is_empty() {
165        int.to_string()
166    } else {
167        format!("{int}.{frac}")
168    }
169}
170
171fn group(int: &str) -> String {
172    let mut out = String::new();
173    for (i, c) in int.chars().enumerate() {
174        if i > 0 && (int.len() - i).is_multiple_of(3) {
175            out.push(',');
176        }
177        out.push(c);
178    }
179    out
180}
181
182/// The digits of a number as `Intl.NumberFormat("en-US")` writes them, without
183/// sign: `decimals` fixes the fraction digits (else up to 3, trailing zeros
184/// dropped); grouping uses `,`.
185fn digits(value: f64, decimals: Option<usize>, grouping: bool) -> String {
186    let text = match decimals {
187        Some(places) => fixed(value.abs(), places),
188        None => {
189            let text = fixed(value.abs(), 3);
190            match text.split_once('.') {
191                Some((int, frac)) => {
192                    let frac = frac.trim_end_matches('0');
193                    if frac.is_empty() {
194                        int.to_string()
195                    } else {
196                        format!("{int}.{frac}")
197                    }
198                }
199                None => text,
200            }
201        }
202    };
203    let (int, frac) = text
204        .split_once('.')
205        .map_or((text.as_str(), None), |(i, f)| (i, Some(f)));
206    let int = if grouping {
207        group(int)
208    } else {
209        int.to_string()
210    };
211    match frac {
212        Some(frac) => format!("{int}.{frac}"),
213        None => int,
214    }
215}
216
217fn is_negative_nonzero(value: f64, decimals: Option<usize>) -> bool {
218    value < 0.0
219        && digits(value, decimals, false)
220            .bytes()
221            .any(|b| b.is_ascii_digit() && b != b'0')
222}
223
224/// `formatNumber`: `en-US` digits with grouping unless `grouping` is false.
225pub fn format_number(value: f64, decimals: Option<usize>, grouping: bool) -> String {
226    if value.is_nan() {
227        return String::new();
228    }
229    if value.is_infinite() {
230        return if value > 0.0 { "∞" } else { "-∞" }.into();
231    }
232    let sign = if is_negative_nonzero(value, decimals) {
233        "-"
234    } else {
235        ""
236    };
237    format!("{sign}{}", digits(value, decimals, grouping))
238}
239
240/// The `en-US` symbol `Intl` uses for a currency, when it has one.
241fn currency_symbol(code: &str) -> Option<&'static str> {
242    Some(match code {
243        "USD" => "$",
244        "EUR" => "€",
245        "GBP" => "£",
246        "JPY" => "¥",
247        "CNY" => "CN¥",
248        "INR" => "₹",
249        "KRW" => "₩",
250        "CAD" => "CA$",
251        "AUD" => "A$",
252        "NZD" => "NZ$",
253        "MXN" => "MX$",
254        "BRL" => "R$",
255        "HKD" => "HK$",
256        "TWD" => "NT$",
257        "ILS" => "₪",
258        "VND" => "₫",
259        "PHP" => "₱",
260        "XAF" => "FCFA",
261        "XCD" => "EC$",
262        "XPF" => "CFPF",
263        _ => return None,
264    })
265}
266
267/// `formatCurrency`: the amount with the currency's `en-US` symbol, or its
268/// code and a no-break space when it has none; 2 fraction digits unless
269/// `decimals` says otherwise.
270pub fn format_currency(
271    value: f64,
272    currency: &str,
273    decimals: Option<usize>,
274    grouping: bool,
275) -> String {
276    if value.is_nan() {
277        return String::new();
278    }
279    let code = currency.to_uppercase();
280    let places = Some(decimals.unwrap_or(2));
281    let sign = if is_negative_nonzero(value, places) {
282        "-"
283    } else {
284        ""
285    };
286    let amount = digits(value, places, grouping);
287    match currency_symbol(&code) {
288        Some(symbol) => format!("{sign}{symbol}{amount}"),
289        None => format!("{sign}{code}\u{a0}{amount}"),
290    }
291}
292
293/// The plural category of a number in `en`: `one` for 1, `other` otherwise,
294/// with the explicit forms every SDK checks first (`zero` for 0, `one` for 1,
295/// `two` for 2) when given.
296pub fn plural_category(value: f64, has: impl Fn(&str) -> bool) -> &'static str {
297    if value == 0.0 && has("zero") {
298        "zero"
299    } else if value == 1.0 && has("one") {
300        "one"
301    } else if value == 2.0 && has("two") {
302        "two"
303    } else if value == 1.0 {
304        "one"
305    } else {
306        "other"
307    }
308}
309
310const MONTHS: [&str; 12] = [
311    "January",
312    "February",
313    "March",
314    "April",
315    "May",
316    "June",
317    "July",
318    "August",
319    "September",
320    "October",
321    "November",
322    "December",
323];
324const WEEKDAYS: [&str; 7] = [
325    "Monday",
326    "Tuesday",
327    "Wednesday",
328    "Thursday",
329    "Friday",
330    "Saturday",
331    "Sunday",
332];
333
334struct Timestamp {
335    /// The date and time as written (its own offset kept).
336    wall: jiff::civil::DateTime,
337    /// The instant, in UTC.
338    instant: jiff::Timestamp,
339}
340
341/// Parse an ISO 8601 date or date-time. A value with no offset is read as
342/// UTC; one with an offset keeps its wall-clock fields for formatting. Fields
343/// that do not name a real date or time (`2026-02-30`) fail.
344fn parse_timestamp(text: &str) -> Option<Timestamp> {
345    static SHAPE: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();
346    let shape = SHAPE.get_or_init(|| {
347        regex::Regex::new(
348            r"^([+-]?\d{4,6})-(\d{2})-(\d{2})(?:[T ](\d{2})(?::(\d{2})(?::(\d{2})(?:\.(\d+))?)?)?)?(Z|[+-]\d{2}:?\d{2})?$",
349        )
350        .expect("timestamp pattern")
351    });
352    let caps = shape.captures(text.trim())?;
353    let number = |i: usize| {
354        caps.get(i)
355            .map(|m| m.as_str().parse::<i32>().ok())
356            .unwrap_or(Some(0))
357    };
358    let year = i16::try_from(number(1)?).ok()?;
359    let month = i8::try_from(number(2)?).ok()?;
360    let day = i8::try_from(number(3)?).ok()?;
361    let hour = i8::try_from(number(4)?).ok()?;
362    let minute = i8::try_from(number(5)?).ok()?;
363    let second = i8::try_from(number(6)?).ok()?;
364    let nanos = caps.get(7).map_or(0, |m| {
365        let digits: String = m.as_str().chars().take(9).collect();
366        format!("{digits:0<9}").parse::<i32>().unwrap_or(0)
367    });
368    let wall = jiff::civil::DateTime::new(year, month, day, hour, minute, second, nanos).ok()?;
369    let offset_seconds = match caps.get(8).map(|m| m.as_str()) {
370        None | Some("Z") => 0,
371        Some(offset) => {
372            let sign = if offset.starts_with('-') { -1 } else { 1 };
373            let digits: String = offset.chars().filter(char::is_ascii_digit).collect();
374            let hours: i32 = digits.get(..2)?.parse().ok()?;
375            let minutes: i32 = digits.get(2..)?.parse().ok()?;
376            sign * (hours * 3600 + minutes * 60)
377        }
378    };
379    let offset = jiff::tz::Offset::from_seconds(offset_seconds).ok()?;
380    let instant = offset.to_timestamp(wall).ok()?;
381    Some(Timestamp { wall, instant })
382}
383
384/// `formatDate`: a TR35 pattern applied to the date as written
385/// (`yyyy yy MMMM MMM MM M EEEE E dd d HH H hh h mm ss a`), or `ISO` for the
386/// instant in UTC with milliseconds. A value that does not parse gives `""`.
387pub fn format_date(value: &Value, pattern: &str) -> String {
388    let text = match value {
389        Value::String(s) if !s.is_empty() => s.clone(),
390        _ => return String::new(),
391    };
392    let Some(parsed) = parse_timestamp(&text) else {
393        return String::new();
394    };
395    let pattern = if pattern.is_empty() {
396        "yyyy-MM-dd"
397    } else {
398        pattern
399    };
400    if pattern == "ISO" {
401        let utc = jiff::tz::Offset::UTC.to_datetime(parsed.instant);
402        return format!(
403            "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}.{:03}Z",
404            utc.year(),
405            utc.month(),
406            utc.day(),
407            utc.hour(),
408            utc.minute(),
409            utc.second(),
410            utc.subsec_nanosecond() / 1_000_000
411        );
412    }
413    let wall = parsed.wall;
414    let hour = wall.hour();
415    let hour12 = if hour % 12 == 0 { 12 } else { hour % 12 };
416    let month = usize::try_from(wall.month() - 1).unwrap_or(0);
417    let weekday = usize::try_from(wall.weekday().to_monday_zero_offset()).unwrap_or(0);
418    const TOKENS: [&str; 17] = [
419        "yyyy", "yy", "MMMM", "MMM", "MM", "M", "EEEE", "E", "dd", "d", "HH", "H", "hh", "h", "mm",
420        "ss", "a",
421    ];
422    let mut out = String::new();
423    let mut rest = pattern;
424    'scan: while !rest.is_empty() {
425        for token in TOKENS {
426            if let Some(after) = rest.strip_prefix(token) {
427                let piece = match token {
428                    "yyyy" => wall.year().to_string(),
429                    "yy" => format!("{:02}", wall.year().rem_euclid(100)),
430                    "MMMM" => MONTHS[month].to_string(),
431                    "MMM" => MONTHS[month][..3].to_string(),
432                    "MM" => format!("{:02}", wall.month()),
433                    "M" => wall.month().to_string(),
434                    "EEEE" => WEEKDAYS[weekday].to_string(),
435                    "E" => WEEKDAYS[weekday][..3].to_string(),
436                    "dd" => format!("{:02}", wall.day()),
437                    "d" => wall.day().to_string(),
438                    "HH" => format!("{hour:02}"),
439                    "H" => hour.to_string(),
440                    "hh" => format!("{hour12:02}"),
441                    "h" => hour12.to_string(),
442                    "mm" => format!("{:02}", wall.minute()),
443                    "ss" => format!("{:02}", wall.second()),
444                    _ => if hour < 12 { "AM" } else { "PM" }.to_string(),
445                };
446                out.push_str(&piece);
447                rest = after;
448                continue 'scan;
449            }
450        }
451        let mut chars = rest.chars();
452        if let Some(c) = chars.next() {
453            out.push(c);
454        }
455        rest = chars.as_str();
456    }
457    out
458}
459
460#[cfg(test)]
461mod tests {
462    use super::*;
463    use serde_json::json;
464
465    #[test]
466    fn numbers_print_as_javascript_prints_them() {
467        for (value, text) in [
468            (1.0, "1"),
469            (-0.0, "0"),
470            (0.1 + 0.2, "0.30000000000000004"),
471            (1234.5, "1234.5"),
472            (1e21, "1e+21"),
473            (1.5e-7, "1.5e-7"),
474            (0.000001, "0.000001"),
475            (123456789012345680000.0, "123456789012345680000"),
476            (-42.25, "-42.25"),
477        ] {
478            assert_eq!(number_string(value), text, "{value}");
479        }
480    }
481
482    #[test]
483    fn number_formats_match_intl_en_us() {
484        assert_eq!(format_number(1234.567, Some(2), true), "1,234.57");
485        assert_eq!(format_number(1234.567, Some(0), false), "1235");
486        assert_eq!(format_number(1234.5678, None, true), "1,234.568");
487        assert_eq!(format_number(1.005, Some(2), true), "1.01");
488        assert_eq!(format_number(0.125, Some(2), true), "0.13");
489        assert_eq!(format_number(-0.001, Some(2), true), "0.00");
490        assert_eq!(format_number(-1234.5, Some(1), true), "-1,234.5");
491        assert_eq!(format_number(999.999, Some(2), true), "1,000.00");
492        assert_eq!(
493            format_number(1e21, Some(0), true),
494            "1,000,000,000,000,000,000,000"
495        );
496        assert_eq!(format_currency(99.99, "usd", Some(2), true), "$99.99");
497        assert_eq!(format_currency(1234.5, "USD", None, true), "$1,234.50");
498        assert_eq!(format_currency(-5.0, "EUR", None, true), "-€5.00");
499        assert_eq!(format_currency(5.0, "CHF", None, true), "CHF\u{a0}5.00");
500    }
501
502    #[test]
503    fn dates_format_as_written() {
504        let date = |value: &str, pattern: &str| format_date(&json!(value), pattern);
505        assert_eq!(date("2026-08-26T12:00:00Z", "yyyy-MM-dd"), "2026-08-26");
506        assert_eq!(
507            date("2026-09-04T23:30:00-05:00", "yyyy-MM-dd HH:mm"),
508            "2026-09-04 23:30"
509        );
510        assert_eq!(
511            date("2026-01-16T14:30:00Z", "EEEE, d MMMM"),
512            "Friday, 16 January"
513        );
514        assert_eq!(date("2026-01-16T14:30:00Z", "h:mm a"), "2:30 PM");
515        assert_eq!(
516            date("2026-01-16T00:05:00Z", "hh:mm a, MMM dd, yy"),
517            "12:05 AM, Jan 16, 26"
518        );
519        assert_eq!(
520            date("2026-09-04T23:30:00-05:00", "ISO"),
521            "2026-09-05T04:30:00.000Z"
522        );
523        assert_eq!(date("2026-02-30", "yyyy-MM-dd"), "");
524        assert_eq!(date("not a date", "yyyy"), "");
525    }
526
527    #[test]
528    fn javascript_number_reads() {
529        assert_eq!(to_number(&json!("42.5")), 42.5);
530        assert_eq!(to_number(&json!(" 7 ")), 7.0);
531        assert!(to_number(&json!("not_a_number")).is_nan());
532        assert_eq!(to_number(&json!(null)), 0.0);
533        assert_eq!(to_number(&json!(true)), 1.0);
534        assert!(to_number(&json!({})).is_nan());
535    }
536}