1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
use super::{deg, percent, Angle, Color, Ratio, RGB, RGBA};
use std::fmt;

/// Constructs a HSL Color from numerical values, similar to the
/// [`hsl` function](css-hsl) in CSS.
///
/// The hue component is expressed in degrees. Values outside of
/// the 0-359° range will be normalized accordingly. The saturation
/// and lightness components are expressed in percentages. Values
/// outside of the 0-100% range will cause a panic.
///
/// # Example
/// ```
/// use farver::{Color, hsl};
///
/// let salmon = hsl(6, 93, 71);
///
/// assert_eq!(salmon.to_css(), "hsl(6, 93%, 71%)");
/// ```
///
/// [css-hsl]: https://www.w3.org/TR/css-color-3/#hsl-color
pub fn hsl(h: i32, s: u8, l: u8) -> HSL {
    HSL {
        h: deg(h),
        s: percent(s),
        l: percent(l),
    }
}

/// Constructs a HSLA Color from numerical values, similar to the
/// [`hsla` function](css-hsla) in CSS.
///
/// The hue component is expressed in degrees. Values outside of
/// the 0-359° range will be normalized accordingly. The saturation
/// and lightness components are expressed in percentages. Values
/// outside of the 0-100% range will cause a panic. The alpha value
/// is expressed as a float. Values outside of the 0.0-1.0 range will
/// cause a panic.
///
/// # Example
/// ```
/// use farver::{Color, hsla};
///
/// let salmon = hsla(6, 93, 71, 0.50);
///
/// assert_eq!(salmon.to_css(), "hsla(6, 93%, 71%, 0.50)");
/// ```
///
/// [css-hsla]: https://www.w3.org/TR/css-color-3/#hsla-color
pub fn hsla(h: i32, s: u8, l: u8, a: f32) -> HSLA {
    HSLA {
        h: deg(h),
        s: percent(s),
        l: percent(l),
        a: Ratio::from_f32(a),
    }
}

#[derive(Debug, Copy, Clone, PartialEq, Eq)]
/// A struct to represent how much hue, saturation, and luminosity should be added to create a color.
/// The hue is a degree on the color wheel; 0 (or 360) is red, 120 is green, 240 is blue.
/// A valid value for `h` must range between `0-360`.
/// The saturation ranges between `0-100`, where `0` is completely desaturated, and `100` is full saturation.
/// The luminosity ranges between `0-100`, where `0` is no light (black), and `100` is full light (white).
///
/// For more, see the [CSS Color Spec](https://www.w3.org/TR/2018/REC-css-color-3-20180619/#hsl-color).
pub struct HSL {
    // hue
    pub h: Angle,

    // saturation
    pub s: Ratio,

    // luminosity
    pub l: Ratio,
}

impl fmt::Display for HSL {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "hsl({}, {}, {})", self.h.degrees(), self.s, self.l)
    }
}

impl Color for HSL {
    type Alpha = HSLA;

    fn to_css(self) -> String {
        self.to_string()
    }

    fn to_hex(self) -> String {
        self.to_rgb().to_hex()
    }

    fn to_rgb(self) -> RGB {
        self.to_hsla().to_rgb()
    }

    fn to_rgba(self) -> RGBA {
        self.to_hsla().to_rgba()
    }

    fn to_hsl(self) -> HSL {
        self
    }

    fn to_hsla(self) -> HSLA {
        let HSL { h, s, l } = self;

        HSLA {
            h,
            s,
            l,
            a: percent(100),
        }
    }

    fn saturate(self, amount: Ratio) -> Self {
        self.to_hsla().saturate(amount).to_hsl()
    }

    fn desaturate(self, amount: Ratio) -> Self {
        self.to_hsla().desaturate(amount).to_hsl()
    }

    fn lighten(self, amount: Ratio) -> Self {
        self.to_hsla().lighten(amount).to_hsl()
    }

    fn darken(self, amount: Ratio) -> Self {
        self.to_hsla().darken(amount).to_hsl()
    }

    fn fadein(self, amount: Ratio) -> Self::Alpha {
        self.to_hsla().fadein(amount)
    }

    fn fadeout(self, amount: Ratio) -> Self::Alpha {
        self.to_hsla().fadeout(amount)
    }

    fn fade(self, amount: Ratio) -> Self::Alpha {
        self.to_hsla().fade(amount)
    }

    fn spin(self, amount: Angle) -> Self {
        self.to_hsla().spin(amount).to_hsl()
    }

    fn mix<T: Color>(self, other: T, weight: Ratio) -> Self::Alpha {
        self.to_hsla().mix(other, weight)
    }

    fn tint(self, weight: Ratio) -> Self {
        self.to_hsla().tint(weight).to_hsl()
    }

    fn shade(self, weight: Ratio) -> Self {
        self.to_hsla().shade(weight).to_hsl()
    }

    fn greyscale(self) -> Self {
        self.to_hsla().greyscale().to_hsl()
    }
}

// A function to convert an HSL value (either h, s, or l) into the equivalent, valid RGB value.
fn to_rgb_value(val: u16, temp_1: f32, temp_2: f32) -> f32 {
    let value = val as f32 / 360.0;

    if value > (2.0 / 3.0) {
        // value > 0.66667
        temp_2
    } else if value > (1.0 / 2.0) {
        // value is between 0.5 and 0.66667
        temp_2 + ((temp_1 - temp_2) * ((2.0 / 3.0) - value) * 6.0)
    } else if value > (1.0 / 6.0) {
        // value is between 0.16667 and 0.5
        temp_1
    } else {
        // value <= 0.16667
        temp_2 + ((temp_1 - temp_2) * value * 6.0)
    }
}

