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
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
#![doc(html_favicon_url = "https://raw.githubusercontent.com/zng-ui/zng/main/examples/image/res/zng-logo-icon.png")]
#![doc(html_logo_url = "https://raw.githubusercontent.com/zng-ui/zng/main/examples/image/res/zng-logo.png")]
//!
//! Color and gradient types, functions and macros, [`Rgba`], [`filter`], [`hex!`] and more.
//!
//! # Crate
//!
#![doc = include_str!(concat!("../", std::env!("CARGO_PKG_README")))]
#![warn(unused_extern_crates)]
#![warn(missing_docs)]
#![recursion_limit = "256"]

use std::{fmt, sync::Arc};
use zng_app_context::context_local;

use zng_layout::unit::{about_eq, about_eq_hash, AngleDegree, Factor};
use zng_var::{
    animation::{easing::EasingStep, Transition, Transitionable},
    context_var, impl_from_and_into_var, merge_var, IntoVar, Var, VarValue,
};

pub use zng_view_api::config::ColorScheme;

#[doc(hidden)]
pub use zng_color_proc_macros::hex_color;

pub use zng_layout::unit::{Rgba, RgbaComponent};

pub mod colors;
pub mod filter;
pub mod gradient;
pub mod web_colors;

mod mix;
pub use mix::*;

/// Hexadecimal color literal.
///
/// # Syntax
///
/// `[#|0x]RRGGBB[AA]` or `[#|0x]RGB[A]`.
///
/// An optional prefix `#` or `0x` is supported, after the prefix a hexadecimal integer literal is expected. The literal can be
/// separated using `_`. No integer type suffix is allowed.
///
/// The literal is a sequence of 3 or 4 bytes (red, green, blue and alpha). If the sequence is in pairs each pair is a byte `[00..=FF]`.
/// If the sequence is in single characters this is a shorthand that repeats the character for each byte, e.g. `#012F` equals `#001122FF`.
///
/// # Examples
///
/// ```
/// # use zng_color::hex;
/// let red = hex!(#FF0000);
/// let green = hex!(#00FF00);
/// let blue = hex!(#0000FF);
/// let red_half_transparent = hex!(#FF00007F);
///
/// assert_eq!(red, hex!(#F00));
/// assert_eq!(red, hex!(0xFF_00_00));
/// assert_eq!(red, hex!(FF_00_00));
/// ```
///
#[macro_export]
macro_rules! hex {
    ($($tt:tt)+) => {
        $crate::hex_color!{$crate, $($tt)*}
    };
}

/// Minimal difference between values in around the 0.0..=1.0 scale.
const EPSILON: f32 = 0.00001;
/// Minimal difference between values in around the 1.0..=100.0 scale.
const EPSILON_100: f32 = 0.001;

fn lerp_rgba_linear(mut from: Rgba, to: Rgba, factor: Factor) -> Rgba {
    from.red = from.red.lerp(&to.red, factor);
    from.green = from.green.lerp(&to.green, factor);
    from.blue = from.blue.lerp(&to.blue, factor);
    from.alpha = from.alpha.lerp(&to.alpha, factor);
    from
}

/// Default implementation of lerp for [`Rgba`] in apps.
///
/// Implements [`lerp_space`] dependent transition.
///
/// Apps set this as the default implementation on init.
pub fn lerp_rgba(from: Rgba, to: Rgba, factor: Factor) -> Rgba {
    match lerp_space() {
        LerpSpace::HslaChromatic => Hsla::from(from).slerp_chromatic(to.into(), factor).into(),
        LerpSpace::Rgba => lerp_rgba_linear(from, to, factor),
        LerpSpace::Hsla => Hsla::from(from).slerp(to.into(), factor).into(),
        LerpSpace::HslaLinear => Hsla::from(from).lerp_hsla(to.into(), factor).into(),
    }
}

/// Pre-multiplied RGB + alpha.
///
/// Use from/into conversion to create.
#[derive(Clone, Copy, Debug, serde::Serialize, serde::Deserialize)]
pub struct PreMulRgba {
    /// [`Rgba::red`] multiplied by `alpha`.
    pub red: f32,
    /// [`Rgba::green`] multiplied by `alpha`.
    pub green: f32,
    /// [`Rgba::blue`] multiplied by `alpha`.
    pub blue: f32,
    /// Alpha channel value, in the `[0.0..=1.0]` range.
    pub alpha: f32,
}
impl PartialEq for PreMulRgba {
    fn eq(&self, other: &Self) -> bool {
        about_eq(self.red, other.red, EPSILON)
            && about_eq(self.green, other.green, EPSILON)
            && about_eq(self.blue, other.blue, EPSILON)
            && about_eq(self.alpha, other.alpha, EPSILON)
    }
}
impl std::hash::Hash for PreMulRgba {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        about_eq_hash(self.red, EPSILON, state);
        about_eq_hash(self.green, EPSILON, state);
        about_eq_hash(self.blue, EPSILON, state);
        about_eq_hash(self.alpha, EPSILON, state);
    }
}

