//! Locale-aware value formatting, conditional rules, footnotes and colors.
//!
//! The masks and rule semantics follow the Python reference: `str`, `int`,
//! `float`, `date`, `percent`, `currency`, `bool` and `sparkline`, with the
//! default locale `pt-BR`. CLDR data comes from ICU4X; the Latin numbering
//! system is forced because Babel (the Python reference) renders Latin digits
//! even for `ar-EG`/`he-IL`.
use std::collections::{HashMap, HashSet};
use std::sync::{Arc, LazyLock, Mutex};
use chrono::{Datelike, NaiveDate};
use icu::datetime::fieldsets;
use icu::datetime::input::Date as IcuDate;
use icu::datetime::DateTimeFormatter;
use icu::decimal::input::Decimal;
use icu::decimal::DecimalFormatter;
use icu::locale::Locale;
use indexmap::IndexMap;
use writeable::Writeable;
use crate::charts;
use crate::error::{Error, Result};
use crate::pyops;
use crate::value::Value;
/// Locale used when the payload omits one.
pub const DEFAULT_LOCALE: &str = "pt-BR";
/// Conditional formatting operators accepted in `cell_rules`.
pub const CONDITION_OPS: [&str; 12] = [
"equals",
"not_equals",
"in",
"not_in",
"gt",
"gte",
"lt",
"lte",
"between",
"contains",
"is_null",
"not_null",
];
/// Style keys accepted in `cell_rules`.
pub const STYLE_KEYS: [&str; 4] = ["color", "background", "bold", "italic"];
/// Automatic footnote marks, in order.
pub const FOOTNOTE_MARKS: [&str; 6] = ["*", "†", "‡", "§", "‖", "¶"];
/// Sparkline blocks from empty to full.
pub const SPARK_BLOCKS: [&str; 9] = [" ", "▁", "▂", "▃", "▄", "▅", "▆", "▇", "█"];
const KNOWN_LANGUAGES: &str = "aa ab ae af ak am an ar as av ay az ba be bg bi bm bn bo br bs ca ce ch co cr cs cu cv cy da de dv dz ee el en eo es et eu fa ff fi fj fo fr fy ga gd gl gn gu gv ha he hi ho hr ht hu hy hz ia id ie ig ii ik io is it iu ja jv ka kg ki kj kk kl km kn ko kr ks ku kv kw ky la lb lg li ln lo lt lu lv mg mh mi mk ml mn mr ms mt my na nb nd ne ng nl nn no nr nv ny oc oj om or os pa pi pl ps pt qu rm rn ro ru rw sa sc sd se sg si sk sl sm sn so sq sr ss st su sv sw ta te tg th ti tk tl tn to tr ts tt tw ty ug uk ur uz ve vi vo wa wo xh yi yo za zh zu fil haw yue";
static DECIMAL_CACHE: LazyLock<Mutex<HashMap<String, Arc<DecimalFormatter>>>> = LazyLock::new(|| Mutex::new(HashMap::new()));
/// A normalized locale (BCP-47 with `_` converted to `-`).
pub fn normalize_locale(locale: &str) -> Result<String> {
let normalized = locale.replace('_', "-");
let language = normalized.split('-').next().unwrap_or_default().to_ascii_lowercase();
if !KNOWN_LANGUAGES.split_whitespace().any(|known| known == language) {
return Err(Error::option(format!("Unknown locale: {locale:?}")));
}
Locale::try_from_str(&normalized).map_err(|_| Error::option(format!("Unknown locale: {locale:?}")))?;
Ok(normalized)
}
fn icu_locale(normalized: &str) -> Result<Locale> {
let tag = if normalized.contains("-u-") {
normalized.to_string()
} else {
format!("{normalized}-u-nu-latn")
};
Locale::try_from_str(&tag).map_err(|_| Error::option(format!("Unknown locale: {normalized:?}")))
}
fn decimal_formatter(normalized: &str) -> Result<Arc<DecimalFormatter>> {
if let Some(formatter) = DECIMAL_CACHE
.lock()
.map_err(|_| Error::option("Locale formatter cache is poisoned"))?
.get(normalized)
.cloned()
{
return Ok(formatter);
}
let locale = icu_locale(normalized)?;
let formatter = DecimalFormatter::try_new(locale.into(), Default::default())
.map_err(|_| Error::option(format!("Unknown locale: {normalized:?}")))?;
let formatter = Arc::new(formatter);
DECIMAL_CACHE
.lock()
.map_err(|_| Error::option("Locale formatter cache is poisoned"))?
.insert(normalized.to_string(), formatter.clone());
Ok(formatter)
}
fn manual_number(value: f64, decimals: usize, normalized: &str) -> String {
let rendered = format!("{value:.decimals$}");
let (sign, rendered) = match rendered.strip_prefix('-') {
Some(rest) => ("-", rest),
None => ("", rendered.as_str()),
};
let (integer, fraction) = rendered.split_once('.').unwrap_or((rendered, ""));
let language = normalized.split('-').next().unwrap_or("en");
let (group, decimal) = if normalized == "pt-PT" {
("\u{a0}", ",")
} else if matches!(
language,
"pt" | "de" | "fr" | "es" | "it" | "nl" | "ru" | "pl" | "cs" | "hu" | "ro" | "tr"
) {
(".", ",")
} else {
(",", ".")
};
let mut grouped = String::new();
for (index, ch) in integer.chars().rev().enumerate() {
if index > 0 && index % 3 == 0 {
grouped.insert(0, group.chars().next().unwrap_or(','));
}
grouped.insert(0, ch);
}
if fraction.is_empty() {
format!("{sign}{grouped}")
} else {
format!("{sign}{grouped}{decimal}{fraction}")
}
}
/// Format a number with `decimals` fraction digits in the locale.
pub fn format_number(value: f64, decimals: usize, locale: &str) -> Result<String> {
let normalized = normalize_locale(locale)?;
if !value.is_finite() {
return Ok(pyops::py_float_str(value));
}
let formatter = decimal_formatter(&normalized)?;
let scale = 10f64.powi(decimals as i32);
let scaled = (value * scale).round_ties_even();
if scaled < i64::MIN as f64 || scaled > i64::MAX as f64 {
return Ok(manual_number(value, decimals, &normalized));
}
let mut decimal = Decimal::from(scaled as i64);
decimal.multiply_pow10(-(decimals as i16));
let rendered = formatter.format(&decimal).write_to_string().to_string();
Ok(apply_babel_four_digit_grouping(rendered, &normalized))
}
/// Babel groups 4-digit numbers in `pt-PT`/`es-ES`; CLDR's
/// `minimumGroupingDigits=2` makes ICU4X wait until 5 digits. Keep the ICU
/// digits/separators and add the missing group separator for those locales.
fn apply_babel_four_digit_grouping(rendered: String, normalized: &str) -> String {
let separator = match normalized {
"pt-PT" => "\u{a0}",
"es-ES" => ".",
_ => return rendered,
};
let (sign, rest) = match rendered.strip_prefix('-') {
Some(rest) => ("-", rest),
None => ("", rendered.as_str()),
};
let integer_end = rest.find(|ch: char| !ch.is_ascii_digit()).unwrap_or(rest.len());
let integer = &rest[..integer_end];
if integer.len() != 4 {
return rendered;
}
format!("{sign}{}{separator}{}{}", &integer[..1], &integer[1..], &rest[integer_end..])
}
fn locale_parts(normalized: &str) -> Result<(String, String)> {
let locale = icu_locale(normalized)?;
let language = locale.id.language.to_string();
let region = locale.id.region.map(|region| region.to_string()).unwrap_or_default();
Ok((language, region))
}
/// The locale territory's primary currency code (`USD` fallback).
pub fn default_currency(locale: &str) -> Result<String> {
let normalized = normalize_locale(locale)?;
let (_, region) = locale_parts(&normalized)?;
Ok(match region.as_str() {
"BR" => "BRL",
"US" => "USD",
"GB" => "GBP",
"JP" => "JPY",
"CN" => "CNY",
"IN" => "INR",
"RU" => "RUB",
"EG" => "EGP",
"IL" => "ILS",
"CA" => "CAD",
"AU" => "AUD",
"CH" => "CHF",
"MX" => "MXN",
"AR" => "ARS",
"CL" => "CLP",
"CO" => "COP",
"KR" => "KRW",
"SA" => "SAR",
"AE" => "AED",
"TR" => "TRY",
"ZA" => "ZAR",
"SE" => "SEK",
"NO" => "NOK",
"DK" => "DKK",
"PL" => "PLN",
"CZ" => "CZK",
"HU" => "HUF",
"RO" => "RON",
"NZ" => "NZD",
"SG" => "SGD",
"HK" => "HKD",
"TW" => "TWD",
"TH" => "THB",
"ID" => "IDR",
"MY" => "MYR",
"PH" => "PHP",
"VN" => "VND",
"NG" => "NGN",
"KE" => "KES",
"PT" | "DE" | "FR" | "ES" | "IT" | "NL" | "IE" | "AT" | "BE" | "FI" | "GR" => "EUR",
_ => "USD",
}
.to_string())
}
fn currency_decimals(code: &str) -> usize {
match code {
"JPY" | "KRW" | "CLP" | "VND" | "ISK" | "UGX" | "XOF" | "XAF" => 0,
"KWD" | "BHD" | "OMR" | "JOD" | "TND" | "IQD" | "LYD" => 3,
_ => 2,
}
}
fn currency_symbol(code: &str, language: &str, region: &str) -> String {
let code = code.to_ascii_uppercase();
if matches!((language, region), ("en", "US") | ("pt", "BR")) {
let symbol = match code.as_str() {
"USD" if language == "pt" => "US$",
"USD" => "$",
"EUR" => "€",
"BRL" => "R$",
"GBP" => "£",
"JPY" if language == "pt" => "JP¥",
"JPY" => "¥",
"CNY" => "CN¥",
"INR" => "₹",
"CAD" => "CA$",
"AUD" if language == "pt" => "AU$",
"AUD" => "A$",
"CHF" => "CHF",
"MXN" => "MX$",
"KRW" => "₩",
"ILS" => "₪",
"NZD" => "NZ$",
"HKD" => "HK$",
"TWD" => "NT$",
"THB" if language == "pt" => "฿",
"THB" => "THB",
"PHP" if language == "pt" => "PHP",
"PHP" => "₱",
"VND" => "₫",
// Babel renders these currencies as ISO codes in en-US and pt-BR.
"RUB" | "EGP" | "SAR" | "AED" | "ARS" | "CLP" | "COP" | "TRY" | "ZAR" | "SEK" | "NOK" | "DKK" | "PLN" | "CZK" | "HUF"
| "RON" | "SGD" | "IDR" | "MYR" | "NGN" | "KES" => code.as_str(),
other => other,
};
return symbol.to_string();
}
match (language, region, code.as_str()) {
("pt", "BR", "USD") => "US$".to_string(),
("pt", "BR", "EUR") => "€".to_string(),
("en", _, "BRL") => "R$".to_string(),
("en", _, "EUR") => "€".to_string(),
("ja", _, "USD") => "$".to_string(),
("ja", _, "EUR") => "€".to_string(),
(_, _, "USD") => "$".to_string(),
(_, _, "EUR") => "€".to_string(),
(_, _, "BRL") => "R$".to_string(),
(_, _, "GBP") => "£".to_string(),
(_, _, "JPY") => "¥".to_string(),
(_, _, "CNY") => "¥".to_string(),
(_, _, "INR") => "₹".to_string(),
(_, _, "RUB") => "₽".to_string(),
(_, _, "EGP") => "ج.م.".to_string(),
(_, _, "ILS") => "₪".to_string(),
(_, _, "CAD") => "CA$".to_string(),
(_, _, "AUD") => "A$".to_string(),
(_, _, "CHF") => "CHF".to_string(),
(_, _, "MXN") => "MX$".to_string(),
(_, _, "ARS") => "AR$".to_string(),
(_, _, "CLP") => "CLP".to_string(),
(_, _, "COP") => "COL$".to_string(),
(_, _, "KRW") => "₩".to_string(),
(_, _, "SAR") => "ر.س.".to_string(),
(_, _, "AED") => "د.إ.".to_string(),
(_, _, "TRY") => "₺".to_string(),
(_, _, "ZAR") => "R".to_string(),
(_, _, "SEK") | (_, _, "NOK") | (_, _, "DKK") => "kr".to_string(),
(_, _, "PLN") => "zł".to_string(),
(_, _, "CZK") => "Kč".to_string(),
(_, _, "HUF") => "Ft".to_string(),
(_, _, "RON") => "lei".to_string(),
(_, _, "NZD") => "NZ$".to_string(),
(_, _, "SGD") => "S$".to_string(),
(_, _, "HKD") => "HK$".to_string(),
(_, _, "TWD") => "NT$".to_string(),
(_, _, "THB") => "฿".to_string(),
(_, _, "IDR") => "Rp".to_string(),
(_, _, "MYR") => "RM".to_string(),
(_, _, "PHP") => "₱".to_string(),
(_, _, "VND") => "₫".to_string(),
(_, _, "NGN") => "₦".to_string(),
(_, _, "KES") => "KSh".to_string(),
(_, _, other) => other.to_string(),
}
}
/// Currency symbol used inside native spreadsheet number formats.
///
/// Babel (the Python reference) exposes the locale's currency symbol, which for
/// Arabic currencies carries a trailing right-to-left mark.
#[cfg(feature = "xlsx")]
pub(crate) fn xlsx_currency_symbol(code: &str, locale: &str) -> String {
let normalized = match normalize_locale(locale) {
Ok(value) => value,
Err(_) => return "$".to_string(),
};
let (language, region) = match locale_parts(&normalized) {
Ok(value) => value,
Err(_) => return "$".to_string(),
};
let code = if code.is_empty() {
default_currency(&normalized).unwrap_or_else(|_| "USD".to_string())
} else {
code.to_ascii_uppercase()
};
let mut symbol = currency_symbol(&code, &language, ®ion);
if language == "ar" && matches!(code.as_str(), "EGP" | "SAR" | "AED") {
symbol.push('\u{200f}');
}
symbol
}
/// Format a monetary value using the locale's placement conventions.
pub fn format_currency(value: f64, code: &str, locale: &str) -> Result<String> {
let normalized = normalize_locale(locale)?;
let (language, region) = locale_parts(&normalized)?;
let code = if code.is_empty() {
default_currency(&normalized)?
} else {
code.to_ascii_uppercase()
};
let symbol = currency_symbol(&code, &language, ®ion);
let decimals = currency_decimals(&code);
let number = format_number(value, decimals, &normalized)?;
let (sign, magnitude) = match number.strip_prefix('-') {
Some(rest) => ("-", rest),
None => ("", number.as_str()),
};
if language == "ar" && region == "EG" {
return Ok(format!("\u{200f}{number}\u{a0}{symbol}\u{200f}"));
}
if language == "he" && region == "IL" {
return Ok(format!("\u{200f}{number}\u{a0}\u{200f}{symbol}"));
}
let suffix = matches!(
region.as_str(),
"DE" | "FR" | "ES" | "IT" | "NL" | "PT" | "RU" | "SE" | "NO" | "DK" | "PL" | "CZ" | "HU" | "RO" | "GR" | "IE" | "AT" | "BE" | "FI"
);
let space = if suffix || matches!(region.as_str(), "BR" | "EG" | "IL") {
"\u{a0}"
} else {
""
};
if suffix {
Ok(format!("{sign}{magnitude}{space}{symbol}"))
} else {
Ok(format!("{sign}{symbol}{space}{magnitude}"))
}
}
/// Format a percentage (fraction input, e.g. `0.091` -> `9,10%`).
pub fn format_percent(value: f64, locale: &str) -> Result<String> {
let number = format_number(value * 100.0, 2, locale)?;
Ok(format!("{number}%"))
}
/// Format a date with the locale's medium style.
pub fn format_date(date: NaiveDate, locale: &str) -> Result<String> {
let normalized = normalize_locale(locale)?;
let icu_locale = icu_locale(&normalized)?;
let field_set = fieldsets::YMD::medium();
let formatter =
DateTimeFormatter::try_new(icu_locale.into(), field_set).map_err(|_| Error::option(format!("Unknown locale: {locale:?}")))?;
let date = IcuDate::try_new_iso(date.year(), date.month() as u8, date.day() as u8).map_err(|_| Error::option("Invalid date"))?;
Ok(formatter.format(&date).write_to_string().to_string())
}
/// Format a datetime using its date part (Babel's `format_date` behavior).
pub fn format_datetime(value: &chrono::DateTime<chrono::FixedOffset>, locale: &str) -> Result<String> {
format_date(value.date_naive(), locale)
}
/// Fully normalized footnote.
#[derive(Debug, Clone, PartialEq)]
pub struct Footnote {
/// Explicit or automatic mark.
pub mark: Option<String>,
/// Footnote text.
pub text: String,
}
impl Footnote {
/// Encode as a `mark`/`text` object.
pub fn to_value(&self) -> Value {
let mut object = IndexMap::new();
object.insert("mark".to_string(), self.mark.clone().map(Value::String).unwrap_or(Value::Null));
object.insert("text".to_string(), Value::String(self.text.clone()));
Value::Object(object)
}
}
/// Normalize a string or `{mark, text}` footnote definition.
pub fn normalize_footnote(spec: &Value, where_: &str) -> Result<Footnote> {
match spec {
Value::String(text) => {
if text.is_empty() {
return Err(Error::option(format!("Invalid empty footnote for {where_}")));
}
Ok(Footnote {
mark: None,
text: text.clone(),
})
}
Value::Object(object) => {
let unknown: Vec<&String> = object.keys().filter(|key| !matches!(key.as_str(), "mark" | "text")).collect();
if !unknown.is_empty() {
return Err(Error::option(format!("Invalid footnote keys {unknown:?} for {where_}")));
}
let text = object
.get("text")
.and_then(Value::as_str)
.filter(|text| !text.is_empty())
.ok_or_else(|| Error::option(format!("Invalid footnote text for {where_}")))?;
let mark = match object.get("mark") {
None | Some(Value::Null) => None,
Some(Value::String(mark)) if !mark.is_empty() => Some(mark.clone()),
Some(_) => return Err(Error::option(format!("Invalid footnote mark for {where_}"))),
};
Ok(Footnote {
mark,
text: text.to_string(),
})
}
_ => Err(Error::option(format!(
"Invalid footnote for {where_} (need text or {{mark, text}})"
))),
}
}
/// Assign a footnote mark to a single normalized field/item object.
pub fn assign_footnote_mark(value: &mut Value, state: &mut FootnoteState) -> Result<()> {
let mut item = std::mem::replace(value, Value::Null);
assign_footnote_marks(std::slice::from_mut(&mut item), state)?;
*value = item;
Ok(())
}
/// Footnote numbering state shared across a report/section.
#[derive(Debug, Clone, Default)]
pub struct FootnoteState {
/// Marks already used.
pub used: HashSet<String>,
/// Text-to-mark assignments for shared notes.
pub by_text: HashMap<String, String>,
/// Next automatic mark index.
pub auto: usize,
}
/// Fill auto marks (`*†‡§‖¶` then numbers) in a normalized field list.
pub fn assign_footnote_marks(fields: &mut [Value], state: &mut FootnoteState) -> Result<()> {
for field in fields {
let Some(object) = field.as_object_mut() else {
continue;
};
let Some(note) = object.get_mut("footnote").and_then(Value::as_object_mut) else {
continue;
};
let text = note.get("text").and_then(Value::as_str).unwrap_or_default().to_string();
if text.is_empty() {
continue;
}
let explicit = note.get("mark").and_then(Value::as_str).map(str::to_string);
let mark = if let Some(mark) = state.by_text.get(&text) {
if explicit.as_ref().is_some_and(|explicit| explicit != mark) {
return Err(Error::option("Conflicting footnote marks for the same note"));
}
mark.clone()
} else {
let mark = match explicit {
Some(mark) => {
if state.used.contains(&mark) {
return Err(Error::option("Duplicate footnote mark for different notes"));
}
mark
}
None => loop {
let index = state.auto;
let candidate = if index < FOOTNOTE_MARKS.len() {
FOOTNOTE_MARKS[index].to_string()
} else {
(index - FOOTNOTE_MARKS.len() + 1).to_string()
};
state.auto += 1;
if !state.used.contains(&candidate) {
break candidate;
}
},
};
state.by_text.insert(text, mark.clone());
mark
};
state.used.insert(mark.clone());
note.insert("mark".to_string(), Value::String(mark));
}
Ok(())
}
/// Validated `color_scale` gradient endpoints.
#[derive(Debug, Clone, PartialEq)]
pub struct ColorScale {
/// Minimum endpoint color.
pub min: String,
/// Maximum endpoint color.
pub max: String,
}
impl ColorScale {
/// Encode as a `min`/`max` object.
pub fn to_value(&self) -> Value {
let mut object = IndexMap::new();
object.insert("min".to_string(), Value::String(self.min.clone()));
object.insert("max".to_string(), Value::String(self.max.clone()));
Value::Object(object)
}
}
fn parse_hex_color(spec: &Value, where_: &str) -> Result<(u8, u8, u8)> {
let Some(text) = spec.as_str() else {
return Err(Error::option(format!("Invalid color for {where_} (need #rrggbb): {spec:?}")));
};
let Some(hex) = text.strip_prefix('#') else {
return Err(Error::option(format!("Invalid color for {where_} (need #rrggbb): {spec:?}")));
};
let hex = if hex.len() == 3 {
hex.chars().flat_map(|ch| [ch, ch]).collect::<String>()
} else {
hex.to_string()
};
if hex.len() != 6 {
return Err(Error::option(format!("Invalid color for {where_} (need #rrggbb): {spec:?}")));
}
let parse = |value: &str| u8::from_str_radix(value, 16).ok();
let red = parse(&hex[0..2]);
let green = parse(&hex[2..4]);
let blue = parse(&hex[4..6]);
match (red, green, blue) {
(Some(red), Some(green), Some(blue)) => Ok((red, green, blue)),
_ => Err(Error::option(format!("Invalid color for {where_} (need #rrggbb): {spec:?}"))),
}
}
/// Normalize and validate a `color_scale` definition.
pub fn normalize_color_scale(spec: &Value, where_: &str) -> Result<ColorScale> {
let Some(object) = spec.as_object() else {
return Err(Error::option(format!(
"Invalid color_scale for {where_} (need {{min, max}} colors): {spec:?}"
)));
};
let unknown = object.keys().any(|key| !matches!(key.as_str(), "min" | "max"));
if unknown || !object.contains_key("min") || !object.contains_key("max") {
return Err(Error::option(format!(
"Invalid color_scale for {where_} (need {{min, max}} colors): {spec:?}"
)));
}
parse_hex_color(object.get("min").unwrap_or(&Value::Null), where_)?;
parse_hex_color(object.get("max").unwrap_or(&Value::Null), where_)?;
Ok(ColorScale {
min: object.get("min").and_then(Value::as_str).unwrap_or("#000000").to_string(),
max: object.get("max").and_then(Value::as_str).unwrap_or("#FFFFFF").to_string(),
})
}
/// Interpolate a `#rrggbb` fill between min/max colors (clamped).
pub fn color_scale_fill(value: f64, low: f64, high: f64, min_color: &str, max_color: &str) -> String {
let low_rgb = parse_hex_color(&Value::String(min_color.to_string()), "color_scale").unwrap_or((0, 0, 0));
let high_rgb = parse_hex_color(&Value::String(max_color.to_string()), "color_scale").unwrap_or((255, 255, 255));
let t = if high == low {
0.5
} else {
((value - low) / (high - low)).clamp(0.0, 1.0)
};
let mix = |low: u8, high: u8| (low as f64 + (high as f64 - low as f64) * t).round_ties_even().clamp(0.0, 255.0) as u8;
format!(
"#{:02X}{:02X}{:02X}",
mix(low_rgb.0, high_rgb.0),
mix(low_rgb.1, high_rgb.1),
mix(low_rgb.2, high_rgb.2)
)
}
/// Unicode block-art nanoplot (text-safe fallback for CSV/XLSX).
pub fn sparkline_text(value: &Value) -> String {
let numbers = charts::spark_numbers(value);
if numbers.is_empty() {
return String::new();
}
let lo = numbers.iter().copied().fold(f64::INFINITY, f64::min);
let hi = numbers.iter().copied().fold(f64::NEG_INFINITY, f64::max);
let span = if (hi - lo) == 0.0 { 1.0 } else { hi - lo };
numbers
.iter()
.map(|value| {
let index = 1 + ((value - lo) / span * 7.0).floor() as usize;
SPARK_BLOCKS[index.min(SPARK_BLOCKS.len() - 1)]
})
.collect()
}
fn rule_repr(rule: &IndexMap<String, Value>) -> String {
pyops::py_str(&Value::Object(rule.clone()))
}
/// Match a value against every comparison operator in the rule (AND).
pub fn match_rule(value: &Value, rule: &IndexMap<String, Value>) -> Result<bool> {
let mut matched = false;
for op in CONDITION_OPS {
let Some(expected) = rule.get(op) else {
continue;
};
matched = true;
let ok = match op {
"equals" => pyops::py_eq(value, expected),
"not_equals" => !pyops::py_eq(value, expected),
"in" => pyops::py_membership(value, expected).unwrap_or(false),
"not_in" => !pyops::py_membership(value, expected).unwrap_or(false),
"is_null" => value.is_null(),
"not_null" => !value.is_null(),
"between" => {
let Some(pair) = expected.as_array() else {
return Err(Error::option(format!("'between' needs a [lo, hi] pair: {}", rule_repr(rule))));
};
if pair.len() != 2 {
return Err(Error::option(format!("'between' needs a [lo, hi] pair: {}", rule_repr(rule))));
}
match (pyops::py_cmp(&pair[0], value), pyops::py_cmp(value, &pair[1])) {
(Some(low), Some(high)) => low != std::cmp::Ordering::Greater && high != std::cmp::Ordering::Greater,
_ => false,
}
}
"contains" => {
let Some(needle) = expected.as_str() else {
return Err(Error::option(format!("'contains' needs a string needle: {}", rule_repr(rule))));
};
!value.is_null() && pyops::py_str(value).contains(needle)
}
"gt" | "gte" | "lt" | "lte" => match pyops::py_cmp(value, expected) {
Some(ordering) => match op {
"gt" => ordering == std::cmp::Ordering::Greater,
"gte" => ordering != std::cmp::Ordering::Less,
"lt" => ordering == std::cmp::Ordering::Less,
_ => ordering != std::cmp::Ordering::Greater,
},
None => false,
},
_ => false,
};
if !ok {
return Ok(false);
}
}
if !matched {
return Err(Error::option(format!("Rule has no known operator: {}", rule_repr(rule))));
}
Ok(true)
}
/// First matching `cell_rules` entry as a style.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct CellStyle {
/// Foreground color.
pub color: Option<String>,
/// Background color.
pub background: Option<String>,
/// Bold text.
pub bold: bool,
/// Italic text.
pub italic: bool,
}
/// Resolve the first matching `cell_rules` entry for a field.
pub fn cell_style_dict(value: &Value, field_def: &Value) -> Result<CellStyle> {
let Some(field) = field_def.as_object() else {
return Ok(CellStyle::default());
};
let Some(rules) = field.get("cell_rules").and_then(Value::as_array) else {
return Ok(CellStyle::default());
};
for rule in rules {
let Some(rule) = rule.as_object() else {
return Err(Error::option(format!("Invalid cell rule (must be an object): {rule:?}")));
};
let unknown: Vec<&String> = rule
.keys()
.filter(|key| !CONDITION_OPS.contains(&key.as_str()) && !STYLE_KEYS.contains(&key.as_str()))
.collect();
if !unknown.is_empty() {
return Err(Error::option(format!("Invalid cell rule keys {unknown:?}: {}", rule_repr(rule))));
}
let has_condition = CONDITION_OPS.iter().any(|op| rule.contains_key(*op));
if !has_condition || match_rule(value, rule)? {
return Ok(CellStyle {
color: rule.get("color").and_then(Value::as_str).map(str::to_string),
background: rule.get("background").and_then(Value::as_str).map(str::to_string),
bold: rule.get("bold").is_some_and(Value::truthy),
italic: rule.get("italic").is_some_and(Value::truthy),
});
}
}
Ok(CellStyle::default())
}
/// Gradient fill for `color_scale` fields with a `color_domain`.
pub fn scale_fill(value: &Value, field_def: &Value) -> Option<String> {
let field = field_def.as_object()?;
let scale = field.get("color_scale")?.as_object()?;
let domain = field.get("color_domain")?.as_array()?;
if domain.len() != 2 || matches!(value, Value::Bool(_)) {
return None;
}
let number = pyops::py_float(value).ok()?;
let low = pyops::py_float(&domain[0]).ok()?;
let high = pyops::py_float(&domain[1]).ok()?;
let min = scale.get("min")?.as_str()?;
let max = scale.get("max")?.as_str()?;
Some(color_scale_fill(number, low, high, min, max))
}
/// First matching `cell_rules` entry as inline CSS.
pub fn cell_style(value: &Value, field_def: &Value) -> Result<String> {
let style = cell_style_dict(value, field_def)?;
let mut parts = Vec::new();
if let Some(color) = style.color {
parts.push(format!("color:{color}"));
}
if let Some(background) = style.background.or_else(|| scale_fill(value, field_def)) {
parts.push(format!("background:{background}"));
}
if style.bold {
parts.push("font-weight:bold".to_string());
}
if style.italic {
parts.push("font-style:italic".to_string());
}
Ok(parts.join(";"))
}
/// Decide column visibility (`visible` / `visible_when` with any/all scope).
pub fn field_visible(field_def: &Value, rows: &[Value]) -> Result<bool> {
let Some(field) = field_def.as_object() else {
return Ok(true);
};
if field.get("visible").and_then(Value::as_bool) == Some(false) {
return Ok(false);
}
let Some(condition) = field.get("visible_when").filter(|value| value.truthy()) else {
return Ok(true);
};
let condition_value = condition.clone();
let Some(condition) = condition.as_object() else {
return Err(Error::option(format!(
"Invalid visible_when condition: {}",
pyops::py_str(condition)
)));
};
let Some(field_name) = condition.get("field").and_then(Value::as_str) else {
return Err(Error::option(format!(
"Invalid visible_when condition: {}",
pyops::py_str(&condition_value)
)));
};
let scope = condition.get("scope").and_then(Value::as_str).unwrap_or("any");
if !matches!(scope, "any" | "all") {
return Err(Error::option(format!("Invalid visible_when scope: {scope:?}")));
}
let mut matches = Vec::new();
for row in rows {
if row.is_object() {
matches.push(match_rule(row.get(field_name).unwrap_or(&Value::Null), condition)?);
}
}
Ok(if scope == "any" {
matches.iter().any(|matched| *matched)
} else {
matches.iter().all(|matched| *matched)
})
}
/// Mapped display text via `substitutions`/`missing_text`, else `None`.
pub fn field_text(value: &Value, field: Option<&Value>) -> Result<Option<String>> {
let Some(field) = field.and_then(Value::as_object) else {
return Ok(None);
};
if let Some(substitutions) = field.get("substitutions") {
let Some(substitutions) = substitutions.as_object() else {
return Err(Error::option(format!(
"Invalid substitutions (must be an object): {substitutions:?}"
)));
};
if let Value::String(key) = value {
if let Some(mapped) = substitutions.get(key) {
return Ok(Some(pyops::py_str(mapped)));
}
}
if !value.is_null() {
let key = pyops::py_str(value);
if let Some(mapped) = substitutions.get(&key) {
return Ok(Some(pyops::py_str(mapped)));
}
}
}
if value.is_null() {
if let Some(missing) = field.get("missing_text") {
return Ok(Some(if missing.is_null() { String::new() } else { pyops::py_str(missing) }));
}
}
Ok(None)
}
/// Format a value according to the mask and locale.
pub fn format_value(value: &Value, format_mask: &str, locale: &str, currency: Option<&str>, field: Option<&Value>) -> Result<String> {
if let Some(mapped) = field_text(value, field)? {
return Ok(mapped);
}
if value.is_null() {
return Ok(String::new());
}
if format_mask == "sparkline" {
let options = field.and_then(Value::as_object);
let kind = options
.and_then(|options| options.get("spark_kind"))
.and_then(Value::as_str)
.unwrap_or("line");
let color = options
.and_then(|options| options.get("spark_color"))
.and_then(Value::as_str)
.unwrap_or("#0A2F46");
return charts::sparkline(value, kind, 96, 28, color);
}
let normalized = normalize_locale(locale)?;
match format_mask {
"int" => match pyops::py_int(value) {
Ok(value) => format_number(value as f64, 0, &normalized),
Err(_) => Ok(pyops::py_str(value)),
},
"float" => match pyops::py_float(value) {
Ok(value) => format_number(value, 2, &normalized),
Err(_) => Ok(pyops::py_str(value)),
},
"percent" => match pyops::py_float(value) {
Ok(value) => format_percent(value, &normalized),
Err(_) => Ok(pyops::py_str(value)),
},
"currency" => match pyops::py_float(value) {
Ok(value) => {
let code = match currency {
Some(code) => code.to_string(),
None => default_currency(&normalized)?,
};
format_currency(value, &code, &normalized)
}
Err(_) => Ok(pyops::py_str(value)),
},
"bool" => {
let yes = match value {
Value::String(text) => matches!(text.trim().to_ascii_lowercase().as_str(), "true" | "yes" | "y" | "1" | "sim"),
other => other.truthy(),
};
Ok(if yes { "Yes" } else { "No" }.to_string())
}
"date" => match value {
Value::Date(date) => format_date(*date, &normalized),
Value::DateTime(datetime) => format_datetime(datetime, &normalized),
other => Ok(pyops::py_str(other)),
},
_ => Ok(pyops::py_str(value)),
}
}
/// Normalize a raw field definition with defaults (label=name, alignment=left).
pub fn format_field(name: &str, field_def: &IndexMap<String, Value>) -> Result<Value> {
let mut out = IndexMap::new();
out.insert("name".to_string(), Value::String(name.to_string()));
out.insert(
"label".to_string(),
field_def.get("label").cloned().unwrap_or_else(|| Value::String(name.to_string())),
);
out.insert(
"format_mask".to_string(),
Value::String(field_def.get("format_mask").map(pyops::py_str).unwrap_or_else(|| "str".to_string())),
);
out.insert(
"alignment".to_string(),
Value::String(field_def.get("alignment").map(pyops::py_str).unwrap_or_else(|| "left".to_string())),
);
if field_def.get("cell_rules").is_some_and(|value| value.truthy()) {
out.insert(
"cell_rules".to_string(),
field_def.get("cell_rules").cloned().unwrap_or(Value::Null),
);
}
if let Some(value) = field_def.get("missing_text") {
out.insert("missing_text".to_string(), value.clone());
}
if let Some(value) = field_def.get("substitutions") {
out.insert("substitutions".to_string(), value.clone());
}
if let Some(value) = field_def.get("footnote") {
let footnote = normalize_footnote(value, &format!("field {name:?}"))?;
out.insert("footnote".to_string(), footnote.to_value());
}
if let Some(value) = field_def.get("footnote_mark") {
out.insert("footnote_mark".to_string(), value.clone());
}
if let Some(value) = field_def.get("color_scale") {
let scale = normalize_color_scale(value, &format!("field {name:?}"))?;
out.insert("color_scale".to_string(), scale.to_value());
}
if let Some(value) = field_def.get("data_bar") {
let Some(flag) = value.as_bool() else {
return Err(Error::option(format!(
"Invalid data_bar for field {name:?} (must be true/false): {value:?}"
)));
};
out.insert("data_bar".to_string(), Value::Bool(flag));
}
Ok(Value::Object(out))
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
fn value(value: serde_json::Value) -> Value {
Value::from_json(value)
}
#[test]
fn none_and_int_and_float() {
assert_eq!(format_value(&Value::Null, "str", "pt-BR", None, None).unwrap(), "");
assert_eq!(format_value(&Value::Int(1234), "int", "pt-BR", None, None).unwrap(), "1.234");
assert_eq!(
format_value(&Value::Float(1234.5), "float", "pt-BR", None, None).unwrap(),
"1.234,50"
);
assert_eq!(
format_value(&Value::Float(1234.5), "float", "en-US", None, None).unwrap(),
"1,234.50"
);
}
#[test]
fn percent_and_currency() {
assert_eq!(format_value(&Value::Float(0.091), "percent", "pt-BR", None, None).unwrap(), "9,10%");
assert_eq!(
format_value(&Value::Float(1234.5), "currency", "pt-BR", None, None).unwrap(),
"R$\u{a0}1.234,50"
);
assert_eq!(
format_value(&Value::Float(1234.5), "currency", "en-US", None, None).unwrap(),
"$1,234.50"
);
assert_eq!(
format_value(&Value::Float(1234.5), "currency", "pt-BR", Some("EUR"), None).unwrap(),
"€\u{a0}1.234,50"
);
}
#[test]
fn currency_symbols_follow_babel_for_en_us_and_pt_br() {
let cases = [
("EGP", "en-US", "EGP1,234.50"),
("EGP", "pt-BR", "EGP\u{a0}1.234,50"),
("CNY", "en-US", "CN¥1,234.50"),
("AUD", "pt-BR", "AU$\u{a0}1.234,50"),
("JPY", "en-US", "¥1,234"),
("JPY", "pt-BR", "JP¥\u{a0}1.234"),
("RUB", "en-US", "RUB1,234.50"),
("PHP", "pt-BR", "PHP\u{a0}1.234,50"),
];
for (code, locale, expected) in cases {
assert_eq!(
format_value(&Value::Float(1234.5), "currency", locale, Some(code), None).unwrap(),
expected,
"{code} {locale}"
);
}
}
#[cfg(feature = "xlsx")]
#[test]
fn xlsx_currency_symbol_matches_babel() {
assert_eq!(xlsx_currency_symbol("EGP", "ar-EG"), "ج.م.\u{200f}");
assert_eq!(xlsx_currency_symbol("SAR", "ar-EG"), "ر.س.\u{200f}");
assert_eq!(xlsx_currency_symbol("ILS", "ar-EG"), "₪");
assert_eq!(xlsx_currency_symbol("EGP", "en-US"), "EGP");
assert_eq!(xlsx_currency_symbol("USD", "pt-BR"), "US$");
}
#[test]
fn bool_and_date_and_invalid() {
assert_eq!(format_value(&Value::Bool(true), "bool", "pt-BR", None, None).unwrap(), "Yes");
assert_eq!(
format_value(&Value::String("false".into()), "bool", "pt-BR", None, None).unwrap(),
"No"
);
assert_eq!(
format_value(&Value::String("abc".into()), "int", "pt-BR", None, None).unwrap(),
"abc"
);
assert_eq!(
format_value(&Value::String("01/12/2024".into()), "date", "en-US", None, None).unwrap(),
"01/12/2024"
);
}
#[test]
fn unknown_locale_fails_closed() {
assert!(format_value(&Value::Int(1), "int", "xx-YY", None, None).is_err());
assert!(format_value(&Value::Int(1), "int", "pt_BR", None, None).is_ok());
}
#[test]
fn locale_matrix_matches_python() {
use chrono::NaiveDate;
let date = Value::Date(NaiveDate::from_ymd_opt(2024, 12, 1).unwrap());
let cases = [
("pt-BR", "1.234,50", "R$\u{a0}1.234,50", "1 de dez. de 2024"),
("en-US", "1,234.50", "$1,234.50", "Dec 1, 2024"),
("de-DE", "1.234,50", "1.234,50\u{a0}€", "01.12.2024"),
("fr-FR", "1\u{202f}234,50", "1\u{202f}234,50\u{a0}€", "1 déc. 2024"),
("ja-JP", "1,234.50", "¥1,234", "2024/12/01"),
(
"ar-EG",
"1,234.50",
"\u{200f}1,234.50\u{a0}ج.م.\u{200f}",
"01\u{200f}/12\u{200f}/2024",
),
("he-IL", "1,234.50", "\u{200f}1,234.50\u{a0}\u{200f}₪", "1 בדצמ׳ 2024"),
("ru-RU", "1\u{a0}234,50", "1\u{a0}234,50\u{a0}₽", "1 дек. 2024\u{202f}г."),
("zh-CN", "1,234.50", "¥1,234.50", "2024年12月1日"),
("hi-IN", "1,234.50", "₹1,234.50", "1 दिस॰ 2024"),
("pt-PT", "1\u{a0}234,50", "1\u{a0}234,50\u{a0}\u{20ac}", "01/12/2024"),
("es-ES", "1.234,50", "1.234,50\u{a0}\u{20ac}", "1 dic 2024"),
("en-GB", "1,234.50", "£1,234.50", "1 Dec 2024"),
];
for (locale, number, currency, date_text) in cases {
assert_eq!(
format_value(&Value::Float(1234.5), "float", locale, None, None).unwrap(),
number,
"float {locale}"
);
assert_eq!(
format_value(&Value::Float(1234.5), "currency", locale, None, None).unwrap(),
currency,
"currency {locale}"
);
assert_eq!(format_value(&date, "date", locale, None, None).unwrap(), date_text, "date {locale}");
}
for (locale, five_digit) in [("pt-PT", "12\u{a0}345,50"), ("es-ES", "12.345,50")] {
assert_eq!(
format_value(&Value::Float(12345.5), "float", locale, None, None).unwrap(),
five_digit,
"five digits {locale}"
);
}
assert_eq!(format_value(&Value::Int(1234), "int", "pt-PT", None, None).unwrap(), "1\u{a0}234");
assert_eq!(
format_value(&Value::Float(-1234.5), "float", "es-ES", None, None).unwrap(),
"-1.234,50"
);
}
#[test]
fn field_text_and_substitutions() {
let field = value(json!({"missing_text": "n/a", "substitutions": {"A": "Active"}}));
assert_eq!(field_text(&Value::Null, Some(&field)).unwrap(), Some("n/a".into()));
assert_eq!(field_text(&Value::String("A".into()), Some(&field)).unwrap(), Some("Active".into()));
let number_field = value(json!({"substitutions": {"1": "one"}}));
assert_eq!(field_text(&Value::Int(1), Some(&number_field)).unwrap(), Some("one".into()));
}
#[test]
fn match_rule_operators() {
assert!(match_rule(&Value::Int(15), &value(json!({"gte": 10, "lt": 20})).as_object().unwrap().clone()).unwrap());
assert!(!match_rule(&Value::Int(25), &value(json!({"gte": 10, "lt": 20})).as_object().unwrap().clone()).unwrap());
assert!(match_rule(&Value::Int(10), &value(json!({"between": [10, 20]})).as_object().unwrap().clone()).unwrap());
assert!(match_rule(
&Value::String("cancelled by user".into()),
&value(json!({"contains": "cancel"})).as_object().unwrap().clone()
)
.unwrap());
assert!(match_rule(&Value::Null, &value(json!({"is_null": true})).as_object().unwrap().clone()).unwrap());
assert!(match_rule(&Value::Int(1), &value(json!({"no_op_here": true})).as_object().unwrap().clone()).is_err());
}
#[test]
fn cell_style_first_match_wins() {
let field = value(json!({"cell_rules": [{"lt": 0, "color": "#C00000", "bold": true}, {"lt": 100, "italic": true}]}));
let style = cell_style_dict(&Value::Int(-5), &field).unwrap();
assert_eq!(style.color.as_deref(), Some("#C00000"));
assert!(style.bold);
assert_eq!(cell_style(&Value::Int(-5), &field).unwrap(), "color:#C00000;font-weight:bold");
assert_eq!(cell_style(&Value::Int(50), &field).unwrap(), "font-style:italic");
}
#[test]
fn footnote_marks_sequence_and_reuse() {
let mut fields = vec![
Value::from_json(json!({"footnote": {"mark": null, "text": "First"}})),
Value::from_json(json!({"footnote": {"mark": null, "text": "Second"}})),
Value::from_json(json!({"footnote": {"mark": null, "text": "First"}})),
Value::from_json(json!({"footnote": {"mark": "‡", "text": "Pinned"}})),
];
let mut state = FootnoteState::default();
assign_footnote_marks(&mut fields, &mut state).unwrap();
let marks: Vec<&str> = fields
.iter()
.map(|field| {
field
.get("footnote")
.and_then(|note| note.get("mark"))
.and_then(Value::as_str)
.unwrap()
})
.collect();
assert_eq!(marks, ["*", "†", "*", "‡"]);
}
#[test]
fn color_scale_interpolation() {
assert_eq!(color_scale_fill(0.0, 0.0, 10.0, "#000000", "#FFFFFF"), "#000000");
assert_eq!(color_scale_fill(10.0, 0.0, 10.0, "#000000", "#FFFFFF"), "#FFFFFF");
assert_eq!(color_scale_fill(5.0, 0.0, 10.0, "#000000", "#FFFFFF"), "#808080");
assert_eq!(color_scale_fill(99.0, 0.0, 10.0, "#000000", "#FFFFFF"), "#FFFFFF");
}
#[test]
fn sparkline_blocks() {
assert_eq!(sparkline_text(&Value::from_json(json!([1, 2, 3, 4, 5, 6, 7, 8]))), "▁▂▃▄▅▆▇█");
assert_eq!(sparkline_text(&Value::Null), "");
}
#[test]
fn format_field_defaults_and_validation() {
let field = format_field("s", &value(json!({"label": "S"})).as_object().unwrap().clone()).unwrap();
assert_eq!(field.get("format_mask").and_then(Value::as_str), Some("str"));
assert_eq!(field.get("alignment").and_then(Value::as_str), Some("left"));
assert!(format_field("v", &value(json!({"label": "V", "data_bar": "yes"})).as_object().unwrap().clone()).is_err());
}
}
#[cfg(test)]
mod extra_tests {
use super::*;
use chrono::{DateTime, NaiveDate};
use serde_json::json;
fn value(value: serde_json::Value) -> Value {
Value::from_json(value)
}
#[test]
fn dates_and_datetimes_localize() {
let date = NaiveDate::from_ymd_opt(2024, 1, 2).unwrap();
let pt = format_date(date, "pt-BR").unwrap();
let en = format_date(date, "en-US").unwrap();
assert!(pt.contains("2024"), "{pt}");
assert!(en.contains("2024"), "{en}");
assert!(format_date(date, "xx-YY").is_err());
let datetime = DateTime::parse_from_rfc3339("2024-01-02T03:04:05+00:00").unwrap();
let formatted = format_datetime(&datetime, "en-US").unwrap();
assert!(formatted.contains("2024"), "{formatted}");
assert!(format_datetime(&datetime, "xx-YY").is_err());
}
#[test]
fn footnote_validation_and_assignment() {
assert_eq!(
normalize_footnote(&value(json!("Note")), "f").unwrap(),
Footnote {
mark: None,
text: "Note".into()
}
);
assert_eq!(
normalize_footnote(&value(json!({"mark": "†", "text": "Note"})), "f").unwrap(),
Footnote {
mark: Some("†".into()),
text: "Note".into()
}
);
assert!(normalize_footnote(&value(json!({"mark": "*"})), "f").is_err());
assert!(normalize_footnote(&value(json!({"text": ""})), "f").is_err());
assert!(normalize_footnote(&value(json!({"text": "x", "extra": 1})), "f").is_err());
assert!(normalize_footnote(&value(json!(123)), "f").is_err());
let mut fields = vec![
value(json!({"name": "a", "footnote": {"text": "One"}})),
value(json!({"name": "b", "footnote": {"text": "One"}})),
value(json!({"name": "c", "footnote": {"text": "Two"}})),
value(json!({"name": "d"})),
];
let mut state = FootnoteState::default();
assign_footnote_marks(&mut fields, &mut state).unwrap();
let marks: Vec<&str> = fields
.iter()
.filter_map(|field| field.get("footnote").and_then(|note| note.get("mark")).and_then(Value::as_str))
.collect();
assert_eq!(marks.len(), 3);
assert_eq!(marks[0], marks[1]);
assert_ne!(marks[0], marks[2]);
}
#[test]
fn visibility_rules() {
let rows = [value(json!({"x": 1})), value(json!({}))];
assert!(field_visible(&value(json!({"label": "A"})), &rows).unwrap());
assert!(!field_visible(&value(json!({"visible": false})), &rows).unwrap());
assert!(field_visible(&value(json!({"visible_when": {"field": "x", "equals": 1}})), &rows[..1]).unwrap());
assert!(!field_visible(
&value(json!({"visible_when": {"field": "x", "equals": 1}})),
&[value(json!({"x": 2})), value(json!({}))]
)
.unwrap());
assert!(field_visible(
&value(json!({"visible_when": {"field": "x", "not_null": true, "scope": "all"}})),
&rows[..1]
)
.unwrap());
assert!(!field_visible(
&value(json!({"visible_when": {"field": "x", "not_null": true, "scope": "all"}})),
&rows
)
.unwrap());
assert!(field_visible(&value(json!({"visible_when": {"equals": 1}})), &rows[..1]).is_err());
assert!(field_visible(
&value(json!({"visible_when": {"field": "x", "equals": 1, "scope": "many"}})),
&rows[..1]
)
.is_err());
}
#[test]
fn color_and_style_edges() {
assert!(normalize_color_scale(&value(json!({"min": "#000000"})), "f").is_err());
assert!(normalize_color_scale(&value(json!({"min": "#000000", "max": "#ffffff", "extra": 1})), "f").is_err());
assert!(normalize_color_scale(&value(json!({"min": "#zzzzzz", "max": "#ffffff"})), "f").is_err());
assert!(normalize_color_scale(&value(json!(5)), "f").is_err());
assert_eq!(parse_hex_color(&value(json!("#abc")), "f").unwrap(), (170, 187, 204));
assert!(parse_hex_color(&value(json!("red")), "f").is_err());
assert!(parse_hex_color(&value(json!("#12")), "f").is_err());
let field = value(json!({"cell_rules": [{"lt": 0, "color": "#C00000", "background": "#FFFF00", "bold": true, "italic": true}]}));
let style = cell_style_dict(&Value::Int(-1), &field).unwrap();
assert_eq!(style.color.as_deref(), Some("#C00000"));
assert_eq!(style.background.as_deref(), Some("#FFFF00"));
assert!(style.bold && style.italic);
assert!(cell_style(&Value::Int(-1), &field).unwrap().contains("color:#C00000"));
let no_rules = value(json!({"cell_rules": [{"gt": 0}]}));
assert!(cell_style_dict(&Value::Int(-1), &no_rules).unwrap().color.is_none());
assert!(cell_style_dict(&Value::Int(-1), &Value::Null).unwrap().color.is_none());
assert!(
!cell_style_dict(&Value::Int(-1), &value(json!({"cell_rules": [{"lt": "x"}]})))
.unwrap()
.bold
);
}
#[test]
fn format_edges_and_defaults() {
assert_eq!(
format_value(&Value::String("x".into()), "unknown", "pt-BR", None, None).unwrap(),
"x"
);
assert_eq!(
format_value(&Value::String("no".into()), "bool", "pt-BR", None, None).unwrap(),
"No"
);
assert_eq!(
format_value(&Value::String("yes".into()), "bool", "pt-BR", None, None).unwrap(),
"Yes"
);
assert_eq!(
format_value(&Value::String("01/12/2024".into()), "date", "en-US", None, None).unwrap(),
"01/12/2024"
);
assert_eq!(
format_value(&Value::String("abc".into()), "float", "en-US", None, None).unwrap(),
"abc"
);
assert_eq!(
format_value(&Value::Int(3), "sparkline", "en-US", None, None)
.unwrap()
.matches("<circle")
.count(),
1
);
assert_eq!(format_currency(10.0, "JPY", "en-US").unwrap(), "¥10");
assert!(format_currency(1.0, "USD", "xx-YY").is_err());
assert_eq!(normalize_locale("pt_BR").unwrap(), "pt-BR");
assert_eq!(default_currency("pt-BR").unwrap(), "BRL");
assert_eq!(default_currency("en-US").unwrap(), "USD");
assert!(default_currency("xx-YY").is_err());
}
}