pub type Rgba = [u8; 4];
pub struct Color;
impl Color {
pub fn parse(color: &str) -> laravel::Result<Rgba> {
let color = color.trim().to_lowercase();
if let Some(hex) = color.strip_prefix('#')
&& hex.chars().all(|c| c.is_ascii_hexdigit())
&& matches!(hex.len(), 3 | 6 | 8)
{
return Ok(Self::hex(hex));
}
if let Some(parsed) = Self::functional(&color) {
return Ok(parsed);
}
Err(laravel::Error::msg(format!(
"Laracards: unsupported colour [{color}]. Use #rgb, #rrggbb, #rrggbbaa, rgb() or rgba()."
)))
}
fn hex(hex: &str) -> Rgba {
let expanded: String = if hex.len() == 3 {
hex.chars().flat_map(|c| [c, c]).collect()
} else {
hex.to_owned()
};
let channel = |at: usize| u8::from_str_radix(&expanded[at..at + 2], 16).unwrap_or(0);
let alpha = if expanded.len() == 8 { channel(6) } else { 255 };
[channel(0), channel(2), channel(4), alpha]
}
fn functional(color: &str) -> Option<Rgba> {
let inner = color
.strip_prefix("rgba(")
.or_else(|| color.strip_prefix("rgb("))?
.strip_suffix(')')?;
let parts: Vec<&str> = inner.split(',').map(str::trim).collect();
if !matches!(parts.len(), 3 | 4) {
return None;
}
let channel = |part: &str| {
(!part.is_empty() && part.len() <= 3 && part.chars().all(|c| c.is_ascii_digit()))
.then(|| part.parse::<u16>().map_or(255, |value| value.min(255)) as u8)
};
let opacity = match parts.get(3) {
Some(part) if !part.is_empty() && part.chars().all(|c| c.is_ascii_digit() || c == '.') => {
part.parse::<f64>().ok()?
}
Some(_) => return None,
None => 1.0,
};
Some([
channel(parts[0])?,
channel(parts[1])?,
channel(parts[2])?,
(opacity.clamp(0.0, 1.0) * 255.0).round() as u8,
])
}
}