impl_from_and_into_var! {
    fn from(c: Rgba) -> PreMulRgba {
        PreMulRgba {
            red: c.red * c.alpha,
            green: c.green * c.alpha,
            blue: c.blue * c.alpha,
            alpha: c.alpha,
        }
    }

    fn from(c: PreMulRgba) -> Rgba {
        Rgba {
            red: c.red / c.alpha,
            green: c.green / c.alpha,
            blue: c.blue / c.alpha,
            alpha: c.alpha,
        }
    }

    fn from(c: Hsla) -> PreMulRgba {
        Rgba::from(c).into()
    }

    fn from(c: PreMulRgba) -> Hsla {
        Rgba::from(c).into()
    }

    fn from(c: Hsva) -> PreMulRgba {
        Rgba::from(c).into()
    }

    fn from(c: PreMulRgba) -> Hsva {
        Rgba::from(c).into()
    }
}

/// HSL + alpha.
///
/// # Equality
///
/// Equality is determined using [`about_eq`] with `0.001` epsilon for [`hue`](Hsla::hue)
/// and `0.00001` epsilon for the others.
///
/// [`about_eq`]: zng_layout::unit::about_eq
#[derive(Copy, Clone, serde::Serialize, serde::Deserialize)]
pub struct Hsla {
    /// Hue color angle in the `[0.0..=360.0]` range.
    pub hue: f32,
    /// Saturation amount in the `[0.0..=1.0]` range, zero is gray, one is full color.
    pub saturation: f32,
    /// Lightness amount in the `[0.0..=1.0]` range, zero is black, one is white.
    pub lightness: f32,
    /// Alpha channel in the `[0.0..=1.0]` range, zero is invisible, one is opaque.
    pub alpha: f32,
}
impl PartialEq for Hsla {
    fn eq(&self, other: &Self) -> bool {
        about_eq(self.hue, other.hue, EPSILON_100)
            && about_eq(self.saturation, other.saturation, EPSILON)
            && about_eq(self.lightness, other.lightness, EPSILON)
            && about_eq(self.alpha, other.alpha, EPSILON)
    }
}
impl std::hash::Hash for Hsla {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        about_eq_hash(self.hue, EPSILON_100, state);
        about_eq_hash(self.saturation, EPSILON, state);
        about_eq_hash(self.lightness, EPSILON, state);
        about_eq_hash(self.alpha, EPSILON, state);
    }
}
impl Hsla {
    /// Sets the [`hue`](Self::hue) color angle.
    ///
    /// The value is normalized to be in the `[0.0..=360.0]` range, that is `362.deg()` becomes `2.0`.
    pub fn set_hue<H: Into<AngleDegree>>(&mut self, hue: H) {
        self.hue = hue.into().modulo().0
    }

    /// Sets the [`lightness`](Self::lightness) value.
    pub fn set_lightness<L: Into<Factor>>(&mut self, lightness: L) {
        self.lightness = lightness.into().0;
    }

    /// Sets the [`saturation`](Self::saturation) value.
    pub fn set_saturation<S: Into<Factor>>(&mut self, saturation: S) {
        self.saturation = saturation.into().0;
    }

    /// Sets the [`alpha`](Self::alpha) value.
    pub fn set_alpha<A: Into<Factor>>(&mut self, alpha: A) {
        self.alpha = alpha.into().0
    }

    /// Returns a copy of this color with a new `hue`.
    pub fn with_hue<H: Into<AngleDegree>>(mut self, hue: H) -> Self {
        self.set_hue(hue);
        self
    }

    /// Returns a copy of this color with a new `lightness`.
    pub fn with_lightness<L: Into<Factor>>(mut self, lightness: L) -> Self {
        self.set_lightness(lightness);
        self
    }

    /// Returns a copy of this color with a new `saturation`.
    pub fn with_saturation<S: Into<Factor>>(mut self, saturation: S) -> Self {
        self.set_saturation(saturation);
        self
    }

    /// Returns a copy of this color with a new `alpha`.
    pub fn with_alpha<A: Into<Factor>>(mut self, alpha: A) -> Self {
        self.set_alpha(alpha);
        self
    }

    fn lerp_sla(mut self, to: Hsla, factor: Factor) -> Self {
        self.saturation = self.saturation.lerp(&to.saturation, factor);
        self.lightness = self.lightness.lerp(&to.lightness, factor);
        self.alpha = self.alpha.lerp(&to.alpha, factor);
        self
    }

