material-color-utils 0.1.3

Color libraries for Google's Material You
Documentation
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
use crate::dynamic::color_spec::{Platform, SpecVersion};
use crate::dynamic::dynamic_color::DynamicColor;
use crate::dynamic::material_dynamic_colors::MaterialDynamicColors;
use crate::dynamic::variant::Variant;
use crate::hct::hct_color::Hct;
use crate::palettes::tonal_palette::TonalPalette;
use crate::utils::color_utils::Argb;
use crate::utils::math_utils::MathUtils;
use std::sync::OnceLock;

#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};

#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct DynamicScheme {
    pub source_color_hct_list: Vec<Hct>,
    pub variant: Variant,
    pub is_dark: bool,
    pub contrast_level: f64,
    pub platform: Platform,
    pub spec_version: SpecVersion,
    pub primary_palette: TonalPalette,
    pub secondary_palette: TonalPalette,
    pub tertiary_palette: TonalPalette,
    pub neutral_palette: TonalPalette,
    pub neutral_variant_palette: TonalPalette,
    pub error_palette: TonalPalette,

    #[cfg_attr(feature = "serde", serde(skip))]
    pub argb_cache: papaya::HashMap<String, Argb>,

    #[cfg_attr(feature = "serde", serde(skip))]
    pub tone_cache: papaya::HashMap<String, f64>,

    #[cfg_attr(feature = "serde", serde(skip))]
    pub hct_cache: papaya::HashMap<String, Hct>,
}

impl PartialEq for DynamicScheme {
    fn eq(&self, other: &Self) -> bool {
        self.source_color_hct_list == other.source_color_hct_list
            && self.variant == other.variant
            && self.is_dark == other.is_dark
            && self.contrast_level.to_bits() == other.contrast_level.to_bits()
            && self.platform == other.platform
            && self.spec_version == other.spec_version
            && self.primary_palette == other.primary_palette
            && self.secondary_palette == other.secondary_palette
            && self.tertiary_palette == other.tertiary_palette
            && self.neutral_palette == other.neutral_palette
            && self.neutral_variant_palette == other.neutral_variant_palette
            && self.error_palette == other.error_palette
    }
}

impl Eq for DynamicScheme {}

impl std::hash::Hash for DynamicScheme {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.source_color_hct_list.hash(state);
        self.variant.hash(state);
        self.is_dark.hash(state);
        self.contrast_level.to_bits().hash(state);
        self.platform.hash(state);
        self.spec_version.hash(state);
    }
}

impl DynamicScheme {
    #[must_use]
    pub fn new(
        source_color_hct: Hct,
        variant: Variant,
        is_dark: bool,
        contrast_level: f64,
        primary_palette: TonalPalette,
        secondary_palette: TonalPalette,
        tertiary_palette: TonalPalette,
        neutral_palette: TonalPalette,
        neutral_variant_palette: TonalPalette,
        error_palette: TonalPalette,
    ) -> Self {
        Self::new_with_platform_and_spec(
            source_color_hct,
            variant,
            is_dark,
            contrast_level,
            Platform::Phone,
            SpecVersion::Spec2021,
            primary_palette,
            secondary_palette,
            tertiary_palette,
            neutral_palette,
            neutral_variant_palette,
            error_palette,
        )
    }

    #[must_use]
    pub fn new_with_platform_and_spec(
        source_color_hct: Hct,
        variant: Variant,
        is_dark: bool,
        contrast_level: f64,
        platform: Platform,
        spec_version: SpecVersion,
        primary_palette: TonalPalette,
        secondary_palette: TonalPalette,
        tertiary_palette: TonalPalette,
        neutral_palette: TonalPalette,
        neutral_variant_palette: TonalPalette,
        error_palette: TonalPalette,
    ) -> Self {
        Self {
            source_color_hct_list: vec![source_color_hct],
            variant,
            is_dark,
            contrast_level,
            platform,
            spec_version: Self::maybe_fallback_spec_version(spec_version, variant),
            primary_palette,
            secondary_palette,
            tertiary_palette,
            neutral_palette,
            neutral_variant_palette,
            error_palette,
            argb_cache: papaya::HashMap::new(),
            tone_cache: papaya::HashMap::new(),
            hct_cache: papaya::HashMap::new(),
        }
    }

    #[must_use]
    pub fn from_scheme(other: &Self, is_dark: bool) -> Self {
        Self::from_scheme_with_contrast(other, is_dark, other.contrast_level)
    }