#[derive(Debug, Copy, Clone, PartialEq, Eq)]
/// A struct to represent how much hue, saturation, and luminosity should be added to create a color.
/// Also handles alpha specifications.
///
/// A valid value for `h` must range between `0-360`.
/// The saturation ranges between `0-100`, where `0` is completely desaturated, and `100` is full saturation.
/// The luminosity ranges between `0-100`, where `0` is no light (black), and `100` is full light (white).
///
/// For more, see the [CSS Color Spec](https://www.w3.org/TR/2018/REC-css-color-3-20180619/#hsla-color).
pub struct HSLA {
    // hue
    pub h: Angle,

    // saturation
    pub s: Ratio,

    // luminosity
    pub l: Ratio,

    // alpha
    pub a: Ratio,
}

impl fmt::Display for HSLA {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "hsla({}, {}, {}, {:.02})",
            self.h.degrees(),
            self.s,
            self.l,
            self.a.as_f32()
        )
    }
}

impl Color for HSLA {
    type Alpha = Self;

    fn to_css(self) -> String {
        self.to_string()
    }

    fn to_hex(self) -> String {
        self.to_rgba().to_hex()
    }

    fn to_rgb(self) -> RGB {
        self.to_rgba().to_rgb()
    }

    fn to_rgba(self) -> RGBA {
        let HSLA { h, s, l, a } = self;

        // If there is no saturation, the color is a shade of grey.
        // We can convert the luminosity and set r, g, and b to that value.
        if s == percent(0) {
            return RGBA {
                r: l,
                g: l,
                b: l,
                a,
            };
        }

        let s = s.as_f32();
        let l = l.as_f32();

        // If the color is not a grey, then we need to create a temporary variable to continue with the algorithm.
        // If the luminosity is less than 50%, we add 1.0 to the saturation and multiply by the luminosity.
        // Otherwise, we add the luminosity and saturation, and subtract the product of luminosity and saturation from it.
        let temp_1 = if l < 0.5 {
            l * (1.0 + s)
        } else {
            (l + s) - (l * s)
        };

        // Another temporary variable.
        let temp_2 = (2.0 * l) - temp_1;

        // Create a rotation of 120 degrees in order to divide the angle into thirds.
        let rotation = Angle::new(120);

        // Then rotate the circle clockwise by 1/3 for the red value, and by 2/3rds for the blue value.
        let temporary_r = (h + rotation).degrees();
        let temporary_g = h.degrees();
        let temporary_b = (h - rotation).degrees();

        let red = to_rgb_value(temporary_r, temp_1, temp_2);
        let green = to_rgb_value(temporary_g, temp_1, temp_2);
        let blue = to_rgb_value(temporary_b, temp_1, temp_2);

        RGBA {
            r: Ratio::from_f32(red),
            g: Ratio::from_f32(green),
            b: Ratio::from_f32(blue),
            a,
        }
    }

    fn to_hsl(self) -> HSL {
        let HSLA { h, s, l, .. } = self;
        HSL { h, s, l }
    }

    fn to_hsla(self) -> HSLA {
        self
    }

    fn saturate(self, amount: Ratio) -> Self {
        let HSLA { h, s, l, a } = self;

        HSLA {
            h,
            s: s + amount,
            l,
            a,
        }
    }

    fn desaturate(self, amount: Ratio) -> Self {
        let HSLA { h, s, l, a } = self;

        HSLA {
            h,
            s: s - amount,
            l,
            a,
        }
    }

    fn lighten(self, amount: Ratio) -> Self {
        let HSLA { h, s, l, a } = self;

        HSLA {
            h,
            s,
            l: l + amount,
            a,
        }
    }

    fn darken(self, amount: Ratio) -> Self {
        let HSLA { h, s, l, a } = self;

        HSLA {
            h,
            s,
            l: l - amount,
            a,
        }
    }

    fn fadein(self, amount: Ratio) -> Self {
        self.fade(self.a + amount)
    }

    fn fadeout(self, amount: Ratio) -> Self {
        self.fade(self.a - amount)
    }

    fn fade(self, amount: Ratio) -> Self::Alpha {
        let HSLA { h, s, l, .. } = self;
        HSLA { h, s, l, a: amount }
    }

    fn spin(self, amount: Angle) -> Self {
        let HSLA { h, s, l, a } = self;

        HSLA {
            h: h + amount,
            s,
            l,
            a,
        }
    }

    fn mix<T: Color>(self, other: T, weight: Ratio) -> Self::Alpha {
        self.to_rgba().mix(other, weight).to_hsla()
    }

    fn tint(self, weight: Ratio) -> Self {
        self.to_rgba().tint(weight).to_hsla()
    }

    fn shade(self, weight: Ratio) -> Self {
        self.to_rgba().shade(weight).to_hsla()
    }

    fn greyscale(self) -> Self {
        let HSLA { h, l, a, .. } = self;

        HSLA {
            h,
            s: percent(0),
            l,
            a,
        }
    }
}