    /// Interpolate in the [`LerpSpace::Hsla`] mode.
    pub fn slerp(mut self, to: Self, factor: Factor) -> Self {
        self = self.lerp_sla(to, factor);
        self.hue = AngleDegree(self.hue).slerp(AngleDegree(to.hue), factor).0;
        self
    }

    /// If the saturation is more than zero.
    ///
    /// If `false` the color is achromatic, the hue value does not affect the color.
    pub fn is_chromatic(self) -> bool {
        self.saturation > 0.0001
    }

    /// Interpolate in the [`LerpSpace::HslaChromatic`] mode.
    pub fn slerp_chromatic(mut self, to: Self, factor: Factor) -> Self {
        if self.is_chromatic() && to.is_chromatic() {
            self.slerp(to, factor)
        } else {
            self = self.lerp_sla(to, factor);
            if to.is_chromatic() {
                self.hue = to.hue;
            }
            self
        }
    }

    fn lerp_hsla(mut self, to: Self, factor: Factor) -> Self {
        self = self.lerp_sla(to, factor);
        self.hue = self.hue.lerp(&to.hue, factor);
        self
    }

    fn lerp(self, to: Self, factor: Factor) -> Self {
        match lerp_space() {
            LerpSpace::HslaChromatic => self.slerp_chromatic(to, factor),
            LerpSpace::Rgba => lerp_rgba_linear(self.into(), to.into(), factor).into(),
            LerpSpace::Hsla => self.slerp(to, factor),
            LerpSpace::HslaLinear => self.lerp_hsla(to, factor),
        }
    }
}
impl fmt::Debug for Hsla {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if f.alternate() {
            f.debug_struct("Hsla")
                .field("hue", &self.hue)
                .field("saturation", &self.saturation)
                .field("lightness", &self.lightness)
                .field("alpha", &self.alpha)
                .finish()
        } else {
            fn p(n: f32) -> f32 {
                clamp_normal(n) * 100.0
            }
            let a = p(self.alpha);
            let h = AngleDegree(self.hue).modulo().0.round();
            if (a - 100.0).abs() <= EPSILON {
                write!(f, "hsl({h}.deg(), {}.pct(), {}.pct())", p(self.saturation), p(self.lightness))
            } else {
                write!(
                    f,
                    "hsla({h}.deg(), {}.pct(), {}.pct(), {}.pct())",
                    p(self.saturation),
                    p(self.lightness),
                    a
                )
            }
        }
    }
}
impl fmt::Display for Hsla {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fn p(n: f32) -> f32 {
            clamp_normal(n) * 100.0
        }
        let a = p(self.alpha);
        let h = AngleDegree(self.hue).modulo().0.round();
        if (a - 100.0).abs() <= EPSILON {
            write!(f, "hsl({h}º, {}%, {}%)", p(self.saturation), p(self.lightness))
        } else {
            write!(f, "hsla({h}º, {}%, {}%, {}%)", p(self.saturation), p(self.lightness), a)
        }
    }
}
impl Transitionable for Hsla {
    fn lerp(self, to: &Self, step: EasingStep) -> Self {
        self.lerp(*to, step)
    }
}

/// HSV + alpha
///
/// # Equality
///
/// Equality is determined using [`about_eq`] with `0.001` epsilon for [`hue`](Hsva::hue)
/// and `0.00001` epsilon for the others.
///
/// [`about_eq`]: zng_layout::unit::about_eq
#[derive(Copy, Clone, serde::Serialize, serde::Deserialize)]
pub struct Hsva {
    /// Hue color angle in the `[0.0..=360.0]` range.
    pub hue: f32,
    /// Saturation amount in the `[0.0..=1.0]` range, zero is gray, one is full color.
    pub saturation: f32,
    /// Brightness amount in the `[0.0..=1.0]` range, zero is black, one is white.
    pub value: f32,
    /// Alpha channel in the `[0.0..=1.0]` range, zero is invisible, one is opaque.
    pub alpha: f32,
}
impl PartialEq for Hsva {
    fn eq(&self, other: &Self) -> bool {
        about_eq(self.hue, other.hue, EPSILON_100)
            && about_eq(self.saturation, other.saturation, EPSILON)
            && about_eq(self.value, other.value, EPSILON)
            && about_eq(self.alpha, other.alpha, EPSILON)
    }
}
impl std::hash::Hash for Hsva {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        about_eq_hash(self.hue, EPSILON_100, state);
        about_eq_hash(self.saturation, EPSILON, state);
        about_eq_hash(self.value, EPSILON, state);
        about_eq_hash(self.alpha, EPSILON, state);
    }
}
impl Hsva {
    /// Sets the [`hue`](Self::hue) color angle.
    ///
    /// The value is normalized to be in the `[0.0..=360.0]` range, that is `362.deg()` becomes `2.0`.
    pub fn set_hue<H: Into<AngleDegree>>(&mut self, hue: H) {
        self.hue = hue.into().modulo().0
    }