    #[must_use]
    pub fn from_scheme_with_contrast(other: &Self, is_dark: bool, contrast_level: f64) -> Self {
        Self {
            source_color_hct_list: other.source_color_hct_list.clone(),
            variant: other.variant,
            is_dark,
            contrast_level,
            platform: other.platform,
            spec_version: other.spec_version,
            primary_palette: other.primary_palette.clone(),
            secondary_palette: other.secondary_palette.clone(),
            tertiary_palette: other.tertiary_palette.clone(),
            neutral_palette: other.neutral_palette.clone(),
            neutral_variant_palette: other.neutral_variant_palette.clone(),
            error_palette: other.error_palette.clone(),
            argb_cache: papaya::HashMap::new(),
            tone_cache: papaya::HashMap::new(),
            hct_cache: papaya::HashMap::new(),
        }
    }

    /// Returns the primary source color in HCT.
    #[must_use]
    pub fn source_color_hct(&self) -> &Hct {
        &self.source_color_hct_list[0]
    }

    #[must_use]
    pub fn source_color_argb(&self) -> Argb {
        self.source_color_hct().to_argb()
    }

    #[must_use]
    pub fn get_hct(&self, dynamic_color: &DynamicColor) -> Hct {
        let pin = self.hct_cache.pin();
        if let Some(&hct) = pin.get(&dynamic_color.name) {
            return hct;
        }
        let hct = crate::dynamic::color_specs::ColorSpecs::get(self.spec_version)
            .call()
            .get_hct(self, dynamic_color);
        pin.insert(dynamic_color.name.clone(), hct);
        hct
    }

    #[must_use]
    pub fn get_argb(&self, dynamic_color: &DynamicColor) -> Argb {
        let pin = self.argb_cache.pin();
        if let Some(&argb) = pin.get(&dynamic_color.name) {
            return argb;
        }
        // Entry point for Argb resolution
        let hct = self.get_hct(dynamic_color);
        let mut argb = hct.to_argb();

        if let Some(ref opacity_func) = dynamic_color.opacity
            && let Some(opacity_percentage) = opacity_func(self)
        {
            let alpha = (opacity_percentage * 255.0).round() as u32;
            let alpha = alpha.clamp(0, 255);
            argb = Argb((argb.0 & 0x00ffffff) | (alpha << 24));
        }

        pin.insert(dynamic_color.name.clone(), argb);
        argb
    }

    #[must_use]
    pub fn get_tone(&self, dynamic_color: &DynamicColor) -> f64 {
        let pin = self.tone_cache.pin();
        if let Some(&tone) = pin.get(&dynamic_color.name) {
            return tone;
        }
        let tone = crate::dynamic::color_specs::ColorSpecs::get(self.spec_version)
            .call()
            .get_tone(self, dynamic_color);
        pin.insert(dynamic_color.name.clone(), tone);
        tone
    }

    #[must_use]
    pub fn get_piecewise_value(
        source_color_hct: &Hct,
        hue_breakpoints: &[f64],
        hues: &[f64],
    ) -> f64 {
        let size = (hue_breakpoints.len().saturating_sub(1)).min(hues.len());
        let source_hue = source_color_hct.hue();

        for i in 0..size {
            if source_hue >= hue_breakpoints[i] && source_hue < hue_breakpoints[i + 1] {
                return MathUtils::sanitize_degrees_double(hues[i]);
            }
        }

        // No condition matched, return the source value.
        source_hue
    }

    /// Given a hue and set of hue thresholds / rotations, returns the rotated hue.
    #[must_use]
    pub fn get_rotated_hue(
        source_color_hct: &Hct,
        hue_breakpoints: &[f64],
        rotations: &[f64],
    ) -> f64 {
        let mut rotation = Self::get_piecewise_value(source_color_hct, hue_breakpoints, rotations);
        let size = (hue_breakpoints.len().saturating_sub(1)).min(rotations.len());
        if size == 0 {
            rotation = 0.0;
        }
        MathUtils::sanitize_degrees_double(source_color_hct.hue() + rotation)
    }

    fn maybe_fallback_spec_version(spec_version: SpecVersion, variant: Variant) -> SpecVersion {
        if variant == Variant::Cmf {
            return spec_version;
        }
        if variant == Variant::Expressive
            || variant == Variant::Vibrant
            || variant == Variant::TonalSpot
            || variant == Variant::Neutral
        {
            if spec_version == SpecVersion::Spec2026 {
                return SpecVersion::Spec2025;
            }
            return spec_version;
        }
        SpecVersion::Spec2021
    }

    #[must_use]
    pub fn primary_palette_key_color(&self) -> Argb {
        self.get_argb(&dynamic_colors().primary_palette_key_color())
    }

    #[must_use]
    pub fn secondary_palette_key_color(&self) -> Argb {
        self.get_argb(&dynamic_colors().secondary_palette_key_color())
    }

