use crate::color::Color;
use crate::spaces::Hsl;
fn hsl_of(color: &Color) -> Hsl {
if let Color::Hsl(c) = color {
return *c;
}
match color.convert_to("hsl") {
Some(Color::Hsl(c)) => c,
_ => unreachable!("convert_to(\"hsl\") returns Color::Hsl for any known mode"),
}
}
fn two_decimals(value: f64) -> f64 {
if value.is_nan() {
0.0
} else {
(value * 100.0).round() / 100.0
}
}
fn clamp01(value: f64) -> f64 {
if value.is_nan() {
0.0
} else {
value.clamp(0.0, 1.0)
}
}
pub fn format_hsl(color: &Color) -> String {
let hsl = hsl_of(color);
let h = two_decimals(if hsl.h.is_nan() { 0.0 } else { hsl.h });
let s = two_decimals(clamp01(hsl.s) * 100.0);
let l = two_decimals(clamp01(hsl.l) * 100.0);
match hsl.alpha {
None | Some(1.0) => format!("hsl({}, {}%, {}%)", h, s, l),
Some(a) => {
let clamped = if a.is_nan() { 0.0 } else { a.clamp(0.0, 1.0) };
let rounded = two_decimals(clamped);
format!("hsla({}, {}%, {}%, {})", h, s, l, rounded)
}
}
}