    /// Sets the [`value`](Self::value).
    pub fn set_value<L: Into<Factor>>(&mut self, value: L) {
        self.value = value.into().0;
    }

    /// Sets the [`saturation`](Self::saturation) value.
    pub fn set_saturation<L: Into<Factor>>(&mut self, saturation: L) {
        self.saturation = saturation.into().0;
    }

    /// Sets the [`alpha`](Self::alpha) value.
    pub fn set_alpha<A: Into<Factor>>(&mut self, alpha: A) {
        self.alpha = alpha.into().0
    }

    /// Returns a copy of this color with a new `hue`.
    pub fn with_hue<H: Into<AngleDegree>>(mut self, hue: H) -> Self {
        self.set_hue(hue);
        self
    }

    /// Returns a copy of this color with a new `value`.
    pub fn with_value<V: Into<Factor>>(mut self, value: V) -> Self {
        self.set_value(value);
        self
    }

    /// Returns a copy of this color with a new `saturation`.
    pub fn with_saturation<S: Into<Factor>>(mut self, saturation: S) -> Self {
        self.set_saturation(saturation);
        self
    }

    /// Returns a copy of this color with a new `alpha`.
    pub fn with_alpha<A: Into<Factor>>(mut self, alpha: A) -> Self {
        self.set_alpha(alpha);
        self
    }
}
impl fmt::Debug for Hsva {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if f.alternate() {
            f.debug_struct("Hsla")
                .field("hue", &self.hue)
                .field("saturation", &self.saturation)
                .field("value", &self.value)
                .field("alpha", &self.alpha)
                .finish()
        } else {
            fn p(n: f32) -> f32 {
                clamp_normal(n) * 100.0
            }
            let a = p(self.alpha);
            let h = AngleDegree(self.hue).modulo().0.round();
            if (a - 100.0).abs() <= EPSILON {
                write!(f, "hsv({h}.deg(), {}.pct(), {}.pct())", p(self.saturation), p(self.value))
            } else {
                write!(
                    f,
                    "hsva({h}.deg(), {}.pct(), {}.pct(), {}.pct())",
                    p(self.saturation),
                    p(self.value),
                    a
                )
            }
        }
    }
}
impl fmt::Display for Hsva {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fn p(n: f32) -> f32 {
            clamp_normal(n) * 100.0
        }
        let a = p(self.alpha);
        let h = AngleDegree(self.hue).modulo().0.round();
        if (a - 100.0).abs() <= EPSILON {
            write!(f, "hsv({h}º, {}%, {}%)", p(self.saturation), p(self.value))
        } else {
            write!(f, "hsva({h}º, {}%, {}%, {}%)", p(self.saturation), p(self.value), a)
        }
    }
}
impl_from_and_into_var! {
    fn from(hsla: Hsla) -> Hsva {
        let lightness = clamp_normal(hsla.lightness);
        let saturation = clamp_normal(hsla.saturation);

        let value = lightness + saturation * lightness.min(1.0 - lightness);
        let saturation = if value <= EPSILON {
            0.0
        } else {
            2.0 * (1.0 - lightness / value)
        };

        Hsva {
            hue: hsla.hue,
            saturation,
            value,
            alpha: hsla.alpha,
        }
    }

    fn from(hsva: Hsva) -> Hsla {
        let saturation = clamp_normal(hsva.saturation);
        let value = clamp_normal(hsva.value);

        let lightness = value * (1.0 - saturation / 2.0);
        let saturation = if lightness <= EPSILON || lightness >= 1.0 - EPSILON {
            0.0
        } else {
            2.0 * (1.0 * lightness / value)
        };

        Hsla {
            hue: hsva.hue,
            saturation,
            lightness,
            alpha: hsva.alpha,
        }
    }

    fn from(hsva: Hsva) -> Rgba {
        let hue = AngleDegree(hsva.hue).modulo().0;
        let saturation = clamp_normal(hsva.saturation);
        let value = clamp_normal(hsva.value);

        let c = value * saturation;
        let hue = hue / 60.0;
        let x = c * (1.0 - (hue.rem_euclid(2.0) - 1.0).abs());

        let (red, green, blue) = if hue <= 1.0 {
            (c, x, 0.0)
        } else if hue <= 2.0 {
            (x, c, 0.0)
        } else if hue <= 3.0 {
            (0.0, c, x)
        } else if hue <= 4.0 {
            (0.0, x, c)
        } else if hue <= 5.0 {
            (x, 0.0, c)
        } else if hue <= 6.0 {
            (c, 0.0, x)
        } else {
            (0.0, 0.0, 0.0)
        };

        let m = value - c;

        let f = |n: f32| ((n + m) * 255.0).round() / 255.0;

        Rgba {
            red: f(red),
            green: f(green),
            blue: f(blue),
            alpha: hsva.alpha,
        }
    }

    fn from(hsla: Hsla) -> Rgba {
        if hsla.saturation <= EPSILON {
            return rgba(hsla.lightness, hsla.lightness, hsla.lightness, hsla.alpha);
        }

        let hue = AngleDegree(hsla.hue).modulo().0;
        let saturation = clamp_normal(hsla.saturation);
        let lightness = clamp_normal(hsla.lightness);

        let c = (1.0 - (2.0 * lightness - 1.0).abs()) * saturation;
        let hp = hue / 60.0;
        let x = c * (1.0 - ((hp % 2.0) - 1.0).abs());
        let (red, green, blue) = if hp <= 1.0 {
            (c, x, 0.0)
        } else if hp <= 2.0 {
            (x, c, 0.0)
        } else if hp <= 3.0 {
            (0.0, c, x)
        } else if hp <= 4.0 {
            (0.0, x, c)
        } else if hp <= 5.0 {
            (x, 0.0, c)
        } else if hp <= 6.0 {
            (c, 0.0, x)
        } else {
            (0.0, 0.0, 0.0)
        };
        let m = lightness - c * 0.5;

        let f = |i: f32| ((i + m) * 255.0).round() / 255.0;

        Rgba {
            red: f(red),
            green: f(green),
            blue: f(blue),
            alpha: hsla.alpha,
        }
    }
}
impl Transitionable for Hsva {
    fn lerp(self, to: &Self, step: EasingStep) -> Self {
        match lerp_space() {
            LerpSpace::HslaChromatic => Hsla::from(self).slerp_chromatic((*to).into(), step).into(),
            LerpSpace::Rgba => lerp_rgba_linear(self.into(), (*to).into(), step).into(),
            LerpSpace::Hsla => Hsla::from(self).slerp((*to).into(), step).into(),
            LerpSpace::HslaLinear => Hsla::from(self).lerp_hsla((*to).into(), step).into(),
        }
    }
}