    #[must_use]
    pub fn tertiary_palette_key_color(&self) -> Argb {
        self.get_argb(&dynamic_colors().tertiary_palette_key_color())
    }

    #[must_use]
    pub fn neutral_palette_key_color(&self) -> Argb {
        self.get_argb(&dynamic_colors().neutral_palette_key_color())
    }

    #[must_use]
    pub fn neutral_variant_palette_key_color(&self) -> Argb {
        self.get_argb(&dynamic_colors().neutral_variant_palette_key_color())
    }

    #[must_use]
    pub fn background(&self) -> Argb {
        self.get_argb(&dynamic_colors().background())
    }

    #[must_use]
    pub fn on_background(&self) -> Argb {
        self.get_argb(&dynamic_colors().on_background())
    }

    #[must_use]
    pub fn surface(&self) -> Argb {
        self.get_argb(&dynamic_colors().surface())
    }

    #[must_use]
    pub fn surface_dim(&self) -> Argb {
        self.get_argb(&dynamic_colors().surface_dim())
    }

    #[must_use]
    pub fn surface_bright(&self) -> Argb {
        self.get_argb(&dynamic_colors().surface_bright())
    }

    #[must_use]
    pub fn surface_container_lowest(&self) -> Argb {
        self.get_argb(&dynamic_colors().surface_container_lowest())
    }

    #[must_use]
    pub fn surface_container_low(&self) -> Argb {
        self.get_argb(&dynamic_colors().surface_container_low())
    }

    #[must_use]
    pub fn surface_container(&self) -> Argb {
        self.get_argb(&dynamic_colors().surface_container())
    }

    #[must_use]
    pub fn surface_container_high(&self) -> Argb {
        self.get_argb(&dynamic_colors().surface_container_high())
    }

    #[must_use]
    pub fn surface_container_highest(&self) -> Argb {
        self.get_argb(&dynamic_colors().surface_container_highest())
    }

    #[must_use]
    pub fn on_surface(&self) -> Argb {
        self.get_argb(&dynamic_colors().on_surface())
    }

    #[must_use]
    pub fn surface_variant(&self) -> Argb {
        self.get_argb(&dynamic_colors().surface_variant())
    }

    #[must_use]
    pub fn on_surface_variant(&self) -> Argb {
        self.get_argb(&dynamic_colors().on_surface_variant())
    }

    #[must_use]
    pub fn inverse_surface(&self) -> Argb {
        self.get_argb(&dynamic_colors().inverse_surface())
    }

    #[must_use]
    pub fn inverse_on_surface(&self) -> Argb {
        self.get_argb(&dynamic_colors().inverse_on_surface())
    }

    #[must_use]
    pub fn outline(&self) -> Argb {
        self.get_argb(&dynamic_colors().outline())
    }

    #[must_use]
    pub fn outline_variant(&self) -> Argb {
        self.get_argb(&dynamic_colors().outline_variant())
    }

    #[must_use]
    pub fn shadow(&self) -> Argb {
        self.get_argb(&dynamic_colors().shadow())
    }

    #[must_use]
    pub fn scrim(&self) -> Argb {
        self.get_argb(&dynamic_colors().scrim())
    }

    #[must_use]
    pub fn surface_tint(&self) -> Argb {
        self.get_argb(&dynamic_colors().surface_tint())
    }

    #[must_use]
    pub fn primary(&self) -> Argb {
        self.get_argb(&dynamic_colors().primary())
    }

    #[must_use]
    pub fn on_primary(&self) -> Argb {
        self.get_argb(&dynamic_colors().on_primary())
    }

    #[must_use]
    pub fn primary_container(&self) -> Argb {
        self.get_argb(&dynamic_colors().primary_container())
    }

    #[must_use]
    pub fn on_primary_container(&self) -> Argb {
        self.get_argb(&dynamic_colors().on_primary_container())
    }

    #[must_use]
    pub fn inverse_primary(&self) -> Argb {
        self.get_argb(&dynamic_colors().inverse_primary())
    }

    #[must_use]
    pub fn secondary(&self) -> Argb {
        self.get_argb(&dynamic_colors().secondary())
    }

    #[must_use]
    pub fn on_secondary(&self) -> Argb {
        self.get_argb(&dynamic_colors().on_secondary())
    }

    #[must_use]
    pub fn secondary_container(&self) -> Argb {
        self.get_argb(&dynamic_colors().secondary_container())
    }

    #[must_use]
    pub fn on_secondary_container(&self) -> Argb {
        self.get_argb(&dynamic_colors().on_secondary_container())
    }

