Skip to main content

egui_pop_tokens/
palette.rs

1//! Palette ramps generated from one seed colour.
2//!
3//! [`ramp`] turns a seed into the twelve steps of a colour scale, in the
4//! step model of the reference tier (`docs/tokens.md`, after Radix
5//! Colors): 1 and 2 backgrounds, 3 to 5 quiet fills, 6 and 7
6//! borders, 8 a solid fill being pressed, 9 the solid fill, 10 the solid
7//! fill under the pointer, 11 low-contrast text, 12 high-contrast text.
8//! The light and dark ramps of a theme pair come from the same seed
9//! ([`Scheme`]). [`Ramp`] adds the text colour that reads on step 9 (a
10//! scale's `contrast`), and writes the scale as tokens.
11//!
12//! How a ramp is made, in OkHsl ([`Okhsl`], Björn Ottosson's
13//! perceptual hue, saturation and lightness over Oklab, whose saturation
14//! is relative to the sRGB gamut, so no step leaves it):
15//!
16//! - **Lightness** per step is a fixed target for the backgrounds and
17//!   borders (1 to 7) and the high-contrast text (12), taken from the
18//!   built-in `pop-light` and `pop-dark` scales; steps 8, 10 and 11
19//!   follow step 9.
20//! - **Step 9 is the seed** when it reads: APCA ([`crate::apca`]) checks
21//!   the text on it, and its lightness moves away from the text (darker
22//!   in light, lighter in dark) until the text reaches Lc 60 and WCAG
23//!   4.5:1 with margin. egui-pop's accent is also text on panels, so in
24//!   a light scheme step 9 is dark enough for white text, in a dark one
25//!   light enough for dark text.
26//! - **Saturation** is the seed's, scaled per step (quiet backgrounds,
27//!   full solids), then limited per hue band: greens and cyans turn
28//!   neon, and yellows muddy, at full saturation in large areas.
29//! - **Hue** shifts with lightness, as warm and cool colours are seen to
30//!   (lighter warm steps lean to yellow, lighter cool steps to cyan), by
31//!   a few degrees at most.
32//!
33//! [`clamp_seed`] brings a seed into what gives a usable ramp (not
34//! nearly black or white, saturation within its band); [`ramp`] applies
35//! it first. A grey seed gives a neutral ramp.
36//!
37//! The approach follows egui_colors (MIT), which generates 12-step
38//! Radix-like scales in OkHsl with hue shifts, saturation limits per
39//! hue band and APCA; this is a re-derivation with documented targets,
40//! not its code. The OkHsl conversions follow Ottosson's published
41//! reference implementation (MIT).
42//!
43//! ```
44//! use egui_pop_tokens::palette::{self, Scheme};
45//! use egui_pop_tokens::{Color, contrast};
46//!
47//! let seed = Color::from_hex("#3a7bd5").unwrap();
48//! let light = palette::Ramp::new(seed, Scheme::Light);
49//! assert!(contrast::contrast_ratio(light.contrast, light.steps[8]) >= 4.5);
50//! let dark = palette::ramp(seed, Scheme::Dark);
51//! assert!(dark[0].is_dark() && !dark[11].is_dark());
52//! ```
53
54use serde_json::{Value as Json, json};
55
56use crate::Color;
57use crate::apca;
58use crate::color::contrast_ratio;
59
60/// Which kind of theme a ramp is for.
61#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
62pub enum Scheme {
63    /// Light backgrounds, dark text.
64    Light,
65    /// Dark backgrounds, light text.
66    Dark,
67}
68
69impl Scheme {
70    /// The scheme of a theme whose panels are this colour.
71    pub fn of_background(panel: Color) -> Scheme {
72        if panel.is_dark() {
73            Scheme::Dark
74        } else {
75            Scheme::Light
76        }
77    }
78}
79
80/// A colour in OkHsl: hue in degrees (0 to 360), saturation and
81/// lightness from 0 to 1, saturation relative to the most the sRGB gamut
82/// holds at that hue and lightness.
83#[derive(Clone, Copy, Debug, PartialEq)]
84pub struct Okhsl {
85    pub h: f32,
86    pub s: f32,
87    pub l: f32,
88}
89
90impl Okhsl {
91    /// A colour's OkHsl coordinates (alpha ignored).
92    pub fn from_color(c: Color) -> Okhsl {
93        let (h, s, l) = ok::srgb_to_okhsl(c);
94        Okhsl {
95            h: h as f32,
96            s: s as f32,
97            l: l as f32,
98        }
99    }
100
101    /// The opaque sRGB colour.
102    pub fn to_color(self) -> Color {
103        ok::okhsl_to_srgb(
104            f64::from(self.h),
105            f64::from(self.s.clamp(0.0, 1.0)),
106            f64::from(self.l.clamp(0.0, 1.0)),
107        )
108    }
109}
110
111/// The lowest and highest lightness of a usable seed.
112pub const SEED_LIGHTNESS: (f32, f32) = (0.25, 0.92);
113
114/// The Lc the text on step 9 reaches, at least (APCA's floor for
115/// ordinary text).
116pub const SOLID_LC: f32 = 60.0;
117
118/// The WCAG ratio the text on steps 9 and 10, and step 9 on the
119/// scheme's backgrounds, reach at least: AA's 4.5:1 with a margin for
120/// panels that are not the ramp's own backgrounds.
121pub const SOLID_RATIO: f32 = 5.0;
122
123/// Background lightness targets, steps 1 to 7.
124const LIGHT_L: [f32; 7] = [0.985, 0.96, 0.925, 0.89, 0.855, 0.81, 0.73];
125const DARK_L: [f32; 7] = [0.075, 0.1, 0.15, 0.2, 0.25, 0.305, 0.38];
126/// High-contrast text, step 12.
127const LIGHT_TEXT_L: f32 = 0.22;
128const DARK_TEXT_L: f32 = 0.93;
129/// The most step 9 may be, light or dark, so 8, 10 and 11 stay apart.
130const LIGHT_SOLID_MIN_L: f32 = 0.32;
131const DARK_SOLID_MAX_L: f32 = 0.84;
132
133/// The seed's saturation is scaled by these, steps 1 to 12.
134const LIGHT_S: [f32; 12] = [
135    0.45, 0.6, 0.7, 0.75, 0.75, 0.75, 0.8, 0.95, 1.0, 1.0, 0.95, 0.7,
136];
137const DARK_S: [f32; 12] = [
138    0.3, 0.35, 0.5, 0.6, 0.65, 0.65, 0.7, 0.9, 1.0, 1.0, 0.9, 0.5,
139];
140
141/// Degrees of hue shift per unit of lightness away from step 9.
142const HUE_SHIFT: f32 = 16.0;
143
144/// A weight from 0 to 1 that is 1 inside `from..=to` and fades to 0
145/// over `fade` degrees on each side (hues wrap at 360).
146fn band(h: f32, from: f32, to: f32, fade: f32) -> f32 {
147    let inside = |h: f32| {
148        if h >= from && h <= to {
149            1.0
150        } else if h < from {
151            (1.0 - (from - h) / fade).max(0.0)
152        } else {
153            (1.0 - (h - to) / fade).max(0.0)
154        }
155    };
156    inside(h).max(inside(h - 360.0)).max(inside(h + 360.0))
157}
158
159/// The most saturation a step of this hue takes: greens and cyans
160/// (OkHsl hue 125 to 200) and yellows (85 to 115) are limited in large
161/// areas (steps 1 to 7) and less so in solids.
162fn saturation_cap(h: f32, step: usize, scheme: Scheme) -> f32 {
163    let background = step < 7;
164    let green = band(h, 125.0, 200.0, 15.0);
165    let yellow = band(h, 85.0, 115.0, 10.0);
166    let green_cap = if background { 0.55 } else { 0.85 };
167    let yellow_cap = match (background, scheme) {
168        (true, Scheme::Dark) => 0.45,
169        (true, Scheme::Light) => 0.75,
170        (false, _) => 1.0,
171    };
172    let cap = |weight: f32, cap: f32| 1.0 - weight * (1.0 - cap);
173    cap(green, green_cap).min(cap(yellow, yellow_cap))
174}
175
176/// The hue of a step `dl` lighter than step 9: warm hues (red to
177/// yellow, 0 to 100) lean to yellow when lighter, cool ones (blue, 200
178/// to 290) to cyan.
179fn shifted_hue(h: f32, dl: f32) -> f32 {
180    let warm = band(h, 10.0, 90.0, 20.0);
181    let cool = band(h, 210.0, 280.0, 20.0);
182    (h + HUE_SHIFT * dl * (warm - cool)).rem_euclid(360.0)
183}
184
185/// A seed brought into what gives a usable ramp: opaque, its lightness
186/// within [`SEED_LIGHTNESS`] (nearly black or white seeds have no hue to
187/// speak of) and its saturation within its hue band's limit for solids.
188/// A seed already usable comes back unchanged (to the byte).
189pub fn clamp_seed(seed: Color) -> Color {
190    let opaque = Color { a: 1.0, ..seed };
191    let hsl = Okhsl::from_color(opaque);
192    let l = hsl.l.clamp(SEED_LIGHTNESS.0, SEED_LIGHTNESS.1);
193    let s = hsl.s.min(saturation_cap(hsl.h, 8, Scheme::Light));
194    if (l - hsl.l).abs() < 1e-4 && (s - hsl.s).abs() < 1e-4 {
195        return opaque;
196    }
197    Okhsl { h: hsl.h, s, l }.to_color()
198}
199
200/// A colour's counterpart in a theme of the other scheme, light for
201/// dark: the same OkHsl hue and saturation (the chroma, as far as the
202/// sRGB gamut holds it at the new lightness), the lightness mirrored
203/// (`1 - l`), the alpha kept. Black and white swap, a mid grey stays;
204/// mirrored twice, a colour comes back (to within rounding), unless a
205/// mirror was clipped: near the cusp of its hue (the most saturated
206/// colours, `#0000ff`), the mirrored colour can lie just outside the
207/// sRGB gamut, and is clipped to it channel by channel, so its hue is
208/// kept but its saturation and lightness move a little, and mirroring
209/// it back does not give the colour it came from. What the
210/// theme editor's "Generate the other variant" does to a colour
211/// ([`crate::ThemeDraft::generate_counterpart`]).
212///
213/// ```
214/// use egui_pop_tokens::{Color, palette};
215///
216/// let white = palette::mirror(Color::BLACK);
217/// assert_eq!(white.to_hex(), "#ffffff");
218/// let deep = Color::from_hex("#1a3a6e").unwrap();
219/// let pale = palette::mirror(deep);
220/// assert!(deep.is_dark() && !pale.is_dark());
221/// ```
222pub fn mirror(c: Color) -> Color {
223    let hsl = Okhsl::from_color(c);
224    let out = Okhsl {
225        l: 1.0 - hsl.l,
226        ..hsl
227    }
228    .to_color();
229    Color { a: c.a, ..out }
230}
231
232/// Whether a seed gives a ramp as it is ([`clamp_seed`] leaves it).
233pub fn is_usable_seed(seed: Color) -> bool {
234    clamp_seed(seed).to_hex() == Color { a: 1.0, ..seed }.to_hex()
235}
236
237/// The dark text of a dark scheme's solid: nearly black, of the seed's
238/// hue.
239fn dark_text(h: f32, s: f32) -> Color {
240    Okhsl {
241        h,
242        s: s.min(0.3),
243        l: 0.06,
244    }
245    .to_color()
246}
247
248/// The text colour that reads on a solid fill, as APCA ranks them:
249/// white, or `dark` (nearly black), whichever has the larger Lc.
250pub fn text_on(solid: Color, dark: Color) -> Color {
251    if apca::lc(Color::WHITE, solid).abs() >= apca::lc(dark, solid).abs() {
252        Color::WHITE
253    } else {
254        dark
255    }
256}
257
258/// Whether text reads on a solid well enough for a ramp's step 9.
259fn reads(text: Color, solid: Color) -> bool {
260    apca::lc(text, solid).abs() >= SOLID_LC && contrast_ratio(text, solid) >= SOLID_RATIO
261}
262
263/// What a ramp is drawn with in a theme, when it is known: the ramp is
264/// then fitted to it ([`Ramp::fitted`]).
265#[derive(Clone, Debug, Default, PartialEq)]
266pub struct Backdrop {
267    /// Where step 9 is drawn as text (an accent on panels, a keyword in
268    /// an editor): it reaches [`FITTED_RATIO`] on each.
269    pub surfaces: Vec<Color>,
270    /// Where step 9 is drawn as a part to see (a slider's fill on its
271    /// track): it reaches 3:1 (3.1, for rounding) on each when the
272    /// scheme's direction allows.
273    pub parts: Vec<Color>,
274    /// Text drawn on steps 3 to 5 (a selection): those steps move away
275    /// from it until it reaches [`FITTED_RATIO`].
276    pub text: Vec<Color>,
277}
278
279impl Backdrop {
280    /// Where an accent's step 9 is drawn as text, in the contrast pairs:
281    /// the surfaces, the editor's background, and what a badge on the
282    /// accent is written in.
283    pub const SURFACES: &'static [&'static str] = &[
284        "surface.canvas",
285        "surface.panel",
286        "surface.raised",
287        "surface.overlay",
288        "surface.sunken",
289        "editor-frame.rest.fill",
290        "indicator-badge.rest.text",
291    ];
292    /// Where it is drawn as a part to see: a slider's and a progress
293    /// bar's track.
294    pub const PARTS: &'static [&'static str] = &["slider.rest.fill", "progress-bar.rest.fill"];
295    /// The text drawn on its quiet steps (the selection is step 5).
296    pub const TEXT: &'static [&'static str] = &[
297        "text.default",
298        "syntax.plain",
299        "terminal.foreground",
300        "command-palette-row.rest.text",
301    ];
302
303    /// The backdrop of an accent in a theme, its colours read by path
304    /// ([`Backdrop::SURFACES`], [`Backdrop::PARTS`], [`Backdrop::TEXT`]);
305    /// a path without a colour is left out.
306    pub fn from_tokens(color: impl Fn(&str) -> Option<Color>) -> Backdrop {
307        let all = |paths: &[&str]| paths.iter().filter_map(|p| color(p)).collect();
308        Backdrop {
309            surfaces: all(Self::SURFACES),
310            parts: all(Self::PARTS),
311            text: all(Self::TEXT),
312        }
313    }
314}
315
316/// The WCAG ratio a fitted ramp reaches on the surfaces and text of its
317/// [`Backdrop`]: AA's 4.5:1, with a small margin for rounding.
318pub const FITTED_RATIO: f32 = 4.6;
319
320/// A ramp and the text colour on its solid step.
321#[derive(Clone, Copy, Debug, PartialEq)]
322pub struct Ramp {
323    /// Steps 1 to 12 (`steps[0]` is step 1).
324    pub steps: [Color; 12],
325    /// The text that reads on step 9 and step 10 (a scale's `contrast`).
326    pub contrast: Color,
327}
328
329impl Ramp {
330    /// The ramp of a seed in a scheme (the seed clamped first).
331    pub fn new(seed: Color, scheme: Scheme) -> Ramp {
332        Ramp::fitted(seed, scheme, &Backdrop::default())
333    }
334
335    /// The ramp of a seed in a scheme, fitted to what a theme draws it
336    /// with: step 9 moves on (darker in light, lighter in dark) until it
337    /// also reads on the backdrop's surfaces and is seen on its parts,
338    /// and steps 3 to 5 move away from its text until it reads on them.
339    pub fn fitted(seed: Color, scheme: Scheme, backdrop: &Backdrop) -> Ramp {
340        let clamped = clamp_seed(seed);
341        let seed = Okhsl::from_color(clamped);
342        let (h, s0) = (seed.h, seed.s);
343        let mults = match scheme {
344            Scheme::Light => LIGHT_S,
345            Scheme::Dark => DARK_S,
346        };
347        let sat = |step: usize| (s0 * mults[step]).min(saturation_cap(h, step, scheme));
348
349        // Step 9: the seed, its lightness moved until the text reads.
350        let s9 = sat(8);
351        let dark = dark_text(h, s0);
352        let (text, mut l9) = match scheme {
353            Scheme::Light => (Color::WHITE, seed.l.max(LIGHT_SOLID_MIN_L)),
354            Scheme::Dark => (dark, seed.l.min(DARK_SOLID_MAX_L)),
355        };
356        let solid = |l: f32| Okhsl { h, s: s9, l }.to_color();
357        let behind = match scheme {
358            Scheme::Light => Color::WHITE,
359            Scheme::Dark => dark,
360        };
361        for _ in 0..200 {
362            let c = solid(l9);
363            let fits = backdrop
364                .surfaces
365                .iter()
366                .all(|b| contrast_ratio(c, *b) >= FITTED_RATIO)
367                && backdrop.parts.iter().all(|b| contrast_ratio(c, *b) >= 3.1);
368            if reads(text, c) && contrast_ratio(c, behind) >= SOLID_RATIO && fits {
369                break;
370            }
371            match scheme {
372                Scheme::Light if l9 > 0.05 => l9 -= 0.005,
373                Scheme::Dark if l9 < 0.98 => l9 += 0.005,
374                _ => break,
375            }
376        }
377
378        let mut l = [0.0_f32; 12];
379        match scheme {
380            Scheme::Light => {
381                l[..7].copy_from_slice(&LIGHT_L);
382                l[8] = l9;
383                l[7] = (l9 + 0.09).min(LIGHT_L[6] - 0.04);
384                l[9] = l9 - 0.045;
385                l[10] = (l9 - 0.03).min(0.45);
386                l[11] = LIGHT_TEXT_L.min(l[10] - 0.1);
387            }
388            Scheme::Dark => {
389                l[..7].copy_from_slice(&DARK_L);
390                l[8] = l9;
391                l[7] = (l9 - 0.08).max(DARK_L[6] + 0.05);
392                l[9] = (l9 + 0.05).min(0.97);
393                l[10] = (l9 + 0.08).clamp(0.76, 0.9);
394                l[11] = DARK_TEXT_L.max(l[10] + 0.04);
395            }
396        }
397        // Steps 3 to 5 away from the text drawn on them, then 1 and 2
398        // kept beyond them.
399        let quiet = |i: usize, l: f32| {
400            Okhsl {
401                h: shifted_hue(h, l - l9),
402                s: sat(i),
403                l,
404            }
405            .to_color()
406        };
407        for i in (2..5).rev() {
408            for _ in 0..100 {
409                let c = quiet(i, l[i]);
410                if backdrop
411                    .text
412                    .iter()
413                    .all(|t| contrast_ratio(*t, c) >= FITTED_RATIO)
414                {
415                    break;
416                }
417                match scheme {
418                    Scheme::Light if l[i] < 0.995 => l[i] = (l[i] + 0.005).min(0.995),
419                    Scheme::Dark if l[i] > 0.01 => l[i] = (l[i] - 0.005).max(0.01),
420                    _ => break,
421                }
422            }
423        }
424        for i in (0..2).rev() {
425            l[i] = match scheme {
426                Scheme::Light => l[i].max((l[i + 1] + 0.005).min(0.998)),
427                Scheme::Dark => l[i].min((l[i + 1] - 0.005).max(0.0)),
428            };
429        }
430        let mut steps = [Color::BLACK; 12];
431        let as_given = (l9 - seed.l).abs() < 1e-6 && (s9 - s0).abs() < 1e-6;
432        for (i, step) in steps.iter_mut().enumerate() {
433            if i == 8 && as_given {
434                // The seed itself, not its round trip through OkHsl.
435                *step = clamped;
436                continue;
437            }
438            let hue = if i == 8 { h } else { shifted_hue(h, l[i] - l9) };
439            let s = if i == 8 { s9 } else { sat(i) };
440            *step = Okhsl { h: hue, s, l: l[i] }.to_color();
441        }
442        let contrast = text_on(steps[8], dark);
443        Ramp { steps, contrast }
444    }
445
446    /// The scale as raw tokens: `<name>.1` to `<name>.12` and
447    /// `<name>.contrast`, each a `#rrggbb` colour.
448    pub fn tokens(&self, name: &str) -> Vec<(String, Json)> {
449        let mut out: Vec<(String, Json)> = self
450            .steps
451            .iter()
452            .enumerate()
453            .map(|(i, c)| (format!("{name}.{}", i + 1), json!(c.to_hex())))
454            .collect();
455        out.push((format!("{name}.contrast"), json!(self.contrast.to_hex())));
456        out
457    }
458}
459
460/// The twelve steps generated from a seed for a scheme ([`Ramp::new`]).
461pub fn ramp(seed: Color, scheme: Scheme) -> [Color; 12] {
462    Ramp::new(seed, scheme).steps
463}
464
465/// The root `$extensions` key under which a token file gives colour
466/// scales by their seed rather than as twelve values:
467///
468/// ```json
469/// { "$extensions": { "org.egui-pop.seeds": {
470///     "blue": { "seed": "#8e44ad", "scheme": "light" }
471/// } } }
472/// ```
473///
474/// When the theme is resolved, each such scale is generated from its
475/// seed ([`Ramp::fitted`], fitted to the theme's surfaces and text as
476/// the file gives them), then the file's own tokens are laid over it: a
477/// step the file also gives explicitly keeps the file's value.
478pub const SEEDS_EXTENSION: &str = "org.egui-pop.seeds";
479
480/// A colour scale given by its seed in a token file ([`SEEDS_EXTENSION`]).
481#[derive(Clone, Copy, Debug, PartialEq)]
482pub struct Seed {
483    /// The seed colour (its alpha ignored).
484    pub color: Color,
485    /// The scheme the scale is generated for; `None`: the theme's, from
486    /// its panels (`surface.panel`).
487    pub scheme: Option<Scheme>,
488}
489
490impl Seed {
491    /// A seed for a scheme.
492    pub fn new(color: Color, scheme: Scheme) -> Seed {
493        Seed {
494            color,
495            scheme: Some(scheme),
496        }
497    }
498
499    /// As written under [`SEEDS_EXTENSION`]: `{ "seed": "#rrggbb",
500    /// "scheme": "light" }`, the scheme left out when not given.
501    pub fn to_json(self) -> Json {
502        let mut entry = serde_json::Map::new();
503        entry.insert(
504            "seed".into(),
505            json!(
506                Color {
507                    a: 1.0,
508                    ..self.color
509                }
510                .to_hex()
511            ),
512        );
513        if let Some(scheme) = self.scheme {
514            entry.insert("scheme".into(), json!(scheme.name()));
515        }
516        Json::Object(entry)
517    }
518
519    /// Reads an entry written by [`Seed::to_json`]; why not, when it
520    /// cannot be read.
521    pub fn from_json(entry: &Json) -> Result<Seed, String> {
522        let obj = entry
523            .as_object()
524            .ok_or_else(|| format!("`{entry}` is not a map with a `seed`"))?;
525        let color = match obj.get("seed") {
526            Some(Json::String(hex)) => {
527                Color::from_hex(hex).ok_or_else(|| format!("`{hex}` is not a hex colour"))?
528            }
529            Some(other) => return Err(format!("`seed`: `{other}` is not a hex colour")),
530            None => return Err("no `seed`".into()),
531        };
532        let scheme = match obj.get("scheme") {
533            None => None,
534            Some(Json::String(s)) if s == "light" => Some(Scheme::Light),
535            Some(Json::String(s)) if s == "dark" => Some(Scheme::Dark),
536            Some(other) => {
537                return Err(format!("`scheme`: `{other}` is neither `light` nor `dark`"));
538            }
539        };
540        Ok(Seed { color, scheme })
541    }
542}
543
544impl Scheme {
545    /// `"light"` or `"dark"`, as a file names it.
546    pub fn name(self) -> &'static str {
547        match self {
548            Scheme::Light => "light",
549            Scheme::Dark => "dark",
550        }
551    }
552}
553
554impl crate::TokenFile {
555    /// The colour scales the file gives by their seed
556    /// ([`SEEDS_EXTENSION`]), by scale name, and a warning for each entry
557    /// that cannot be read (left out: the scale keeps the values under
558    /// it).
559    pub fn seeds(
560        &self,
561    ) -> (
562        std::collections::BTreeMap<String, Seed>,
563        Vec<crate::Warning>,
564    ) {
565        let mut seeds = std::collections::BTreeMap::new();
566        let mut warnings = Vec::new();
567        let Some(raw) = self
568            .extensions
569            .as_ref()
570            .and_then(|x| x.get(SEEDS_EXTENSION))
571        else {
572            return (seeds, warnings);
573        };
574        let Some(map) = raw.as_object() else {
575            warnings.push(crate::Warning::Invalid {
576                path: format!("$extensions.{SEEDS_EXTENSION}"),
577                reason: format!("`{raw}` is not a map of scales"),
578            });
579            return (seeds, warnings);
580        };
581        for (scale, entry) in map {
582            let path = format!("$extensions.{SEEDS_EXTENSION}.{scale}");
583            if scale.is_empty() || scale.contains(['.', '{', '}']) {
584                warnings.push(crate::Warning::Invalid {
585                    path,
586                    reason: "a scale's name may not be empty or contain `.`, `{` or `}`".into(),
587                });
588                continue;
589            }
590            match Seed::from_json(entry) {
591                Ok(seed) => {
592                    seeds.insert(scale.clone(), seed);
593                }
594                Err(reason) => warnings.push(crate::Warning::Invalid { path, reason }),
595            }
596        }
597        (seeds, warnings)
598    }
599
600    /// Gives a scale by its seed (`None` takes it out), keeping the rest
601    /// of the root `$extensions`.
602    pub fn set_seed(&mut self, scale: &str, seed: Option<Seed>) {
603        let mut root = match self.extensions.take() {
604            Some(Json::Object(m)) => m,
605            _ => serde_json::Map::new(),
606        };
607        let mut seeds = match root.remove(SEEDS_EXTENSION) {
608            Some(Json::Object(m)) => m,
609            _ => serde_json::Map::new(),
610        };
611        match seed {
612            Some(seed) => {
613                seeds.insert(scale.to_string(), seed.to_json());
614            }
615            None => {
616                seeds.remove(scale);
617            }
618        }
619        if !seeds.is_empty() {
620            root.insert(SEEDS_EXTENSION.to_string(), Json::Object(seeds));
621        }
622        self.extensions = (!root.is_empty()).then_some(Json::Object(root));
623    }
624}
625
626/// OkHsl over Oklab, after Björn Ottosson's reference implementation
627/// ("Okhsv and Okhsl", 2021, MIT).
628mod ok {
629    use std::f64::consts::PI;
630
631    use crate::Color;
632
633    fn linear(c: f32) -> f64 {
634        let c = f64::from(c.clamp(0.0, 1.0));
635        if c <= 0.040_45 {
636            c / 12.92
637        } else {
638            ((c + 0.055) / 1.055).powf(2.4)
639        }
640    }
641
642    fn linear_srgb_to_oklab(r: f64, g: f64, b: f64) -> (f64, f64, f64) {
643        let l = 0.412_221_470_8 * r + 0.536_332_536_3 * g + 0.051_445_992_9 * b;
644        let m = 0.211_903_498_2 * r + 0.680_699_545_1 * g + 0.107_396_956_6 * b;
645        let s = 0.088_302_461_9 * r + 0.281_718_837_6 * g + 0.629_978_700_5 * b;
646        let (l_, m_, s_) = (l.cbrt(), m.cbrt(), s.cbrt());
647        (
648            0.210_454_255_3 * l_ + 0.793_617_785_0 * m_ - 0.004_072_046_8 * s_,
649            1.977_998_495_1 * l_ - 2.428_592_205_0 * m_ + 0.450_593_709_9 * s_,
650            0.025_904_037_1 * l_ + 0.782_771_766_2 * m_ - 0.808_675_766_0 * s_,
651        )
652    }
653
654    fn oklab_to_linear_srgb(l: f64, a: f64, b: f64) -> (f64, f64, f64) {
655        let l_ = l + 0.396_337_777_4 * a + 0.215_803_757_3 * b;
656        let m_ = l - 0.105_561_345_8 * a - 0.063_854_172_8 * b;
657        let s_ = l - 0.089_484_177_5 * a - 1.291_485_548_0 * b;
658        let (l3, m3, s3) = (l_.powi(3), m_.powi(3), s_.powi(3));
659        (
660            4.076_741_662_1 * l3 - 3.307_711_591_3 * m3 + 0.230_969_929_2 * s3,
661            -1.268_438_004_6 * l3 + 2.609_757_401_1 * m3 - 0.341_319_396_5 * s3,
662            -0.004_196_086_3 * l3 - 0.703_418_614_7 * m3 + 1.707_614_701_0 * s3,
663        )
664    }
665
666    /// The most saturation (C / L) at a hue (`a`, `b` normalised) that
667    /// stays in sRGB.
668    fn compute_max_saturation(a: f64, b: f64) -> f64 {
669        let (k0, k1, k2, k3, k4, wl, wm, ws) = if -1.881_703_28 * a - 0.809_364_93 * b > 1.0 {
670            (
671                1.190_862_77,
672                1.765_767_28,
673                0.596_626_41,
674                0.755_151_97,
675                0.567_712_45,
676                4.076_741_662_1,
677                -3.307_711_591_3,
678                0.230_969_929_2,
679            )
680        } else if 1.814_441_04 * a - 1.194_452_76 * b > 1.0 {
681            (
682                0.739_565_15,
683                -0.459_544_04,
684                0.082_854_27,
685                0.125_410_70,
686                0.145_032_04,
687                -1.268_438_004_6,
688                2.609_757_401_1,
689                -0.341_319_396_5,
690            )
691        } else {
692            (
693                1.357_336_52,
694                -0.009_157_99,
695                -1.151_302_10,
696                -0.505_596_06,
697                0.006_921_67,
698                -0.004_196_086_3,
699                -0.703_418_614_7,
700                1.707_614_701_0,
701            )
702        };
703        let mut s = k0 + k1 * a + k2 * b + k3 * a * a + k4 * a * b;
704        let k_l = 0.396_337_777_4 * a + 0.215_803_757_3 * b;
705        let k_m = -0.105_561_345_8 * a - 0.063_854_172_8 * b;
706        let k_s = -0.089_484_177_5 * a - 1.291_485_548_0 * b;
707        // One step of Halley's method.
708        let l_ = 1.0 + s * k_l;
709        let m_ = 1.0 + s * k_m;
710        let s_ = 1.0 + s * k_s;
711        let (l, m, ss) = (l_.powi(3), m_.powi(3), s_.powi(3));
712        let (l_ds, m_ds, s_ds) = (
713            3.0 * k_l * l_ * l_,
714            3.0 * k_m * m_ * m_,
715            3.0 * k_s * s_ * s_,
716        );
717        let (l_ds2, m_ds2, s_ds2) = (
718            6.0 * k_l * k_l * l_,
719            6.0 * k_m * k_m * m_,
720            6.0 * k_s * k_s * s_,
721        );
722        let f = wl * l + wm * m + ws * ss;
723        let f1 = wl * l_ds + wm * m_ds + ws * s_ds;
724        let f2 = wl * l_ds2 + wm * m_ds2 + ws * s_ds2;
725        s -= f * f1 / (f1 * f1 - 0.5 * f * f2);
726        s
727    }
728
729    /// The lightness and chroma of the most saturated colour of a hue.
730    fn find_cusp(a: f64, b: f64) -> (f64, f64) {
731        let s_cusp = compute_max_saturation(a, b);
732        let (r, g, bl) = oklab_to_linear_srgb(1.0, s_cusp * a, s_cusp * b);
733        let l_cusp = (1.0 / r.max(g).max(bl)).cbrt();
734        (l_cusp, l_cusp * s_cusp)
735    }
736
737    /// Where the line from (L0, 0) to (L1, C1) leaves the gamut, as `t`.
738    fn find_gamut_intersection(a: f64, b: f64, l1: f64, c1: f64, l0: f64) -> f64 {
739        let (cusp_l, cusp_c) = find_cusp(a, b);
740        if ((l1 - l0) * cusp_c - (cusp_l - l0) * c1) <= 0.0 {
741            return cusp_c * l0 / (c1 * cusp_l + cusp_c * (l0 - l1));
742        }
743        let mut t = cusp_c * (l0 - 1.0) / (c1 * (cusp_l - 1.0) + cusp_c * (l0 - l1));
744        let dl = l1 - l0;
745        let dc = c1;
746        let k_l = 0.396_337_777_4 * a + 0.215_803_757_3 * b;
747        let k_m = -0.105_561_345_8 * a - 0.063_854_172_8 * b;
748        let k_s = -0.089_484_177_5 * a - 1.291_485_548_0 * b;
749        let l_dt = dl + dc * k_l;
750        let m_dt = dl + dc * k_m;
751        let s_dt = dl + dc * k_s;
752        let ll = l0 * (1.0 - t) + t * l1;
753        let c = t * c1;
754        let l_ = ll + c * k_l;
755        let m_ = ll + c * k_m;
756        let s_ = ll + c * k_s;
757        let (l, m, s) = (l_.powi(3), m_.powi(3), s_.powi(3));
758        let (ldt, mdt, sdt) = (
759            3.0 * l_dt * l_ * l_,
760            3.0 * m_dt * m_ * m_,
761            3.0 * s_dt * s_ * s_,
762        );
763        let (ldt2, mdt2, sdt2) = (
764            6.0 * l_dt * l_dt * l_,
765            6.0 * m_dt * m_dt * m_,
766            6.0 * s_dt * s_dt * s_,
767        );
768        let step = |w: (f64, f64, f64)| {
769            let f = w.0 * l + w.1 * m + w.2 * s - 1.0;
770            let f1 = w.0 * ldt + w.1 * mdt + w.2 * sdt;
771            let f2 = w.0 * ldt2 + w.1 * mdt2 + w.2 * sdt2;
772            let u = f1 / (f1 * f1 - 0.5 * f * f2);
773            if u >= 0.0 { -f * u } else { f64::MAX }
774        };
775        let t_r = step((4.076_741_662_1, -3.307_711_591_3, 0.230_969_929_2));
776        let t_g = step((-1.268_438_004_6, 2.609_757_401_1, -0.341_319_396_5));
777        let t_b = step((-0.004_196_086_3, -0.703_418_614_7, 1.707_614_701_0));
778        t += t_r.min(t_g).min(t_b);
779        t
780    }
781
782    const K1: f64 = 0.206;
783    const K2: f64 = 0.03;
784    const K3: f64 = (1.0 + K1) / (1.0 + K2);
785
786    fn toe(x: f64) -> f64 {
787        0.5 * (K3 * x - K1 + ((K3 * x - K1) * (K3 * x - K1) + 4.0 * K2 * K3 * x).sqrt())
788    }
789
790    fn toe_inv(x: f64) -> f64 {
791        (x * x + K1 * x) / (K3 * (x + K2))
792    }
793
794    fn st_mid(a: f64, b: f64) -> (f64, f64) {
795        let s = 0.115_169_93
796            + 1.0
797                / (7.447_789_70
798                    + 4.159_012_40 * b
799                    + a * (-2.195_573_47
800                        + 1.751_984_01 * b
801                        + a * (-2.137_049_48 - 10.023_010_43 * b
802                            + a * (-4.248_945_61 + 5.387_708_19 * b + 4.698_910_13 * a))));
803        let t = 0.112_396_42
804            + 1.0
805                / (1.613_203_20 - 0.681_243_79 * b
806                    + a * (0.403_706_12
807                        + 0.901_481_23 * b
808                        + a * (-0.270_879_43
809                            + 0.612_239_90 * b
810                            + a * (0.002_992_15 - 0.453_995_68 * b - 0.146_618_72 * a))));
811        (s, t)
812    }
813
814    /// C at saturation 0 to 0.8 (C0), at 0.8 (Cmid) and at 1 (Cmax).
815    fn cs(l: f64, a: f64, b: f64) -> (f64, f64, f64) {
816        let (cusp_l, cusp_c) = find_cusp(a, b);
817        let c_max = find_gamut_intersection(a, b, l, 1.0, l);
818        let (st_s, st_t) = (cusp_c / cusp_l, cusp_c / (1.0 - cusp_l));
819        let k = c_max / (l * st_s).min((1.0 - l) * st_t);
820        let (mid_s, mid_t) = st_mid(a, b);
821        let ca = l * mid_s;
822        let cb = (1.0 - l) * mid_t;
823        let c_mid = 0.9 * k * (1.0 / (1.0 / ca.powi(4) + 1.0 / cb.powi(4))).sqrt().sqrt();
824        let ca = l * 0.4;
825        let cb = (1.0 - l) * 0.8;
826        let c_0 = (1.0 / (1.0 / (ca * ca) + 1.0 / (cb * cb))).sqrt();
827        (c_0, c_mid, c_max)
828    }
829
830    pub(super) fn okhsl_to_srgb(h: f64, s: f64, l: f64) -> Color {
831        if l >= 1.0 {
832            return Color::WHITE;
833        }
834        if l <= 0.0 {
835            return Color::BLACK;
836        }
837        let (r, g, b) = okhsl_to_linear(h, s, l);
838        Color::from_linear(r as f32, g as f32, b as f32, 1.0)
839    }
840
841    /// The linear sRGB channels of an OkHsl colour (`l` within 0 and 1,
842    /// exclusive), before they are clipped to the gamut: near the cusp
843    /// of a hue, the gamut approximation lets a channel leave 0 to 1.
844    pub(super) fn okhsl_to_linear(h: f64, s: f64, l: f64) -> (f64, f64, f64) {
845        let rad = h.to_radians();
846        let (a_, b_) = (rad.cos(), rad.sin());
847        let ll = toe_inv(l);
848        let c = if s <= 0.0 {
849            0.0
850        } else {
851            let (c_0, c_mid, c_max) = cs(ll, a_, b_);
852            const MID: f64 = 0.8;
853            const MID_INV: f64 = 1.25;
854            if s < MID {
855                let t = MID_INV * s;
856                let k1 = MID * c_0;
857                let k2 = 1.0 - k1 / c_mid;
858                t * k1 / (1.0 - k2 * t)
859            } else {
860                let t = (s - MID) / (1.0 - MID);
861                let k0 = c_mid;
862                let k1 = (1.0 - MID) * c_mid * c_mid * MID_INV * MID_INV / c_0;
863                let k2 = 1.0 - k1 / (c_max - c_mid);
864                k0 + t * k1 / (1.0 - k2 * t)
865            }
866        };
867        oklab_to_linear_srgb(ll, c * a_, c * b_)
868    }
869
870    pub(super) fn srgb_to_okhsl(c: Color) -> (f64, f64, f64) {
871        let (ll, a, b) = linear_srgb_to_oklab(linear(c.r), linear(c.g), linear(c.b));
872        let l = toe(ll).clamp(0.0, 1.0);
873        let chroma = (a * a + b * b).sqrt();
874        if chroma < 1e-6 || ll <= 1e-6 || ll >= 1.0 - 1e-6 {
875            return (0.0, 0.0, l);
876        }
877        let (a_, b_) = (a / chroma, b / chroma);
878        let h = (0.5 + 0.5 * (-b).atan2(-a) / PI) * 360.0;
879        let (c_0, c_mid, c_max) = cs(ll, a_, b_);
880        const MID: f64 = 0.8;
881        const MID_INV: f64 = 1.25;
882        let s = if chroma < c_mid {
883            let k1 = MID * c_0;
884            let k2 = 1.0 - k1 / c_mid;
885            let t = chroma / (k1 + k2 * chroma);
886            t * MID
887        } else {
888            let k0 = c_mid;
889            let k1 = (1.0 - MID) * c_mid * c_mid * MID_INV * MID_INV / c_0;
890            let k2 = 1.0 - k1 / (c_max - c_mid);
891            let t = (chroma - k0) / (k1 + k2 * (chroma - k0));
892            MID + (1.0 - MID) * t
893        };
894        (h.rem_euclid(360.0), s.clamp(0.0, 1.0), l)
895    }
896}
897
898#[cfg(test)]
899mod tests {
900    use super::*;
901
902    fn seeds() -> Vec<Color> {
903        let mut out = Vec::new();
904        for h in (0..360).step_by(15) {
905            for s in [0.35, 0.7, 1.0] {
906                for l in [0.3, 0.5, 0.65, 0.8] {
907                    out.push(Okhsl { h: h as f32, s, l }.to_color());
908                }
909            }
910        }
911        for hex in [
912            "#000000", "#ffffff", "#808080", "#ffff00", "#00ff00", "#0000ff",
913        ] {
914            out.push(Color::from_hex(hex).unwrap());
915        }
916        out
917    }
918
919    #[test]
920    fn okhsl_round_trips() {
921        for hex in [
922            "#3a7bd5", "#f0c060", "#2e64a6", "#c0392b", "#27ae60", "#808080",
923        ] {
924            let c = Color::from_hex(hex).unwrap();
925            let back = Okhsl::from_color(c).to_color();
926            assert_eq!(back.to_hex(), hex, "{:?}", Okhsl::from_color(c));
927        }
928        let white = Okhsl::from_color(Color::WHITE);
929        assert!(white.s < 1e-3 && (white.l - 1.0).abs() < 1e-3, "{white:?}");
930        // Saturation 1 stays in the gamut.
931        for h in (0..360).step_by(10) {
932            for l in [0.2, 0.5, 0.8] {
933                let c = Okhsl {
934                    h: h as f32,
935                    s: 1.0,
936                    l,
937                }
938                .to_color();
939                let back = Okhsl::from_color(c);
940                assert!(back.s > 0.9, "h {h} l {l}: {back:?}");
941            }
942        }
943    }
944
945    #[test]
946    fn contrast_targets_are_met_across_hues_in_both_schemes() {
947        for scheme in [Scheme::Light, Scheme::Dark] {
948            for seed in seeds() {
949                let r = Ramp::new(seed, scheme);
950                let s = &r.steps;
951                let what = format!("{} {scheme:?}", seed.to_hex());
952                // Text on the solid and on its hover, by both measures.
953                for step in [8, 9] {
954                    let ratio = contrast_ratio(r.contrast, s[step]);
955                    assert!(ratio >= 4.5, "{what}: contrast on {}: {ratio}", step + 1);
956                }
957                let lc = apca::lc(r.contrast, s[8]).abs();
958                assert!(lc >= SOLID_LC, "{what}: Lc on 9: {lc}");
959                // The solid as text on the backgrounds (egui-pop's accent
960                // is drawn as text on panels).
961                for bg in [0, 1] {
962                    let ratio = contrast_ratio(s[8], s[bg]);
963                    assert!(ratio >= 4.5, "{what}: 9 on {}: {ratio}", bg + 1);
964                }
965                // Low- and high-contrast text on the backgrounds.
966                for bg in [0, 1] {
967                    let low = contrast_ratio(s[10], s[bg]);
968                    let high = contrast_ratio(s[11], s[bg]);
969                    assert!(low >= 4.5, "{what}: 11 on {}: {low}", bg + 1);
970                    assert!(high >= 7.0, "{what}: 12 on {}: {high}", bg + 1);
971                }
972                // Borders that must be seen: step 8 on the backgrounds.
973                let ui = contrast_ratio(s[7], s[1]);
974                assert!(ui >= 3.0, "{what}: 8 on 2: {ui}");
975                // Backgrounds and borders run one way.
976                let lum: Vec<f32> = s[..7].iter().map(|c| c.relative_luminance()).collect();
977                for w in lum.windows(2) {
978                    match scheme {
979                        Scheme::Light => assert!(w[0] > w[1], "{what}: {lum:?}"),
980                        Scheme::Dark => assert!(w[0] < w[1], "{what}: {lum:?}"),
981                    }
982                }
983                assert_eq!(scheme == Scheme::Dark, s[0].is_dark(), "{what}");
984            }
985        }
986    }
987
988    #[test]
989    fn ramps_are_deterministic() {
990        for seed in seeds() {
991            for scheme in [Scheme::Light, Scheme::Dark] {
992                assert_eq!(Ramp::new(seed, scheme), Ramp::new(seed, scheme));
993            }
994        }
995    }
996
997    #[test]
998    fn a_grey_seed_gives_a_neutral_ramp() {
999        for scheme in [Scheme::Light, Scheme::Dark] {
1000            for c in ramp(Color::from_hex("#7a7a7a").unwrap(), scheme) {
1001                let [r, g, b, _] = c.to_srgba_u8();
1002                assert!(r.abs_diff(g) <= 1 && g.abs_diff(b) <= 1, "{c}");
1003            }
1004        }
1005    }
1006
1007    #[test]
1008    fn a_usable_seed_is_the_dark_solid_or_close_to_it() {
1009        // A mid blue reads with dark text in dark: it is step 9 as given.
1010        let seed = Color::from_hex("#8cc0ff").unwrap();
1011        assert!(is_usable_seed(seed));
1012        let dark = ramp(seed, Scheme::Dark);
1013        assert_eq!(dark[8].to_hex(), seed.to_hex());
1014        // In light it is darkened until white text reads, its hue kept.
1015        let light = ramp(seed, Scheme::Light);
1016        let (a, b) = (Okhsl::from_color(seed), Okhsl::from_color(light[8]));
1017        assert!(b.l < a.l && (a.h - b.h).abs() < 1.0, "{a:?} {b:?}");
1018    }
1019
1020    #[test]
1021    fn seeds_out_of_range_are_clamped() {
1022        for hex in ["#000000", "#ffffff", "#020304", "#fefefe"] {
1023            let seed = Color::from_hex(hex).unwrap();
1024            assert!(!is_usable_seed(seed), "{hex}");
1025            let l = Okhsl::from_color(clamp_seed(seed)).l;
1026            assert!(
1027                l >= SEED_LIGHTNESS.0 - 1e-3 && l <= SEED_LIGHTNESS.1 + 1e-3,
1028                "{hex}: {l}"
1029            );
1030        }
1031        let neon = Color::from_hex("#00ff66").unwrap();
1032        assert!(Okhsl::from_color(clamp_seed(neon)).s <= 0.86);
1033    }
1034
1035    #[test]
1036    fn writes_a_scale_as_tokens() {
1037        let t = Ramp::new(Color::from_hex("#c0392b").unwrap(), Scheme::Light).tokens("brick");
1038        assert_eq!(t.len(), 13);
1039        assert_eq!(t[0].0, "brick.1");
1040        assert_eq!(t[12].0, "brick.contrast");
1041        assert!(
1042            t.iter()
1043                .all(|(_, v)| v.as_str().is_some_and(|s| s.starts_with('#')))
1044        );
1045    }
1046
1047    /// Whether a colour's mirror is clipped to the sRGB gamut: its
1048    /// mirrored coordinates give a channel outside 0 to 1.
1049    fn mirror_clips(c: Color) -> bool {
1050        let hsl = Okhsl::from_color(c);
1051        let l = 1.0 - f64::from(hsl.l);
1052        if l <= 0.0 || l >= 1.0 {
1053            return false;
1054        }
1055        let (r, g, b) = ok::okhsl_to_linear(f64::from(hsl.h), f64::from(hsl.s.clamp(0.0, 1.0)), l);
1056        [r, g, b].iter().any(|x| !(0.0..=1.0).contains(x))
1057    }
1058
1059    #[test]
1060    fn a_mirrored_colour_keeps_its_hue_and_saturation() {
1061        assert_eq!(mirror(Color::BLACK).to_hex(), "#ffffff");
1062        assert_eq!(mirror(Color::WHITE).to_hex(), "#000000");
1063        let half = Color {
1064            a: 0.5,
1065            ..Color::BLACK
1066        };
1067        assert_eq!(mirror(half).to_hex(), "#ffffff80");
1068        let mut clipped = 0;
1069        for c in seeds() {
1070            let m = mirror(c);
1071            let (a, b) = (Okhsl::from_color(c), Okhsl::from_color(m));
1072            assert!((a.l + b.l - 1.0).abs() < 0.01, "{c}: {a:?} {b:?}");
1073            if a.s > 0.05 && a.l > 0.05 && a.l < 0.95 {
1074                let dh = (a.h - b.h).abs();
1075                assert!(dh.min(360.0 - dh) < 1.0, "{c}: {a:?} {b:?}");
1076                assert!((a.s - b.s).abs() < 0.01, "{c}: {a:?} {b:?}");
1077            }
1078            if mirror_clips(c) || mirror_clips(m) {
1079                // Clipped to the gamut on the way: the hue is kept (to
1080                // within a few degrees), the round trip cannot hold.
1081                if a.s > 0.05 && a.l > 0.05 && a.l < 0.95 {
1082                    let back = Okhsl::from_color(mirror(m));
1083                    for other in [b, back] {
1084                        let dh = (a.h - other.h).abs();
1085                        assert!(dh.min(360.0 - dh) < 3.0, "{c}: {a:?} {other:?}");
1086                    }
1087                }
1088                clipped += 1;
1089                continue;
1090            }
1091            // Twice: back where it was.
1092            let back = mirror(m).to_srgba_u8();
1093            let was = c.to_srgba_u8();
1094            for i in 0..3 {
1095                assert!(back[i].abs_diff(was[i]) <= 2, "{c} -> {m} -> {back:?}");
1096            }
1097        }
1098        // `#0000ff`, at the cusp of its hue, is clipped.
1099        assert!(
1100            mirror_clips(Color::from_hex("#0000ff").unwrap())
1101                || mirror_clips(mirror(Color::from_hex("#0000ff").unwrap()))
1102        );
1103        assert!(clipped < seeds().len() / 2, "{clipped} clipped");
1104    }
1105}