macro_rules! cylindrical_color {
    ($rgba:ident -> ($min:ident, $max:ident, $delta:ident, $hue:ident)) => {
        fn sanitize(i: f32) -> f32 {
            clamp_normal((i * 255.0).round() / 255.0)
        }

        let r = sanitize($rgba.red);
        let g = sanitize($rgba.green);
        let b = sanitize($rgba.blue);

        let $min = r.min(g).min(b);
        let $max = r.max(g).max(b);

        fn about_eq(a: f32, b: f32) -> bool {
            (a - b) <= EPSILON
        }

        let $delta = $max - $min;

        let $hue = if $delta <= EPSILON {
            0.0
        } else {
            60.0 * if about_eq($max, r) {
                ((g - b) / $delta).rem_euclid(6.0)
            } else if about_eq($max, g) {
                (b - r) / $delta + 2.0
            } else {
                debug_assert!(about_eq($max, b));
                (r - g) / $delta + 4.0
            }
        };
    };
}

impl_from_and_into_var! {
    fn from(rgba: Rgba) -> Hsva {
        cylindrical_color!(rgba -> (min, max, delta, hue));

        let saturation = if max <= EPSILON { 0.0 } else { delta / max };

        let value = max;

        Hsva {
            hue,
            saturation,
            value,
            alpha: rgba.alpha,
        }
    }

    fn from(rgba: Rgba) -> Hsla {
        cylindrical_color!(rgba -> (min, max, delta, hue));

        let lightness = (max + min) / 2.0;

        let saturation = if delta <= EPSILON {
            0.0
        } else {
            delta / (1.0 - (2.0 * lightness - 1.0).abs())
        };

        Hsla {
            hue,
            lightness,
            saturation,
            alpha: rgba.alpha,
        }
    }
}

// Util
fn clamp_normal(i: f32) -> f32 {
    i.clamp(0.0, 1.0)
}

/// RGB color, opaque, alpha is set to `1.0`.
///
/// # Arguments
///
/// The arguments can either be [`f32`] in the `0.0..=1.0` range or
/// [`u8`] in the `0..=255` range or a [percentage](zng_layout::unit::FactorPercent).
///
/// # Examples
///
/// ```
/// use zng_color::rgb;
///
/// let red = rgb(1.0, 0.0, 0.0);
/// let green = rgb(0, 255, 0);
/// ```
pub fn rgb<C: Into<RgbaComponent>>(red: C, green: C, blue: C) -> Rgba {
    rgba(red, green, blue, 1.0)
}