    #[must_use]
    pub fn tertiary(&self) -> Argb {
        self.get_argb(&dynamic_colors().tertiary())
    }

    #[must_use]
    pub fn on_tertiary(&self) -> Argb {
        self.get_argb(&dynamic_colors().on_tertiary())
    }

    #[must_use]
    pub fn tertiary_container(&self) -> Argb {
        self.get_argb(&dynamic_colors().tertiary_container())
    }

    #[must_use]
    pub fn on_tertiary_container(&self) -> Argb {
        self.get_argb(&dynamic_colors().on_tertiary_container())
    }

    #[must_use]
    pub fn error(&self) -> Argb {
        self.get_argb(&dynamic_colors().error())
    }

    #[must_use]
    pub fn on_error(&self) -> Argb {
        self.get_argb(&dynamic_colors().on_error())
    }

    #[must_use]
    pub fn error_container(&self) -> Argb {
        self.get_argb(&dynamic_colors().error_container())
    }

    #[must_use]
    pub fn on_error_container(&self) -> Argb {
        self.get_argb(&dynamic_colors().on_error_container())
    }

    #[must_use]
    pub fn primary_fixed(&self) -> Argb {
        self.get_argb(&dynamic_colors().primary_fixed())
    }

    #[must_use]
    pub fn primary_fixed_dim(&self) -> Argb {
        self.get_argb(&dynamic_colors().primary_fixed_dim())
    }

    #[must_use]
    pub fn on_primary_fixed(&self) -> Argb {
        self.get_argb(&dynamic_colors().on_primary_fixed())
    }

    #[must_use]
    pub fn on_primary_fixed_variant(&self) -> Argb {
        self.get_argb(&dynamic_colors().on_primary_fixed_variant())
    }

    #[must_use]
    pub fn secondary_fixed(&self) -> Argb {
        self.get_argb(&dynamic_colors().secondary_fixed())
    }

    #[must_use]
    pub fn secondary_fixed_dim(&self) -> Argb {
        self.get_argb(&dynamic_colors().secondary_fixed_dim())
    }

    #[must_use]
    pub fn on_secondary_fixed(&self) -> Argb {
        self.get_argb(&dynamic_colors().on_secondary_fixed())
    }

    #[must_use]
    pub fn on_secondary_fixed_variant(&self) -> Argb {
        self.get_argb(&dynamic_colors().on_secondary_fixed_variant())
    }

    #[must_use]
    pub fn tertiary_fixed(&self) -> Argb {
        self.get_argb(&dynamic_colors().tertiary_fixed())
    }

    #[must_use]
    pub fn tertiary_fixed_dim(&self) -> Argb {
        self.get_argb(&dynamic_colors().tertiary_fixed_dim())
    }

    #[must_use]
    pub fn on_tertiary_fixed(&self) -> Argb {
        self.get_argb(&dynamic_colors().on_tertiary_fixed())
    }

    #[must_use]
    pub fn on_tertiary_fixed_variant(&self) -> Argb {
        self.get_argb(&dynamic_colors().on_tertiary_fixed_variant())
    }
}

fn dynamic_colors() -> &'static MaterialDynamicColors {
    static DYNAMIC_COLORS: OnceLock<MaterialDynamicColors> = OnceLock::new();
    DYNAMIC_COLORS.get_or_init(MaterialDynamicColors::new)
}

#[cfg(test)]
mod tests {
    #![allow(clippy::float_cmp)]
    use super::*;
    use crate::utils::color_utils::Argb;

    #[test]
    fn test_get_piecewise_value() {
        let hct = Hct::from_argb(Argb(0xff0000ff)); // Blue, hue ~265
        let hue_breakpoints = [0.0, 100.0, 200.0, 300.0, 360.0];
        let values = [10.0, 20.0, 30.0, 40.0];

        // Should fall into 200.0..300.0 bucket
        assert_eq!(
            DynamicScheme::get_piecewise_value(&hct, &hue_breakpoints, &values),
            30.0
        );
    }

    #[test]
    fn test_get_rotated_hue() {
        let hct = Hct::from_argb(Argb(0xff0000ff)); // Blue, hue ~265.8
        let hue_breakpoints = [0.0, 100.0, 200.0, 300.0, 360.0];
        let rotations = [10.0, 20.0, -30.0, 40.0];

        // Should fall into 200.0..300.0 bucket, rotation is -30
        let expected_hue = MathUtils::sanitize_degrees_double(hct.hue() - 30.0);

        let rotated = DynamicScheme::get_rotated_hue(&hct, &hue_breakpoints, &rotations);
        assert!((rotated - expected_hue).abs() < 1e-4);
    }
}