Skip to main content

leptos_css/
color.rs

1use std::fmt;
2
3use crate::checked_value::impl_checked_value;
4use crate::{
5    FiniteF64, InvalidCssNumber, PercentageChannel, UnitInterval,
6    number::{assert_finite, try_finite},
7    serialization::CssWriteTo,
8};
9
10/// CSS named-color keywords supported by the typed API.
11///
12/// This deliberately uses an enum instead of accepting arbitrary strings. More names can be
13/// added without weakening the invariant that every represented value is a valid `<color>`.
14#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
15#[non_exhaustive]
16pub enum CssColorName {
17    /// `transparent`.
18    Transparent,
19    /// `currentcolor`.
20    CurrentColor,
21    /// `black`.
22    Black,
23    /// `silver`.
24    Silver,
25    /// `gray`.
26    Gray,
27    /// `white`.
28    White,
29    /// `maroon`.
30    Maroon,
31    /// `red`.
32    Red,
33    /// `purple`.
34    Purple,
35    /// `fuchsia`.
36    Fuchsia,
37    /// `green`.
38    Green,
39    /// `lime`.
40    Lime,
41    /// `olive`.
42    Olive,
43    /// `yellow`.
44    Yellow,
45    /// `navy`.
46    Navy,
47    /// `blue`.
48    Blue,
49    /// `teal`.
50    Teal,
51    /// `aqua`.
52    Aqua,
53}
54
55impl CssColorName {
56    /// Return the CSS keyword.
57    pub const fn as_str(self) -> &'static str {
58        match self {
59            Self::Transparent => "transparent",
60            Self::CurrentColor => "currentcolor",
61            Self::Black => "black",
62            Self::Silver => "silver",
63            Self::Gray => "gray",
64            Self::White => "white",
65            Self::Maroon => "maroon",
66            Self::Red => "red",
67            Self::Purple => "purple",
68            Self::Fuchsia => "fuchsia",
69            Self::Green => "green",
70            Self::Lime => "lime",
71            Self::Olive => "olive",
72            Self::Yellow => "yellow",
73            Self::Navy => "navy",
74            Self::Blue => "blue",
75            Self::Teal => "teal",
76            Self::Aqua => "aqua",
77        }
78    }
79}
80
81/// CSS color values from [CSS Color Level 4].
82///
83/// [CSS Color Level 4]: https://www.w3.org/TR/css-color-4/#color-syntax
84#[derive(Clone, Copy, Debug, PartialEq)]
85#[non_exhaustive]
86pub enum CssColor {
87    /// RGB color (e.g., `rgb(255, 128, 0)`).
88    Rgb(u8, u8, u8),
89    /// RGBA color with alpha (e.g., `rgba(255, 128, 0, 0.5)`).
90    Rgba(u8, u8, u8, UnitInterval),
91    /// HSL color (e.g., `hsl(120, 100%, 50%)`).
92    /// Hue in degrees (any finite value; CSS wraps it around the 0-360 degree color wheel),
93    /// saturation and lightness as percentages (0-100).
94    Hsl(FiniteF64, PercentageChannel, PercentageChannel),
95    /// HSLA color with alpha (e.g., `hsla(120, 100%, 50%, 0.5)`).
96    /// Hue in degrees (any finite value; CSS wraps it around the 0-360 degree color wheel),
97    /// saturation and lightness as percentages (0-100), alpha (0.0-1.0).
98    Hsla(
99        FiniteF64,
100        PercentageChannel,
101        PercentageChannel,
102        UnitInterval,
103    ),
104    /// A CSS named color.
105    Named(CssColorName),
106}
107
108impl CssWriteTo for CssColor {
109    #[allow(clippy::many_single_char_names)]
110    fn css_fmt<W: fmt::Write>(&self, w: &mut W) -> fmt::Result {
111        match self {
112            Self::Rgb(r, g, b) => write!(w, "rgb({r}, {g}, {b})"),
113            Self::Rgba(r, g, b, a) => write!(w, "rgba({r}, {g}, {b}, {a})"),
114            Self::Hsl(h, s, l) => write!(w, "hsl({h}, {s}%, {l}%)"),
115            Self::Hsla(h, s, l, a) => write!(w, "hsla({h}, {s}%, {l}%, {a})"),
116            Self::Named(name) => w.write_str(name.as_str()),
117        }
118    }
119}
120
121/// Create a CSS RGB color value.
122pub const fn rgb(r: u8, g: u8, b: u8) -> CssColor {
123    CssColor::Rgb(r, g, b)
124}
125
126/// Create a CSS RGBA color value with alpha.
127///
128/// # Panics
129///
130/// Panics if `a` is `NaN`, infinite, or outside the inclusive range `[0.0, 1.0]`.
131pub fn rgba(r: u8, g: u8, b: u8, a: f64) -> CssColor {
132    CssColor::Rgba(r, g, b, UnitInterval::new(a))
133}
134
135/// Attempt to create a CSS RGBA color value with alpha.
136///
137/// # Errors
138///
139/// Returns an error if `a` is `NaN`, infinite, or outside the inclusive range `[0.0, 1.0]`.
140pub fn try_rgba(r: u8, g: u8, b: u8, a: f64) -> Result<CssColor, InvalidCssNumber> {
141    UnitInterval::try_new(a).map(|a| CssColor::Rgba(r, g, b, a))
142}
143
144/// Create a CSS HSL color value.
145///
146/// * `h` - Any finite hue in degrees; CSS wraps it around the 0-360 degree color wheel.
147/// * `s` - Saturation as a percentage (0-100).
148/// * `l` - Lightness as a percentage (0-100).
149///
150/// # Panics
151///
152/// Panics if `h` is `NaN` or infinite, or if `s` or `l` is outside the inclusive range
153/// `[0.0, 100.0]`.
154pub fn hsl(h: impl Into<f64>, s: impl Into<f64>, l: impl Into<f64>) -> CssColor {
155    let h = h.into();
156    let s = s.into();
157    let l = l.into();
158    CssColor::Hsl(
159        assert_finite(h, "hsl hue"),
160        PercentageChannel::new(s),
161        PercentageChannel::new(l),
162    )
163}
164
165/// Attempt to create a CSS HSL color value.
166///
167/// # Errors
168///
169/// Returns an error if `h` is non-finite or if `s` or `l` is non-finite or outside the
170/// inclusive range `[0.0, 100.0]`.
171pub fn try_hsl(
172    h: impl Into<f64>,
173    s: impl Into<f64>,
174    l: impl Into<f64>,
175) -> Result<CssColor, InvalidCssNumber> {
176    let h = try_finite(h.into(), "hsl hue")?;
177    let s = PercentageChannel::try_new(s.into())?;
178    let l = PercentageChannel::try_new(l.into())?;
179    Ok(CssColor::Hsl(h, s, l))
180}
181
182/// Create a CSS HSLA color value with alpha.
183///
184/// * `h` - Any finite hue in degrees; CSS wraps it around the 0-360 degree color wheel.
185/// * `s` - Saturation as a percentage (0-100).
186/// * `l` - Lightness as a percentage (0-100).
187/// * `a` - Alpha (0.0-1.0).
188///
189/// # Panics
190///
191/// Panics if `h` is `NaN` or infinite, if `s` or `l` is outside `[0.0, 100.0]`, or if `a`
192/// is outside `[0.0, 1.0]`.
193pub fn hsla(
194    h: impl Into<f64>,
195    s: impl Into<f64>,
196    l: impl Into<f64>,
197    a: impl Into<f64>,
198) -> CssColor {
199    let h = h.into();
200    let s = s.into();
201    let l = l.into();
202    let a = a.into();
203    CssColor::Hsla(
204        assert_finite(h, "hsla hue"),
205        PercentageChannel::new(s),
206        PercentageChannel::new(l),
207        UnitInterval::new(a),
208    )
209}
210
211/// Attempt to create a CSS HSLA color value.
212///
213/// # Errors
214///
215/// Returns an error if `h` is non-finite, or if `s`, `l`, or `a` is non-finite or outside
216/// its documented inclusive range.
217pub fn try_hsla(
218    h: impl Into<f64>,
219    s: impl Into<f64>,
220    l: impl Into<f64>,
221    a: impl Into<f64>,
222) -> Result<CssColor, InvalidCssNumber> {
223    let h = try_finite(h.into(), "hsla hue")?;
224    let s = PercentageChannel::try_new(s.into())?;
225    let l = PercentageChannel::try_new(l.into())?;
226    let a = UnitInterval::try_new(a.into())?;
227    Ok(CssColor::Hsla(h, s, l, a))
228}
229
230impl_checked_value!(CssColor);