/// RGBA color.
///
/// # Arguments
///
/// The arguments can either be `f32` in the `0.0..=1.0` range or
/// `u8` in the `0..=255` range or a [percentage](zng_layout::unit::FactorPercent).
///
/// The rgb arguments must be of the same type, the alpha argument can be of a different type.
///
/// # Examples
///
/// ```
/// use zng_color::rgba;
///
/// let half_red = rgba(255, 0, 0, 0.5);
/// let green = rgba(0.0, 1.0, 0.0, 1.0);
/// let transparent = rgba(0, 0, 0, 0);
/// ```
pub fn rgba<C: Into<RgbaComponent>, A: Into<RgbaComponent>>(red: C, green: C, blue: C, alpha: A) -> Rgba {
    Rgba {
        red: red.into().0,
        green: green.into().0,
        blue: blue.into().0,
        alpha: alpha.into().0,
    }
}

/// HSL color, opaque, alpha is set to `1.0`.
///
/// # Arguments
///
/// The first argument `hue` can be any [angle unit]. The other two arguments can be [`f32`] in the `0.0..=1.0`
/// range or a [percentage](zng_layout::unit::FactorPercent).
///
/// The `saturation` and `lightness` arguments must be of the same type.
///
/// # Examples
///
/// ```
/// use zng_color::hsl;
/// use zng_layout::unit::*;
///
/// let red = hsl(0.deg(), 100.pct(), 50.pct());
/// let green = hsl(115.deg(), 1.0, 0.5);
/// ```
///
/// [angle unit]: trait@zng_layout::unit::AngleUnits
pub fn hsl<H: Into<AngleDegree>, N: Into<Factor>>(hue: H, saturation: N, lightness: N) -> Hsla {
    hsla(hue, saturation, lightness, 1.0)
}

/// HSLA color.
///
/// # Arguments
///
/// The first argument `hue` can be any [angle unit]. The other two arguments can be [`f32`] in the `0.0..=1.0`
/// range or a [percentage](zng_layout::unit::FactorPercent).
///
/// The `saturation` and `lightness` arguments must be of the same type.
///
/// # Examples
///
/// ```
/// use zng_color::hsla;
/// use zng_layout::unit::*;
///
/// let red = hsla(0.deg(), 100.pct(), 50.pct(), 1.0);
/// let green = hsla(115.deg(), 1.0, 0.5, 100.pct());
/// let transparent = hsla(0.deg(), 1.0, 0.5, 0.0);
/// ```
///
/// [angle unit]: trait@zng_layout::unit::AngleUnits
pub fn hsla<H: Into<AngleDegree>, N: Into<Factor>, A: Into<Factor>>(hue: H, saturation: N, lightness: N, alpha: A) -> Hsla {
    Hsla {
        hue: hue.into().0,
        saturation: saturation.into().0,
        lightness: lightness.into().0,
        alpha: alpha.into().0,
    }
}

/// HSV color, opaque, alpha is set to `1.0`.
///
/// # Arguments
///
/// The first argument `hue` can be any [angle unit]. The other two arguments can be [`f32`] in the `0.0..=1.0`
/// range or a [percentage](zng_layout::unit::FactorPercent).
///
/// The `saturation` and `value` arguments must be of the same type.
///
/// # Examples
///
/// ```
/// use zng_color::hsv;
/// use zng_layout::unit::*;
///
/// let red = hsv(0.deg(), 100.pct(), 50.pct());
/// let green = hsv(115.deg(), 1.0, 0.5);
/// ```
///
/// [angle unit]: trait@zng_layout::unit::AngleUnits
pub fn hsv<H: Into<AngleDegree>, N: Into<Factor>>(hue: H, saturation: N, value: N) -> Hsva {
    hsva(hue, saturation, value, 1.0)
}

/// HSVA color.
///
/// # Arguments
///
/// The first argument `hue` can be any [angle unit]. The other two arguments can be [`f32`] in the `0.0..=1.0`
/// range or a [percentage](zng_layout::unit::FactorPercent).
///
/// The `saturation` and `value` arguments must be of the same type.
///
/// # Examples
///
/// ```
/// use zng_color::hsva;
/// use zng_layout::unit::*;
///
/// let red = hsva(0.deg(), 100.pct(), 50.pct(), 1.0);
/// let green = hsva(115.deg(), 1.0, 0.5, 100.pct());
/// let transparent = hsva(0.deg(), 1.0, 0.5, 0.0);
/// ```
///
/// [angle unit]: trait@zng_layout::unit::AngleUnits
pub fn hsva<H: Into<AngleDegree>, N: Into<Factor>, A: Into<Factor>>(hue: H, saturation: N, value: N, alpha: A) -> Hsva {
    Hsva {
        hue: hue.into().0,
        saturation: saturation.into().0,
        value: value.into().0,
        alpha: alpha.into().0,
    }
}

context_var! {
    /// Defines the preferred color scheme in a context.
    pub static COLOR_SCHEME_VAR: ColorScheme = ColorScheme::default();
}

/// Create a variable that maps to `dark` or `light` depending on the contextual [`COLOR_SCHEME_VAR`].
pub fn color_scheme_map<T: VarValue>(dark: impl IntoVar<T>, light: impl IntoVar<T>) -> impl Var<T> {
    merge_var!(COLOR_SCHEME_VAR, dark.into_var(), light.into_var(), |&scheme, dark, light| {
        match scheme {
            ColorScheme::Dark => dark.clone(),
            ColorScheme::Light => light.clone(),
        }
    })
}

/// Create a variable that selects the [`ColorPair`] depending on the contextual [`COLOR_SCHEME_VAR`].
pub fn color_scheme_pair(pair: impl IntoVar<ColorPair>) -> impl Var<Rgba> {
    merge_var!(COLOR_SCHEME_VAR, pair.into_var(), |&scheme, &pair| {
        match scheme {
            ColorScheme::Dark => pair.dark,
            ColorScheme::Light => pair.light,
        }
    })
}

/// Create a variable that selects the [`ColorPair`] highlight depending on the contextual [`COLOR_SCHEME_VAR`].
pub fn color_scheme_highlight(pair: impl IntoVar<ColorPair>, highlight: impl IntoVar<Factor>) -> impl Var<Rgba> {
    merge_var!(
        COLOR_SCHEME_VAR,
        pair.into_var(),
        highlight.into_var(),
        |&scheme, &pair, &highlight| {
            match scheme {
                ColorScheme::Dark => pair.highlight_dark(highlight),
                ColorScheme::Light => pair.highlight_light(highlight),
            }
        }
    )
}

/// Represents a dark and light *color*.
#[derive(Debug, Clone, Copy, PartialEq, Hash, serde::Serialize, serde::Deserialize, Transitionable)]
pub struct ColorPair {
    /// Color used when [`ColorScheme::Dark`].
    pub dark: Rgba,
    /// Color used when [`ColorScheme::Light`].
    pub light: Rgba,
}
impl_from_and_into_var! {
    /// From `(dark, light)` tuple.
    fn from<D: Into<Rgba>, L: Into<Rgba>>((dark, light): (D, L)) -> ColorPair {
        ColorPair {
            dark: dark.into(),
            light: light.into(),
        }
    }

    /// From same color to both.
    fn from(color: Rgba) -> ColorPair {
        ColorPair { dark: color, light: color }
    }

    /// From same color to both.
    fn from(color: Hsva) -> ColorPair {
        Rgba::from(color).into()
    }

    /// From same color to both.
    fn from(color: Hsla) -> ColorPair {
        Rgba::from(color).into()
    }
}
impl ColorPair {
    /// Overlay white with `highlight` amount as alpha over the [`dark`] color.
    ///
    /// [`dark`]: ColorPair::dark
    pub fn highlight_dark(self, highlight: impl Into<Factor>) -> Rgba {
        colors::WHITE.with_alpha(highlight.into()).mix_normal(self.dark)
    }

    /// Overlay black with `highlight` amount as alpha over the [`light`] color.
    ///
    /// [`light`]: ColorPair::light
    pub fn highlight_light(self, highlight: impl Into<Factor>) -> Rgba {
        colors::BLACK.with_alpha(highlight.into()).mix_normal(self.light)
    }

    /// Gets the color for the scheme.
    pub fn color(self, scheme: ColorScheme) -> Rgba {
        match scheme {
            ColorScheme::Light => self.light,
            ColorScheme::Dark => self.dark,
        }
    }
}

/// Defines the color space for color interpolation.
///
/// See [`with_lerp_space`] for more details.
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum LerpSpace {
    /// Linear interpolation in each RGBA component.
    Rgba,
    /// Spherical linear interpolation in Hue (shorter path), linear interpolation in SLA.
    Hsla,
    /// Linear interpolate SLA, spherical linear interpolation in Hue (short) if both colors are chromatic (S>0) or
    /// jumps to the chromatic hue from the start.
    #[default]
    HslaChromatic,
    /// Linear interpolation in each HSLA component.
    HslaLinear,
}

/// Gets the lerp space used for color interpolation.
///
/// Must be called only inside the [`with_lerp_space`] closure or in the lerp implementation of a variable animating
/// with [`rgba_sampler`] or [`hsla_linear_sampler`].
pub fn lerp_space() -> LerpSpace {
    LERP_SPACE.get_clone()
}

/// Calls `f` with [`lerp_space`] set to `space`.
///
/// See [`rgba_sampler`] and [`hsla_linear_sampler`] for a way to set the space in animations.
pub fn with_lerp_space<R>(space: LerpSpace, f: impl FnOnce() -> R) -> R {
    LERP_SPACE.with_context(&mut Some(Arc::new(space)), f)
}

/// Animation sampler that sets the [`lerp_space`] to [`LerpSpace::Rgba`].
///
/// Samplers can be set in animations using the [`Var::easing_with`] method.
///
/// [`Var::easing_with`]: zng_var::Var::easing_with
pub fn rgba_sampler<T: Transitionable>(t: &Transition<T>, step: EasingStep) -> T {
    with_lerp_space(LerpSpace::Rgba, || t.sample(step))
}

/// Animation sampler that sets the [`lerp_space`] to [`LerpSpace::Hsla`].
///
/// Note that this is already the default.
pub fn hsla_sampler<T: Transitionable>(t: &Transition<T>, step: EasingStep) -> T {
    with_lerp_space(LerpSpace::Hsla, || t.sample(step))
}

/// Animation sampler that sets the [`lerp_space`] to [`LerpSpace::HslaLinear`].
///
/// Samplers can be set in animations using the [`Var::easing_with`] method.
///
/// [`Var::easing_with`]: zng_var::Var::easing_with
pub fn hsla_linear_sampler<T: Transitionable>(t: &Transition<T>, step: EasingStep) -> T {
    with_lerp_space(LerpSpace::HslaLinear, || t.sample(step))
}

context_local! {
    static LERP_SPACE: LerpSpace = LerpSpace::default();
}

#[cfg(test)]
mod tests {
    use super::*;
    use zng_layout::unit::{AngleUnits as _, FactorUnits as _};

    #[test]
    fn hsl_red() {
        assert_eq!(Rgba::from(hsl(0.0.deg(), 100.pct(), 50.pct())), rgb(1.0, 0.0, 0.0))
    }

    #[test]
    fn hsl_color() {
        assert_eq!(Rgba::from(hsl(91.0.deg(), 1.0, 0.5)), rgb(123, 255, 0))
    }

    #[test]
    fn rgb_to_hsl() {
        let color = rgba(0, 100, 200, 0.2);
        let a = format!("{color:?}");
        let b = format!("{:?}", Rgba::from(Hsla::from(color)));
        assert_eq!(a, b)
    }

    #[test]
    fn rgb_to_hsv() {
        let color = rgba(0, 100, 200, 0.2);
        let a = format!("{color:?}");
        let b = format!("{:?}", Rgba::from(Hsva::from(color)));
        assert_eq!(a, b)
    }

    #[test]
    fn rgba_display() {
        macro_rules! test {
            ($($tt:tt)+) => {
                let expected = stringify!($($tt)+).replace(" ", "");
                let actual = hex!($($tt)+).to_string();
                assert_eq!(expected, actual);
            }
        }

        test!(#AABBCC);
        test!(#123456);
        test!(#000000);
        test!(#FFFFFF);

        test!(#AABBCCDD);
        test!(#12345678);
        test!(#00000000);
        test!(#FFFFFF00);
    }

    #[test]
    fn test_hex_color() {
        fn f(n: u8) -> f32 {
            n as f32 / 255.0
        }
        assert_eq!(Rgba::new(f(0x11), f(0x22), f(0x33), f(0x44)), hex!(0x11223344));

        assert_eq!(colors::BLACK, hex!(0x00_00_00_FF));
        assert_eq!(colors::WHITE, hex!(0xFF_FF_FF_FF));
        assert_eq!(colors::WHITE, hex!(0xFF_FF_FF));
        assert_eq!(colors::WHITE, hex!(0xFFFFFF));
        assert_eq!(colors::WHITE, hex!(#FFFFFF));
        assert_eq!(colors::WHITE, hex!(FFFFFF));
        assert_eq!(colors::WHITE, hex!(0xFFFF));
        assert_eq!(colors::BLACK, hex!(0x000));
        assert_eq!(colors::BLACK, hex!(#000));
        assert_eq!(colors::BLACK, hex!(000));
    }

    // #[test]
    // fn rgb_to_hsv_all() {
    //     for r in 0..=255 {
    //         println!("{r}");
    //         for g in 0..=255 {
    //             for b in 0..=255 {
    //                 let color = rgb(r, g, b);
    //                 let a = color.to_string();
    //                 let b = color.to_hsva().to_rgba().to_string();
    //                 assert_eq!(a, b)
    //             }
    //         }
    //     }
    // }
}