Skip to main content

egui_pop_tokens/
theme.rs

1//! Themes: base themes, density overlays, accents and overrides composed
2//! into one set of resolved tokens.
3
4use std::collections::{BTreeMap, BTreeSet};
5use std::fmt;
6use std::path::Path;
7use std::str::FromStr;
8
9use serde_json::{Map, Value as Json, json};
10
11use crate::cache::Cache;
12use crate::contract::{Tier, contract, required};
13use crate::file::{RawToken, TokenFile, alias_target};
14use crate::palette::{Backdrop, Ramp, Scheme, Seed};
15use crate::{Color, Error, Value, Warning};
16
17/// The theme everything falls back to.
18pub const FALLBACK_THEME: &str = "pop-dark";
19
20/// The `$extensions` key of the alpha modifier: on a colour token, a
21/// number from 0 to 1 the colour's alpha is multiplied by, after its
22/// alias is followed (`{"$value": "{surface.overlay}", "$extensions":
23/// {"org.egui-pop.alpha": 0.85}}`, the overlay at 85 %). Every modifier
24/// met along a chain of aliases applies.
25pub const ALPHA_EXTENSION: &str = "org.egui-pop.alpha";
26
27/// The root `$extensions` key naming a theme's counterpart: the other
28/// variant, light or dark, of the same theme (`$extensions:
29/// {"org.egui-pop.variant-of": "pop-dark"}` in `pop-light`). Saying it
30/// on one side is enough: the other is found by looking it up. Not
31/// inherited through `$extends`: a theme built on `pop-light` is a
32/// theme of its own.
33pub const VARIANT_OF_EXTENSION: &str = "org.egui-pop.variant-of";
34
35/// The root `$extensions` key carrying a theme's counterpart inside its
36/// file: a light and dark pair saved as one file (the theme editor's).
37/// Its value names the counterpart and gives its token file, an
38/// ordinary one with its own stamp:
39///
40/// ```json
41/// { "$extends": "pop-dark",
42///   "$extensions": {
43///     "org.egui-pop.variant-of": "ocean-light",
44///     "org.egui-pop.counterpart": {
45///       "name": "ocean-light",
46///       "file": { "$extends": "pop-light",
47///                 "$extensions": { "org.egui-pop.variant-of": "ocean" } } } } }
48/// ```
49///
50/// [`Themes::add_text`] and [`Themes::add_path`] add the counterpart
51/// too, under its name; a reader that does not know the key loads the
52/// file's own variant alone.
53pub const COUNTERPART_EXTENSION: &str = "org.egui-pop.counterpart";
54
55impl TokenFile {
56    /// Sets (or, with `None`, removes) one entry of the root
57    /// `$extensions`, keeping the others.
58    pub fn set_extension(&mut self, key: &str, value: Option<Json>) {
59        let mut root = match self.extensions.take() {
60            Some(Json::Object(m)) => m,
61            _ => Map::new(),
62        };
63        match value {
64            Some(v) => {
65                root.insert(key.to_string(), v);
66            }
67            None => {
68                root.remove(key);
69            }
70        }
71        self.extensions = (!root.is_empty()).then_some(Json::Object(root));
72    }
73
74    /// The counterpart this file carries ([`COUNTERPART_EXTENSION`]),
75    /// under its name; `None` when it carries none, an error when the
76    /// entry cannot be read.
77    pub fn counterpart_file(&self) -> Option<Result<TokenFile, Error>> {
78        let raw = self.extensions.as_ref()?.get(COUNTERPART_EXTENSION)?;
79        let malformed = |reason: &str| Error::Malformed {
80            file: self.name.clone(),
81            path: format!("$extensions.{COUNTERPART_EXTENSION}"),
82            reason: reason.to_string(),
83        };
84        let Some(name) = raw
85            .get("name")
86            .and_then(Json::as_str)
87            .filter(|n| !n.is_empty())
88        else {
89            return Some(Err(malformed("no `name` naming the counterpart")));
90        };
91        if name == self.name {
92            return Some(Err(malformed("the counterpart has the file's own name")));
93        }
94        let Some(file) = raw.get("file").filter(|f| f.is_object()) else {
95            return Some(Err(malformed("no `file` giving the counterpart's tokens")));
96        };
97        Some(TokenFile::from_tree(name, file))
98    }
99
100    /// Makes this file carry `counterpart` ([`COUNTERPART_EXTENSION`]),
101    /// each naming the other ([`VARIANT_OF_EXTENSION`]); `None` removes
102    /// it.
103    pub fn set_counterpart_file(&mut self, counterpart: Option<TokenFile>) {
104        match counterpart {
105            Some(mut other) => {
106                other.set_extension(VARIANT_OF_EXTENSION, Some(json!(self.name)));
107                self.set_extension(VARIANT_OF_EXTENSION, Some(json!(other.name)));
108                self.set_extension(
109                    COUNTERPART_EXTENSION,
110                    Some(json!({ "name": other.name, "file": other.to_json() })),
111                );
112            }
113            None => self.set_extension(COUNTERPART_EXTENSION, None),
114        }
115    }
116}
117
118/// egui-pop's own base themes, in the order a switcher shows them.
119pub const POP_THEMES: &[&str] = &["pop-dark", "pop-light", "pop-high-contrast"];
120
121/// Every built-in theme, in the order a switcher shows them: egui-pop's
122/// own, then the editor-inspired ones by family, light before dark (their
123/// sources and licences are in `NOTICE`).
124pub const BUILT_IN_THEMES: &[&str] = &[
125    "pop-dark",
126    "pop-light",
127    "pop-high-contrast",
128    "github-light",
129    "github-dark",
130    "github-light-high-contrast",
131    "github-dark-high-contrast",
132    "catppuccin-latte",
133    "catppuccin-mocha",
134    "one-light",
135    "one-dark-pro",
136    "solarized-light",
137    "solarized-dark",
138    "gruvbox-light",
139    "gruvbox-dark",
140];
141
142/// The built-in themes' names for people (ids stay as they are): the
143/// editor-inspired ones say so, their names only describing where the
144/// colours come from.
145const BUILT_IN_LABELS: &[(&str, &str)] = &[
146    ("pop-dark", "Pop dark"),
147    ("pop-light", "Pop light"),
148    ("pop-high-contrast", "Pop high contrast"),
149    ("github-light", "GitHub-inspired Light"),
150    ("github-dark", "GitHub-inspired Dark"),
151    (
152        "github-light-high-contrast",
153        "GitHub-inspired Light High Contrast",
154    ),
155    (
156        "github-dark-high-contrast",
157        "GitHub-inspired Dark High Contrast",
158    ),
159    ("catppuccin-latte", "Catppuccin-inspired Latte"),
160    ("catppuccin-mocha", "Catppuccin-inspired Mocha"),
161    ("one-light", "One Light-inspired"),
162    ("one-dark-pro", "One Dark Pro-inspired"),
163    ("solarized-light", "Solarized-inspired Light"),
164    ("solarized-dark", "Solarized-inspired Dark"),
165    ("gruvbox-light", "Gruvbox-inspired Light"),
166    ("gruvbox-dark", "Gruvbox-inspired Dark"),
167];
168
169/// A theme's name for people: a built-in theme's label, else its id.
170pub fn theme_label(name: &str) -> String {
171    BUILT_IN_LABELS
172        .iter()
173        .find(|(id, _)| *id == name)
174        .map_or_else(|| name.to_string(), |(_, label)| (*label).to_string())
175}
176
177/// The built-in colour scales usable as an accent.
178pub const BUILT_IN_ACCENTS: &[&str] = &["gold", "blue", "green", "amber", "red"];
179
180/// The default kit's components (`docs/kit.md`), one file each, layered
181/// into `pop-dark` (and so into every theme extending it): one entry per
182/// `themes/kit/<component>.tokens.yaml`, compiled to JSON by `build.rs`.
183pub(crate) const KIT_FILES: &[(&str, &str)] = include!(concat!(env!("OUT_DIR"), "/kit_files.rs"));
184
185/// A shipped token file, `themes/<name>.tokens.yaml`, as `build.rs`
186/// compiled it to JSON.
187macro_rules! shipped {
188    ($name:literal) => {
189        include_str!(concat!(env!("OUT_DIR"), "/themes/", $name, ".tokens.json"))
190    };
191}
192
193const BUILT_IN_FILES: &[(&str, &str)] = &[
194    ("pop-dark", shipped!("pop-dark")),
195    ("pop-light", shipped!("pop-light")),
196    ("pop-high-contrast", shipped!("pop-high-contrast")),
197    ("github-light", shipped!("github-light")),
198    ("github-dark", shipped!("github-dark")),
199    (
200        "github-light-high-contrast",
201        shipped!("github-light-high-contrast"),
202    ),
203    (
204        "github-dark-high-contrast",
205        shipped!("github-dark-high-contrast"),
206    ),
207    ("catppuccin-latte", shipped!("catppuccin-latte")),
208    ("catppuccin-mocha", shipped!("catppuccin-mocha")),
209    ("one-light", shipped!("one-light")),
210    ("one-dark-pro", shipped!("one-dark-pro")),
211    ("solarized-light", shipped!("solarized-light")),
212    ("solarized-dark", shipped!("solarized-dark")),
213    ("gruvbox-light", shipped!("gruvbox-light")),
214    ("gruvbox-dark", shipped!("gruvbox-dark")),
215];
216
217/// The scale an accent generated from a seed colour is written to
218/// ([`ThemeSpec::accent_color`]): `custom.1` to `custom.12` and
219/// `custom.contrast`, replacing a scale of that name.
220pub const SEED_SCALE: &str = "custom";
221
222/// The scale steps an accent re-aliases from, and what they become.
223const ACCENT_ROLES: &[(&str, &str)] = &[
224    ("accent.default", "9"),
225    ("accent.hover", "10"),
226    ("accent.active", "8"),
227    ("accent.subtle", "3"),
228    ("text.on-accent", "contrast"),
229    ("selection", "5"),
230];
231
232/// How much room the interface takes: an overlay of space and size tokens
233/// only.
234#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
235pub enum Density {
236    /// The values the base themes carry.
237    #[default]
238    Comfortable,
239    /// Tighter spacing and smaller controls.
240    Compact,
241}
242
243impl Density {
244    pub const ALL: [Density; 2] = [Density::Comfortable, Density::Compact];
245
246    pub fn name(self) -> &'static str {
247        match self {
248            Density::Comfortable => "comfortable",
249            Density::Compact => "compact",
250        }
251    }
252
253    /// The built-in overlay file of this density.
254    pub fn built_in_file(self) -> TokenFile {
255        let text = match self {
256            Density::Comfortable => shipped!("density-comfortable"),
257            Density::Compact => shipped!("density-compact"),
258        };
259        TokenFile::parse(&format!("density-{}", self.name()), text)
260            .expect("built-in density files parse")
261    }
262}
263
264impl fmt::Display for Density {
265    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
266        f.write_str(self.name())
267    }
268}
269
270impl FromStr for Density {
271    type Err = String;
272
273    fn from_str(s: &str) -> Result<Self, Self::Err> {
274        Density::ALL
275            .into_iter()
276            .find(|d| d.name() == s)
277            .ok_or_else(|| format!("`{s}` is not a density (comfortable, compact)"))
278    }
279}
280
281/// Which theme, if any, is the other variant (light or dark) of a spec's
282/// base theme: installed with it, so that egui's light or dark mode
283/// (the system's, or the user's choice) switches between them without
284/// installing anything again.
285#[derive(Clone, Debug, Default, PartialEq, Eq)]
286#[non_exhaustive]
287pub enum Counterpart {
288    /// The one the token files name ([`VARIANT_OF_EXTENSION`]); none
289    /// when they name none.
290    #[default]
291    Auto,
292    /// This theme, whatever the files say.
293    Theme(String),
294    /// None: the base theme alone, in its own mode whatever is asked.
295    None,
296}
297
298/// What to resolve: a base theme (mode and contrast), a density, an accent,
299/// reduced motion and the user's own overrides, composed in that order.
300/// The base theme's counterpart ([`Counterpart`]), when it has one, is
301/// resolved with the same density, accent, reduced motion and overrides
302/// ([`Themes::resolve_counterpart`]), or with overrides of its own
303/// ([`ThemeSpec::counterpart_overrides`]).
304///
305/// ```
306/// use egui_pop_tokens::{Density, ThemeSpec, Themes};
307///
308/// let spec = ThemeSpec::new("pop-light").density(Density::Compact).accent("blue");
309/// let tokens = Themes::default().resolve(&spec);
310/// assert!(tokens.problems().is_empty());
311/// assert_eq!(tokens.dimension("space.m"), Some(4.0));
312/// ```
313#[derive(Clone, Debug, PartialEq)]
314#[non_exhaustive]
315pub struct ThemeSpec {
316    /// The base theme's name (`pop-dark`, `pop-light`, ...).
317    pub base: String,
318    pub density: Density,
319    /// A colour scale whose steps become the accent roles; `None` keeps
320    /// the base theme's accent.
321    pub accent: Option<String>,
322    /// Sets `motion.duration` to zero.
323    pub reduced_motion: bool,
324    /// Raw DTCG values by token path, applied last; values may be aliases.
325    pub overrides: BTreeMap<String, Json>,
326    /// The other variant of the base theme, light or dark.
327    pub counterpart: Counterpart,
328    /// The counterpart's own overrides, in place of `overrides`: a pair
329    /// whose two variants are edited apart (the theme editor's). `None`:
330    /// `overrides` apply to both.
331    pub counterpart_overrides: Option<BTreeMap<String, Json>>,
332    /// The user's text size: a factor of the size scale (`font.size.*`),
333    /// one of [`TEXT_SIZES`]; 1 keeps the theme's sizes
334    /// ([`ThemeSpec::text_size`]).
335    pub text_size: f32,
336    /// A family the user puts first in `font.family.ui`, before the
337    /// theme's own (which stay its fallbacks).
338    pub font_ui: Option<String>,
339    /// A family the user puts first in `font.family.mono`.
340    pub font_mono: Option<String>,
341    /// The user's choice over the theme's scroll bars
342    /// ([`ThemeSpec::scroll_bars`]).
343    pub scroll_bars: ScrollBars,
344}
345
346/// What the user asks of the scroll bars, over what the theme's
347/// `scroll-bar` says (`ThemeSpec::scroll_bars`, the
348/// `appearance.scroll_bars` setting).
349#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
350pub enum ScrollBars {
351    /// What the theme says.
352    #[default]
353    Auto,
354    /// Full bars at rest, beside the content so that they cover none of it,
355    /// with a track even where the theme has none.
356    Always,
357    /// Nothing at rest: thin under the pointer, wide over the bar, over the
358    /// content.
359    Hover,
360}
361
362impl ScrollBars {
363    /// The setting's choices, in order.
364    pub const CHOICES: [&'static str; 3] = ["auto", "always", "hover"];
365
366    pub fn as_str(self) -> &'static str {
367        match self {
368            ScrollBars::Auto => "auto",
369            ScrollBars::Always => "always",
370            ScrollBars::Hover => "hover",
371        }
372    }
373
374    pub fn parse(s: &str) -> Option<ScrollBars> {
375        [ScrollBars::Auto, ScrollBars::Always, ScrollBars::Hover]
376            .into_iter()
377            .find(|c| c.as_str() == s)
378    }
379}
380
381/// The text sizes a user chooses from, as factors of a theme's size
382/// scale: few steps, so the font atlas holds few sizes.
383pub const TEXT_SIZES: [f32; 7] = [0.85, 1.0, 1.15, 1.3, 1.5, 1.75, 2.0];
384
385/// The step of [`TEXT_SIZES`] nearest to a factor.
386pub fn text_size_step(factor: f32) -> f32 {
387    TEXT_SIZES
388        .iter()
389        .copied()
390        .min_by(|a, b| (a - factor).abs().total_cmp(&(b - factor).abs()))
391        .unwrap_or(1.0)
392}
393
394/// The tokens of the size scale a text size multiplies.
395const SIZE_SCALE: [&str; 5] = [
396    "font.size.xs",
397    "font.size.s",
398    "font.size.m",
399    "font.size.l",
400    "font.size.xl",
401];
402
403impl Default for ThemeSpec {
404    fn default() -> Self {
405        ThemeSpec::new(FALLBACK_THEME)
406    }
407}
408
409impl ThemeSpec {
410    pub fn new(base: impl Into<String>) -> ThemeSpec {
411        ThemeSpec {
412            base: base.into(),
413            density: Density::default(),
414            accent: None,
415            reduced_motion: false,
416            overrides: BTreeMap::new(),
417            counterpart: Counterpart::Auto,
418            counterpart_overrides: None,
419            text_size: 1.0,
420            font_ui: None,
421            font_mono: None,
422            scroll_bars: ScrollBars::Auto,
423        }
424    }
425
426    /// A pair of themes, a dark one and a light one: `dark` is the base
427    /// (shown when nothing asks for light), `light` its counterpart.
428    ///
429    /// ```
430    /// use egui_pop_tokens::{ThemeSpec, Themes};
431    ///
432    /// let spec = ThemeSpec::pair("github-dark", "pop-light");
433    /// let light = Themes::default().resolve_counterpart(&spec).unwrap();
434    /// assert_eq!(light.spec().base, "pop-light");
435    /// assert!(!light.is_dark());
436    /// ```
437    pub fn pair(dark: impl Into<String>, light: impl Into<String>) -> ThemeSpec {
438        ThemeSpec::new(dark).counterpart(light)
439    }
440
441    /// Names the base theme's counterpart, whatever the token files say.
442    pub fn counterpart(mut self, theme: impl Into<String>) -> Self {
443        self.counterpart = Counterpart::Theme(theme.into());
444        self
445    }
446
447    /// The base theme alone, without its counterpart: its mode is forced.
448    pub fn alone(mut self) -> Self {
449        self.counterpart = Counterpart::None;
450        self
451    }
452
453    /// The same spec over another base theme, alone, with the same
454    /// overrides.
455    pub fn variant(&self, base: impl Into<String>) -> ThemeSpec {
456        let mut spec = self.clone();
457        spec.base = base.into();
458        spec.counterpart = Counterpart::None;
459        spec.counterpart_overrides = None;
460        spec
461    }
462
463    /// What the counterpart `other` is resolved from: the same spec over
464    /// it, alone, with the counterpart's own overrides when the spec
465    /// gives them ([`ThemeSpec::counterpart_overrides`]).
466    ///
467    /// ```
468    /// use egui_pop_tokens::{Color, ThemeSpec, Themes};
469    /// use serde_json::json;
470    ///
471    /// let spec = ThemeSpec::new("pop-dark")
472    ///     .override_token("danger", json!("#ff0000"))
473    ///     .counterpart_override("danger", json!("#00ff00"));
474    /// let light = Themes::default().resolve_counterpart(&spec).unwrap();
475    /// assert_eq!(light.color("danger"), Color::from_hex("#00ff00"));
476    /// let dark = Themes::default().resolve(&spec);
477    /// assert_eq!(dark.color("danger"), Color::from_hex("#ff0000"));
478    /// ```
479    pub fn counterpart_variant(&self, other: impl Into<String>) -> ThemeSpec {
480        let mut spec = self.variant(other);
481        if let Some(own) = &self.counterpart_overrides {
482            spec.overrides = own.clone();
483        }
484        spec
485    }
486
487    pub fn density(mut self, density: Density) -> Self {
488        self.density = density;
489        self
490    }
491
492    /// The accent: a colour scale of the theme by name (`"blue"`), or a
493    /// seed colour (`"#3a7bd5"`) the scale is generated from
494    /// ([`ThemeSpec::accent_color`]).
495    pub fn accent(mut self, scale: impl Into<String>) -> Self {
496        self.accent = Some(scale.into());
497        self
498    }
499
500    /// An accent generated from a seed colour: the [`SEED_SCALE`] scale
501    /// ([`palette::Ramp`](crate::palette::Ramp)), for the theme's light
502    /// or dark scheme, the seed clamped to what gives a usable ramp. A
503    /// counterpart gets the ramp of its own scheme from the same seed.
504    ///
505    /// ```
506    /// use egui_pop_tokens::{Color, ThemeSpec, Themes, contrast};
507    ///
508    /// let spec = ThemeSpec::new("pop-light").accent_color(Color::from_hex("#c0392b").unwrap());
509    /// assert_eq!(spec.accent.as_deref(), Some("#c0392b"));
510    /// let tokens = Themes::default().resolve(&spec);
511    /// assert_eq!(tokens.get("accent.default").unwrap().alias.as_deref(), Some("custom.9"));
512    /// assert!(contrast::check(&tokens, contrast::Level::Normal).is_empty());
513    /// ```
514    pub fn accent_color(mut self, seed: Color) -> Self {
515        self.accent = Some(Color { a: 1.0, ..seed }.to_hex());
516        self
517    }
518
519    /// The accent's seed colour, when the accent is one (`#rrggbb`).
520    pub fn accent_seed(&self) -> Option<Color> {
521        self.accent
522            .as_deref()
523            .filter(|a| a.starts_with('#'))
524            .and_then(Color::from_hex)
525    }
526
527    pub fn reduced_motion(mut self, reduced: bool) -> Self {
528        self.reduced_motion = reduced;
529        self
530    }
531
532    /// The user's text size, a factor of the theme's size scale, rounded
533    /// to the nearest of [`TEXT_SIZES`]: each step of `font.size.*` is
534    /// multiplied and rounded to half a point, and every text style and
535    /// component token aliasing a step follows. Only the text grows:
536    /// spacing does not (the interface zoom scales everything), and
537    /// `size.control.height` grows to at least 1.6 times the body text,
538    /// so a larger label is not clipped.
539    ///
540    /// ```
541    /// use egui_pop_tokens::{ThemeSpec, Themes};
542    ///
543    /// let themes = Themes::default();
544    /// let base = themes.resolve(&ThemeSpec::new("pop-dark"));
545    /// let large = themes.resolve(&ThemeSpec::new("pop-dark").text_size(1.3));
546    /// assert_eq!(base.dimension("font.size.m"), Some(13.0));
547    /// assert_eq!(large.dimension("font.size.m"), Some(17.0));
548    /// assert_eq!(large.dimension("font.text-style.body"), Some(17.0));
549    /// assert_eq!(large.dimension("space.m"), base.dimension("space.m"));
550    /// ```
551    pub fn text_size(mut self, factor: f32) -> Self {
552        self.text_size = text_size_step(factor);
553        self
554    }
555
556    /// The user's choice over the theme's scroll bars: `scroll-bar.visibility`
557    /// and `placement` take it when the theme resolves, for the theme and its
558    /// counterpart. `Auto` leaves the theme's.
559    ///
560    /// ```
561    /// use egui_pop_tokens::{ScrollBars, ThemeSpec, Themes, Value};
562    ///
563    /// let themes = Themes::default();
564    /// let full = themes.resolve(&ThemeSpec::new("pop-dark").scroll_bars(ScrollBars::Always));
565    /// let visibility = &full.get("scroll-bar.visibility").unwrap().value;
566    /// assert_eq!(visibility, &Value::Other("always".into()));
567    /// ```
568    pub fn scroll_bars(mut self, choice: ScrollBars) -> Self {
569        self.scroll_bars = choice;
570        self
571    }
572
573    /// A family drawn first for interface text (`font.family.ui`), the
574    /// theme's own families after it; `None` keeps the theme's.
575    pub fn font_ui(mut self, family: Option<String>) -> Self {
576        self.font_ui = family.filter(|f| !f.trim().is_empty());
577        self
578    }
579
580    /// A family drawn first for numbers and code (`font.family.mono`).
581    pub fn font_mono(mut self, family: Option<String>) -> Self {
582        self.font_mono = family.filter(|f| !f.trim().is_empty());
583        self
584    }
585
586    /// Overrides one token with a raw DTCG value (`json!("#3080ff")`,
587    /// `json!("{blue.9}")`).
588    pub fn override_token(mut self, path: impl Into<String>, value: Json) -> Self {
589        self.overrides.insert(path.into(), value);
590        self
591    }
592
593    /// Overrides one token of the counterpart only: from the first one,
594    /// the counterpart has overrides of its own
595    /// ([`ThemeSpec::counterpart_overrides`]), starting empty.
596    pub fn counterpart_override(mut self, path: impl Into<String>, value: Json) -> Self {
597        self.counterpart_overrides
598            .get_or_insert_with(BTreeMap::new)
599            .insert(path.into(), value);
600        self
601    }
602
603    /// A short label: `pop-dark · compact · blue`.
604    pub fn label(&self) -> String {
605        let mut parts = vec![self.base.clone(), self.density.name().to_string()];
606        if let Some(accent) = &self.accent {
607            parts.push(accent.clone());
608        }
609        if self.reduced_motion {
610            parts.push("reduced motion".into());
611        }
612        if (self.text_size - 1.0).abs() > f32::EPSILON {
613            parts.push(format!("text {}%", (self.text_size * 100.0).round()));
614        }
615        if self.scroll_bars != ScrollBars::Auto {
616            parts.push(format!("scroll bars {}", self.scroll_bars.as_str()));
617        }
618        for f in [&self.font_ui, &self.font_mono].into_iter().flatten() {
619            parts.push(f.clone());
620        }
621        if !self.overrides.is_empty() {
622            parts.push(format!("{} overrides", self.overrides.len()));
623        }
624        parts.join(" · ")
625    }
626}
627
628/// A resolved token.
629#[derive(Clone, Debug, PartialEq)]
630pub struct Token {
631    pub path: String,
632    /// The DTCG type.
633    pub ty: String,
634    pub value: Value,
635    /// The path this token directly aliases, if it is an alias.
636    pub alias: Option<String>,
637    pub description: Option<String>,
638    /// `$extensions`, kept as written.
639    pub extensions: Option<Json>,
640    /// Whether the value came from the fallback theme after a problem.
641    pub fallback: bool,
642}
643
644impl Token {
645    /// The token's tier: from the contract, else the palette.
646    pub fn tier(&self) -> Tier {
647        required(&self.path).map_or(Tier::Reference, |r| r.tier)
648    }
649}
650
651/// A theme ready to use: every contract token has a value of its type.
652#[derive(Clone, Debug, PartialEq)]
653pub struct ResolvedTokens {
654    spec: ThemeSpec,
655    tokens: BTreeMap<String, Token>,
656    problems: Vec<Error>,
657}
658
659impl ResolvedTokens {
660    pub fn spec(&self) -> &ThemeSpec {
661        &self.spec
662    }
663
664    /// What was wrong, in the order met; empty for a clean theme.
665    pub fn problems(&self) -> &[Error] {
666        &self.problems
667    }
668
669    pub fn get(&self, path: &str) -> Option<&Token> {
670        self.tokens.get(path)
671    }
672
673    pub fn value(&self, path: &str) -> Option<&Value> {
674        self.tokens.get(path).map(|t| &t.value)
675    }
676
677    pub fn color(&self, path: &str) -> Option<Color> {
678        match self.value(path)? {
679            Value::Color(c) => Some(*c),
680            _ => None,
681        }
682    }
683
684    /// A dimension (or a number) in logical pixels.
685    pub fn dimension(&self, path: &str) -> Option<f32> {
686        match self.value(path)? {
687            Value::Dimension(d) | Value::Number(d) => Some(*d),
688            _ => None,
689        }
690    }
691
692    /// A duration in milliseconds.
693    pub fn duration_ms(&self, path: &str) -> Option<f32> {
694        match self.value(path)? {
695            Value::Duration(ms) => Some(*ms),
696            _ => None,
697        }
698    }
699
700    pub fn font_family(&self, path: &str) -> Option<&[String]> {
701        match self.value(path)? {
702            Value::FontFamily(f) => Some(f),
703            _ => None,
704        }
705    }
706
707    /// Every token, by path.
708    pub fn iter(&self) -> impl Iterator<Item = &Token> {
709        self.tokens.values()
710    }
711
712    pub fn len(&self) -> usize {
713        self.tokens.len()
714    }
715
716    pub fn is_empty(&self) -> bool {
717        self.tokens.is_empty()
718    }
719
720    /// Whether the theme is a dark one: its panels are dark.
721    pub fn is_dark(&self) -> bool {
722        self.color("surface.panel").is_some_and(Color::is_dark)
723    }
724
725    /// The theme as one DTCG file: every token with its resolved value,
726    /// nothing extended, no alias left.
727    pub fn to_dtcg(&self) -> Json {
728        let mut root = Map::new();
729        root.insert("$description".into(), json!(self.spec.label()));
730        for token in self.tokens.values() {
731            let mut node = &mut root;
732            let parts: Vec<&str> = token.path.split('.').collect();
733            let (leaf, groups) = parts.split_last().expect("paths are not empty");
734            for part in groups {
735                node = node
736                    .entry(part.to_string())
737                    .or_insert_with(|| json!({}))
738                    .as_object_mut()
739                    .expect("groups are objects");
740            }
741            let mut entry = Map::new();
742            entry.insert("$type".into(), json!(token.ty));
743            entry.insert("$value".into(), token.value.to_json());
744            if let Some(d) = &token.description {
745                entry.insert("$description".into(), json!(d));
746            }
747            // The alpha modifier is in the value already: kept, it would
748            // apply twice when the file is read back.
749            if let Some(e) = without_alpha(token.extensions.as_ref()) {
750                entry.insert("$extensions".into(), e);
751            }
752            node.insert(leaf.to_string(), Json::Object(entry));
753        }
754        Json::Object(root)
755    }
756}
757
758/// The themes known: the built-in ones and any added.
759#[derive(Clone, Debug)]
760pub struct Themes {
761    themes: BTreeMap<String, TokenFile>,
762    densities: BTreeMap<Density, TokenFile>,
763}
764
765impl Default for Themes {
766    /// The built-in themes and densities.
767    fn default() -> Self {
768        let mut themes = Themes {
769            themes: BTreeMap::new(),
770            densities: Density::ALL
771                .into_iter()
772                .map(|d| (d, d.built_in_file()))
773                .collect(),
774        };
775        for (name, text) in BUILT_IN_FILES {
776            let mut file = TokenFile::parse(name, text).expect("built-in themes parse");
777            if *name == FALLBACK_THEME {
778                // The default kit, read as any kit folder is; its tokens
779                // are `pop-dark`'s own.
780                let kit = crate::kit::built_in(KIT_FILES);
781                for p in kit.problems() {
782                    if matches!(
783                        p,
784                        crate::kit::Problem::Tokens(_) | crate::kit::Problem::Repeated { .. }
785                    ) {
786                        panic!("the default kit: {p}");
787                    }
788                }
789                for (path, token) in kit.theme.tokens {
790                    let clash = file.tokens.insert(path.clone(), token);
791                    assert!(clash.is_none(), "the default kit repeats {path}");
792                }
793            }
794            themes.add(file);
795        }
796        themes
797    }
798}
799
800impl Themes {
801    /// Adds a theme, or replaces the one of the same name (returned).
802    pub fn add(&mut self, theme: TokenFile) -> Option<TokenFile> {
803        self.themes.insert(theme.name.clone(), theme)
804    }
805
806    /// Reads a theme file (YAML or JSON, `TokenFile::parse`) and adds it
807    /// under `name`, loaded over its base theme ([`Themes::check_file`]).
808    /// Only a file that cannot be read at all is an error; what was read
809    /// otherwise than written comes back as warnings.
810    ///
811    /// A file carrying its counterpart ([`COUNTERPART_EXTENSION`]) adds
812    /// it too, under its own name and through the same rule; a
813    /// counterpart that cannot be read is a warning, the file's own
814    /// variant added alone.
815    pub fn add_text(&mut self, name: &str, text: &str) -> Result<Vec<Warning>, Error> {
816        let (file, mut warnings) = self.check_file(TokenFile::parse(name, text)?);
817        warnings.extend(self.add_counterpart_of(&file));
818        self.add(file);
819        Ok(warnings)
820    }
821
822    /// Adds the counterpart a file carries, if any.
823    fn add_counterpart_of(&mut self, file: &TokenFile) -> Vec<Warning> {
824        match file.counterpart_file() {
825            None => Vec::new(),
826            Some(Ok(other)) => {
827                let (other, warnings) = self.check_file(other);
828                self.add(other);
829                warnings
830            }
831            Some(Err(e)) => vec![Warning::Invalid {
832                path: format!("$extensions.{COUNTERPART_EXTENSION}"),
833                reason: e.to_string(),
834            }],
835        }
836    }
837
838    /// Reads a theme file from disk (a user's theme) and adds it under
839    /// `name`, as [`Themes::add_text`] does. Its YAML goes through the
840    /// default cache ([`crate::cache`]): read again unchanged, it is not
841    /// parsed again, and the loading rule still runs, so its warnings
842    /// are the same on a hit.
843    pub fn add_path(&mut self, name: &str, path: &Path) -> Result<Vec<Warning>, Error> {
844        self.add_path_with(name, path, &crate::cache::default())
845    }
846
847    /// [`Themes::add_path`] through a given cache. An entry that cannot
848    /// be written is a [`Warning::NotCached`]: the file is read all the
849    /// same.
850    pub fn add_path_with(
851        &mut self,
852        name: &str,
853        path: &Path,
854        cache: &Cache,
855    ) -> Result<Vec<Warning>, Error> {
856        let (file, unwritten) = TokenFile::read(name, path, cache);
857        let (file, mut warnings) = self.check_file(file?);
858        warnings.extend(self.add_counterpart_of(&file));
859        self.add(file);
860        if let Some(e) = unwritten {
861            warnings.push(Warning::NotCached {
862                file: path.display().to_string(),
863                reason: e.to_string(),
864            });
865        }
866        Ok(warnings)
867    }
868
869    /// Loads a theme file over its base theme (its `$extends`, else
870    /// [`FALLBACK_THEME`]), the rule every theme file goes through: the
871    /// file is brought to the current contract ([`TokenFile::upgrade`]),
872    /// a seed that cannot be read ([`crate::palette::SEEDS_EXTENSION`])
873    /// is left out, then a token whose value does not load (an unreadable value, an
874    /// alias to nothing or in a cycle, another type than the base's or
875    /// the contract's) is left out, so the base theme's value stays. A
876    /// token the base does not have is kept as the file's own (a
877    /// palette, an extension's component); under a group of the
878    /// contract, with a term no token of the base uses, it is reported
879    /// as a likely typo. Nothing here fails: each such thing is a
880    /// [`Warning`]. A base not known yet leaves the tokens unchecked.
881    pub fn check_file(&self, mut file: TokenFile) -> (TokenFile, Vec<Warning>) {
882        let mut warnings = file.upgrade();
883        warnings.extend(file.seeds().1);
884        let base = file
885            .extends
886            .clone()
887            .unwrap_or_else(|| FALLBACK_THEME.to_string());
888        if base != file.name && !self.themes.contains_key(&base) {
889            warnings.push(Warning::Unchecked { base });
890            return (file, warnings);
891        }
892        let base_raw = self.flatten(&base, &mut Vec::new());
893        let groups: BTreeSet<&str> = contract()
894            .filter_map(|r| r.path.split('.').next())
895            .collect();
896        let terms: BTreeSet<&str> = base_raw
897            .keys()
898            .filter_map(|p| p.rsplit('.').next())
899            .collect();
900        for path in file.tokens.keys() {
901            if base_raw.contains_key(path) || required(path).is_some() {
902                continue;
903            }
904            let group = path.split('.').next().unwrap_or_default();
905            let term = path.rsplit('.').next().unwrap_or_default();
906            if groups.contains(group) && !terms.contains(term) {
907                warnings.push(Warning::Unknown {
908                    path: path.clone(),
909                    base: base.clone(),
910                    kept: true,
911                });
912            }
913        }
914        // The file resolved as it would be, without a density overlay
915        // hiding its own space and size tokens: what breaks is left out,
916        // until nothing does (leaving a token out can break another one
917        // aliasing it).
918        let mut trial = self.clone();
919        trial.densities.clear();
920        let base_types: BTreeMap<String, String> = trial
921            .resolve_without_fallback(&ThemeSpec::new(base.clone()))
922            .tokens
923            .into_iter()
924            .map(|(path, t)| (path, t.ty))
925            .collect();
926        loop {
927            trial.add(file.clone());
928            let r = trial.resolve_without_fallback(&ThemeSpec::new(file.name.clone()));
929            let mut bad: BTreeMap<String, String> = BTreeMap::new();
930            for p in &r.problems {
931                if matches!(p, Error::Missing { .. } | Error::UnknownOverride { .. }) {
932                    continue;
933                }
934                let own: Vec<&str> = match p {
935                    Error::AliasCycle { chain } => chain.iter().map(String::as_str).collect(),
936                    _ => p.path().into_iter().collect(),
937                };
938                for path in own {
939                    if file.tokens.contains_key(path) {
940                        bad.entry(path.to_string()).or_insert_with(|| p.to_string());
941                    }
942                }
943            }
944            for (path, t) in &r.tokens {
945                if let Some(ty) = base_types.get(path)
946                    && *ty != t.ty
947                    && file.tokens.contains_key(path)
948                {
949                    bad.entry(path.clone())
950                        .or_insert_with(|| format!("a {}, where `{base}` has a {ty}", t.ty));
951                }
952            }
953            if bad.is_empty() {
954                break;
955            }
956            for (path, reason) in bad {
957                file.tokens.remove(&path);
958                warnings.push(Warning::Invalid { path, reason });
959            }
960        }
961        (file, warnings)
962    }
963
964    /// Replaces a density's overlay.
965    pub fn set_density(&mut self, density: Density, overlay: TokenFile) {
966        self.densities.insert(density, overlay);
967    }
968
969    pub fn get(&self, name: &str) -> Option<&TokenFile> {
970        self.themes.get(name)
971    }
972
973    /// The other variant of a theme, as the token files say
974    /// ([`VARIANT_OF_EXTENSION`]): the theme its own file names, else the
975    /// first theme (by name) naming it. Only a known theme other than
976    /// itself counts.
977    pub fn counterpart_of(&self, name: &str) -> Option<&str> {
978        let named = |file: &TokenFile| {
979            file.extensions
980                .as_ref()
981                .and_then(|e| e.get(VARIANT_OF_EXTENSION))
982                .and_then(Json::as_str)
983                .map(String::from)
984        };
985        if let Some(other) = self.themes.get(name).and_then(named)
986            && other != name
987            && let Some((key, _)) = self.themes.get_key_value(&other)
988        {
989            return Some(key);
990        }
991        self.themes
992            .iter()
993            .find(|(n, file)| n.as_str() != name && named(file).as_deref() == Some(name))
994            .map(|(n, _)| n.as_str())
995    }
996
997    /// The counterpart a spec asks for ([`ThemeSpec::counterpart`]): a
998    /// known theme other than the base, or none.
999    pub fn counterpart(&self, spec: &ThemeSpec) -> Option<String> {
1000        match &spec.counterpart {
1001            Counterpart::Auto => self.counterpart_of(&spec.base).map(String::from),
1002            Counterpart::Theme(t) => {
1003                (*t != spec.base && self.themes.contains_key(t)).then(|| t.clone())
1004            }
1005            Counterpart::None => None,
1006        }
1007    }
1008
1009    /// Resolves a spec's counterpart, if it has one
1010    /// ([`Themes::counterpart`]), with the spec's density, accent,
1011    /// reduced motion and overrides, or the counterpart's own overrides
1012    /// ([`ThemeSpec::counterpart_variant`]).
1013    pub fn resolve_counterpart(&self, spec: &ThemeSpec) -> Option<ResolvedTokens> {
1014        self.counterpart(spec)
1015            .map(|other| self.resolve(&spec.counterpart_variant(other)))
1016    }
1017
1018    /// The names of the themes known, sorted.
1019    pub fn names(&self) -> impl Iterator<Item = &str> {
1020        self.themes.keys().map(String::as_str)
1021    }
1022
1023    /// The theme's tokens with everything it extends, the theme's own
1024    /// winning. An unknown theme falls back to [`FALLBACK_THEME`].
1025    pub(crate) fn flatten(
1026        &self,
1027        name: &str,
1028        problems: &mut Vec<Error>,
1029    ) -> BTreeMap<String, RawToken> {
1030        let mut chain: Vec<String> = Vec::new();
1031        let mut at = Some(name.to_string());
1032        while let Some(n) = at {
1033            if chain.contains(&n) {
1034                chain.push(n);
1035                problems.push(Error::ExtendsCycle {
1036                    chain: chain.clone(),
1037                });
1038                chain.pop();
1039                break;
1040            }
1041            let Some(theme) = self.themes.get(&n) else {
1042                problems.push(Error::UnknownTheme { name: n });
1043                if !chain.iter().any(|c| c == FALLBACK_THEME) {
1044                    chain.push(FALLBACK_THEME.to_string());
1045                }
1046                break;
1047            };
1048            chain.push(n);
1049            at = theme.extends.clone();
1050        }
1051        let mut tokens = BTreeMap::new();
1052        for n in chain.iter().rev() {
1053            if let Some(theme) = self.themes.get(n) {
1054                // The scales the file gives by their seed, under its own
1055                // tokens: a step it also gives keeps its value.
1056                let (seeds, _) = theme.seeds();
1057                if !seeds.is_empty() {
1058                    let generated = seeded_scales(&tokens, &theme.tokens, &seeds);
1059                    layer(&mut tokens, &generated);
1060                }
1061                layer(&mut tokens, &theme.tokens);
1062            }
1063        }
1064        tokens
1065    }
1066
1067    /// The colour scales of a base theme usable as an accent.
1068    pub fn accents(&self, base: &str) -> Vec<String> {
1069        let raw = self.flatten(base, &mut Vec::new());
1070        let mut scales: Vec<String> = raw
1071            .keys()
1072            .filter_map(|p| p.strip_suffix(".contrast"))
1073            .filter(|s| is_accent_scale(&raw, s))
1074            .map(String::from)
1075            .collect();
1076        scales.sort_by_key(|s| {
1077            BUILT_IN_ACCENTS
1078                .iter()
1079                .position(|b| b == s)
1080                .unwrap_or(usize::MAX)
1081        });
1082        scales
1083    }
1084
1085    /// Resolves a spec. Never fails: problems are reported in the result,
1086    /// and every contract token that has one takes the built-in
1087    /// `pop-dark` value.
1088    pub fn resolve(&self, spec: &ThemeSpec) -> ResolvedTokens {
1089        let mut resolved = self.resolve_without_fallback(spec);
1090        let missing: Vec<&str> = contract()
1091            .filter(|r| resolved.tokens.get(r.path).is_none_or(|t| t.ty != r.ty))
1092            .map(|r| r.path)
1093            .collect();
1094        if missing.is_empty() {
1095            return resolved;
1096        }
1097        let mut fallback_spec = spec.clone();
1098        fallback_spec.base = FALLBACK_THEME.to_string();
1099        fallback_spec.overrides.clear();
1100        let fallback = Themes::default().resolve_without_fallback(&fallback_spec);
1101        for path in missing {
1102            if let Some(t) = fallback.tokens.get(path) {
1103                let mut t = t.clone();
1104                t.fallback = true;
1105                resolved.tokens.insert(path.to_string(), t);
1106            }
1107        }
1108        resolved
1109    }
1110
1111    /// Resolves a spec without filling the contract's gaps.
1112    fn resolve_without_fallback(&self, spec: &ThemeSpec) -> ResolvedTokens {
1113        let mut problems = Vec::new();
1114        let mut raw = self.flatten(&spec.base, &mut problems);
1115        if let Some(density) = self.densities.get(&spec.density) {
1116            layer(&mut raw, &density.tokens);
1117        }
1118        if let Some(asked) = &spec.accent {
1119            let scale = match spec.accent_seed() {
1120                Some(seed) => {
1121                    let color = |path: &str| match resolve_one(&raw, path) {
1122                        Ok((_, Value::Color(c))) => Some(c),
1123                        _ => None,
1124                    };
1125                    let scheme = color("surface.panel").map_or(Scheme::Dark, Scheme::of_background);
1126                    let backdrop = Backdrop::from_tokens(color);
1127                    for (path, value) in Ramp::fitted(seed, scheme, &backdrop).tokens(SEED_SCALE) {
1128                        raw.insert(
1129                            path,
1130                            RawToken {
1131                                ty: Some("color".into()),
1132                                value,
1133                                description: Some(format!("Generated from {}.", seed.to_hex())),
1134                                extensions: None,
1135                            },
1136                        );
1137                    }
1138                    SEED_SCALE
1139                }
1140                None => asked.as_str(),
1141            };
1142            if is_accent_scale(&raw, scale) {
1143                for (role, step) in ACCENT_ROLES {
1144                    let entry = raw.entry(role.to_string()).or_insert_with(|| RawToken {
1145                        ty: Some("color".into()),
1146                        value: Json::Null,
1147                        description: None,
1148                        extensions: None,
1149                    });
1150                    entry.value = json!(format!("{{{scale}.{step}}}"));
1151                }
1152            } else {
1153                problems.push(Error::UnknownAccent {
1154                    name: asked.clone(),
1155                });
1156            }
1157        }
1158        if spec.reduced_motion {
1159            let entry = raw
1160                .entry("motion.duration".to_string())
1161                .or_insert_with(|| RawToken {
1162                    ty: Some("duration".into()),
1163                    value: Json::Null,
1164                    description: None,
1165                    extensions: None,
1166                });
1167            entry.value = json!({ "value": 0, "unit": "ms" });
1168        }
1169        inherit(&mut raw, &mut problems);
1170        for (path, value) in &spec.overrides {
1171            match raw.get_mut(path) {
1172                // An override is the value as wanted: the alpha modifier
1173                // of the value it replaces goes with it.
1174                Some(token) => {
1175                    token.value = value.clone();
1176                    token.extensions = without_alpha(token.extensions.as_ref());
1177                }
1178                None => problems.push(Error::UnknownOverride { path: path.clone() }),
1179            }
1180        }
1181        user_fonts(&mut raw, spec);
1182        text_size(&mut raw, spec.text_size);
1183        user_scroll_bars(&mut raw, spec.scroll_bars);
1184
1185        let mut tokens = BTreeMap::new();
1186        for (path, token) in &raw {
1187            match resolve_one(&raw, path) {
1188                Ok((ty, value)) => {
1189                    let contract = required(path);
1190                    if let Some(r) = contract.filter(|r| r.ty != ty) {
1191                        problems.push(Error::TypeMismatch {
1192                            path: path.clone(),
1193                            expected: r.ty.to_string(),
1194                            found: ty,
1195                        });
1196                        continue;
1197                    }
1198                    tokens.insert(
1199                        path.clone(),
1200                        Token {
1201                            path: path.clone(),
1202                            ty,
1203                            value,
1204                            alias: token.alias().map(String::from),
1205                            description: token.description.clone(),
1206                            extensions: token.extensions.clone(),
1207                            fallback: false,
1208                        },
1209                    );
1210                }
1211                // A broken token is reported once, not again for each
1212                // token aliasing it.
1213                Err(e) => {
1214                    if !problems.contains(&e) {
1215                        problems.push(e);
1216                    }
1217                }
1218            }
1219        }
1220        for r in contract() {
1221            if !raw.contains_key(r.path) {
1222                problems.push(Error::Missing {
1223                    path: r.path.to_string(),
1224                });
1225            }
1226        }
1227        ResolvedTokens {
1228            spec: spec.clone(),
1229            tokens,
1230            problems,
1231        }
1232    }
1233}
1234
1235/// Puts the user's families (`ThemeSpec::font_ui`, `font_mono`) first
1236/// in the theme's lists.
1237fn user_fonts(raw: &mut BTreeMap<String, RawToken>, spec: &ThemeSpec) {
1238    for (path, family) in [
1239        ("font.family.ui", &spec.font_ui),
1240        ("font.family.mono", &spec.font_mono),
1241    ] {
1242        let Some(family) = family else { continue };
1243        let theirs = match resolve_one(raw, path) {
1244            Ok((_, Value::FontFamily(list))) => list,
1245            _ => Vec::new(),
1246        };
1247        let mut list = vec![family.clone()];
1248        list.extend(theirs.into_iter().filter(|f| f != family));
1249        let entry = raw.entry(path.to_string()).or_insert_with(|| RawToken {
1250            ty: Some("fontFamily".into()),
1251            value: Json::Null,
1252            description: None,
1253            extensions: None,
1254        });
1255        entry.value = json!(list);
1256    }
1257}
1258
1259/// Writes the user's choice (`ThemeSpec::scroll_bars`) over the theme's
1260/// `scroll-bar`. It sets the placement too: a full bar over the content would
1261/// hide it, and egui always shows a bar beside the content. `Always` promises a
1262/// track, so a theme's transparent one gives way to the track's default.
1263fn user_scroll_bars(raw: &mut BTreeMap<String, RawToken>, choice: ScrollBars) {
1264    let (visibility, placement) = match choice {
1265        ScrollBars::Auto => return,
1266        ScrollBars::Always => ("always", "beside"),
1267        ScrollBars::Hover => ("hover", "over"),
1268    };
1269    for (path, value) in [
1270        ("scroll-bar.visibility", visibility),
1271        ("scroll-bar.placement", placement),
1272    ] {
1273        let entry = raw.entry(path.to_string()).or_insert_with(|| RawToken {
1274            ty: Some("string".into()),
1275            value: Json::Null,
1276            description: None,
1277            extensions: None,
1278        });
1279        entry.value = json!(value);
1280    }
1281    if choice == ScrollBars::Always
1282        && let Ok((_, Value::Color(track))) = resolve_one(raw, "scroll-bar.track-fill")
1283        && track.a == 0.0
1284        && let Some(token) = raw.get_mut("scroll-bar.track-fill")
1285    {
1286        token.value = json!("{surface.sunken}");
1287        token.extensions = without_alpha(token.extensions.as_ref());
1288    }
1289}
1290
1291/// Multiplies the size scale by the user's text size (each step rounded
1292/// to half a point), and grows the control height with the body text.
1293fn text_size(raw: &mut BTreeMap<String, RawToken>, factor: f32) {
1294    if (factor - 1.0).abs() <= f32::EPSILON || !factor.is_finite() || factor <= 0.0 {
1295        return;
1296    }
1297    for path in SIZE_SCALE {
1298        let Ok((_, Value::Dimension(size))) = resolve_one(raw, path) else {
1299            continue;
1300        };
1301        let scaled = (size * factor * 2.0).round() / 2.0;
1302        if let Some(token) = raw.get_mut(path) {
1303            token.value = json!({ "value": scaled, "unit": "px" });
1304        }
1305    }
1306    let body = match resolve_one(raw, "font.text-style.body") {
1307        Ok((_, Value::Dimension(b))) => b,
1308        _ => return,
1309    };
1310    if let Ok((_, Value::Dimension(height))) = resolve_one(raw, "size.control.height") {
1311        let wanted = (body * 1.6).ceil();
1312        if wanted > height
1313            && let Some(token) = raw.get_mut("size.control.height")
1314        {
1315            token.value = json!({ "value": wanted, "unit": "px" });
1316        }
1317    }
1318}
1319
1320/// The component term naming the component another is based on
1321/// (`command-button.based-on: "button"`, `docs/kit.md`).
1322pub const BASED_ON: &str = "based-on";
1323
1324/// The component a component is based on, as its tokens say
1325/// (`<component>.based-on`); `None` when it gives none, or no name.
1326pub(crate) fn base_of<'a>(raw: &'a BTreeMap<String, RawToken>, component: &str) -> Option<&'a str> {
1327    let token = raw.get(&format!("{component}.{BASED_ON}"))?;
1328    token
1329        .value
1330        .as_str()
1331        .filter(|_| alias_target(&token.value).is_none())
1332}
1333
1334/// Components based on another (`<component>.based-on`) receive every
1335/// token of their base they do not give themselves, as an alias of it
1336/// (`command-button.hover.fill: "{button.hover.fill}"`): states, tones,
1337/// component terms and the `shape`. Chains are followed, each base
1338/// completed before the components based on it. A cycle is a problem,
1339/// and its members keep their own tokens only; so is a base no token
1340/// names. Done once per resolution, before the overrides, so that an
1341/// override of the base reaches the components based on it.
1342fn inherit(raw: &mut BTreeMap<String, RawToken>, problems: &mut Vec<Error>) {
1343    let suffix = format!(".{BASED_ON}");
1344    let mut bases: BTreeMap<String, String> = BTreeMap::new();
1345    for (path, token) in raw.iter() {
1346        let Some(component) = path.strip_suffix(&suffix) else {
1347            continue;
1348        };
1349        if component.contains('.') {
1350            continue;
1351        }
1352        match base_of(raw, component) {
1353            Some(base) if !base.is_empty() => {
1354                bases.insert(component.to_string(), base.to_string());
1355            }
1356            _ => problems.push(Error::InvalidValue {
1357                path: path.clone(),
1358                ty: "string".into(),
1359                reason: format!("`{}` does not name a component", token.value),
1360            }),
1361        }
1362    }
1363    if bases.is_empty() {
1364        return;
1365    }
1366    // The members of cycles keep their own tokens.
1367    let mut cyclic: BTreeSet<String> = BTreeSet::new();
1368    for start in bases.keys() {
1369        let mut chain = vec![start.clone()];
1370        let mut at = start;
1371        while let Some(next) = bases.get(at) {
1372            if let Some(i) = chain.iter().position(|c| c == next) {
1373                let members = &chain[i..];
1374                if members.iter().all(|m| !cyclic.contains(m)) {
1375                    let mut shown = members.to_vec();
1376                    shown.push(next.clone());
1377                    problems.push(Error::BasedOnCycle { chain: shown });
1378                    cyclic.extend(members.iter().cloned());
1379                }
1380                break;
1381            }
1382            chain.push(next.clone());
1383            at = next;
1384        }
1385    }
1386    let mut done: BTreeSet<String> = BTreeSet::new();
1387    let components: Vec<String> = bases.keys().cloned().collect();
1388    for component in components {
1389        complete(raw, &bases, &cyclic, &mut done, &component, problems);
1390    }
1391}
1392
1393/// Gives `component` its base's tokens, its base completed first.
1394fn complete(
1395    raw: &mut BTreeMap<String, RawToken>,
1396    bases: &BTreeMap<String, String>,
1397    cyclic: &BTreeSet<String>,
1398    done: &mut BTreeSet<String>,
1399    component: &str,
1400    problems: &mut Vec<Error>,
1401) {
1402    if cyclic.contains(component) || !done.insert(component.to_string()) {
1403        return;
1404    }
1405    let Some(base) = bases.get(component) else {
1406        return;
1407    };
1408    complete(raw, bases, cyclic, done, base, problems);
1409    let prefix = format!("{base}.");
1410    let inherited: Vec<(String, RawToken)> = raw
1411        .range(prefix.clone()..)
1412        .take_while(|(path, _)| path.starts_with(&prefix))
1413        .filter_map(|(path, token)| {
1414            let term = &path[prefix.len()..];
1415            if term == BASED_ON {
1416                return None;
1417            }
1418            let own = format!("{component}.{term}");
1419            (!raw.contains_key(&own)).then(|| {
1420                (
1421                    own,
1422                    RawToken {
1423                        ty: token.ty.clone(),
1424                        value: json!(format!("{{{path}}}")),
1425                        description: None,
1426                        extensions: None,
1427                    },
1428                )
1429            })
1430        })
1431        .collect();
1432    let has_base = raw
1433        .range(prefix.clone()..)
1434        .next()
1435        .is_some_and(|(path, _)| path.starts_with(&prefix));
1436    if !has_base {
1437        problems.push(Error::UnknownBase {
1438            path: format!("{component}.{BASED_ON}"),
1439            base: base.clone(),
1440        });
1441        return;
1442    }
1443    raw.extend(inherited);
1444}
1445
1446/// Lays `over` on `under`: values replace, a token without a type keeps the
1447/// type it had.
1448fn layer(under: &mut BTreeMap<String, RawToken>, over: &BTreeMap<String, RawToken>) {
1449    for (path, token) in over {
1450        let mut token = token.clone();
1451        if token.ty.is_none() {
1452            token.ty = under.get(path).and_then(|t| t.ty.clone());
1453        }
1454        if token.description.is_none() {
1455            token.description = under.get(path).and_then(|t| t.description.clone());
1456        }
1457        under.insert(path.clone(), token);
1458    }
1459}
1460
1461/// Whether `path` is a token of one of `scales` (`blue.3` of `blue`).
1462pub(crate) fn in_scales<'a>(mut scales: impl Iterator<Item = &'a String>, path: &str) -> bool {
1463    scales.any(|s| {
1464        path.strip_prefix(s.as_str())
1465            .is_some_and(|rest| rest.starts_with('.'))
1466    })
1467}
1468
1469/// What a seeded scale is fitted to, and the scheme it is generated for
1470/// when its seed does not say: the theme as `under` and `own` give it,
1471/// the seeded scales' own tokens left out (so a scale never fits itself).
1472pub(crate) fn seed_backdrop(
1473    under: &BTreeMap<String, RawToken>,
1474    own: &BTreeMap<String, RawToken>,
1475    seeds: &BTreeMap<String, Seed>,
1476) -> (Backdrop, Scheme) {
1477    let mut raw = under.clone();
1478    let others: BTreeMap<String, RawToken> = own
1479        .iter()
1480        .filter(|(p, _)| !in_scales(seeds.keys(), p))
1481        .map(|(p, t)| (p.clone(), t.clone()))
1482        .collect();
1483    layer(&mut raw, &others);
1484    let color = |path: &str| match resolve_one(&raw, path) {
1485        Ok((_, Value::Color(c))) => Some(c),
1486        _ => None,
1487    };
1488    let scheme = color("surface.panel").map_or(Scheme::Dark, Scheme::of_background);
1489    (Backdrop::from_tokens(color), scheme)
1490}
1491
1492/// The tokens of the scales a file gives by their seed
1493/// ([`crate::palette::SEEDS_EXTENSION`]), generated over `under` (the
1494/// themes the file extends) and fitted to the theme with the file's own
1495/// tokens ([`seed_backdrop`]). A scale the themes under it already have
1496/// gets the steps they have (a neutral scale has no `contrast`); a new
1497/// one gets its twelve steps and `contrast`.
1498pub(crate) fn seeded_scales(
1499    under: &BTreeMap<String, RawToken>,
1500    own: &BTreeMap<String, RawToken>,
1501    seeds: &BTreeMap<String, Seed>,
1502) -> BTreeMap<String, RawToken> {
1503    let (backdrop, scheme) = seed_backdrop(under, own, seeds);
1504    let mut out = BTreeMap::new();
1505    for (scale, seed) in seeds {
1506        let ramp = Ramp::fitted(seed.color, seed.scheme.unwrap_or(scheme), &backdrop);
1507        let known = under.contains_key(&format!("{scale}.1"));
1508        for (path, value) in ramp.tokens(scale) {
1509            if known && !under.contains_key(&path) && !own.contains_key(&path) {
1510                continue;
1511            }
1512            out.insert(
1513                path,
1514                RawToken {
1515                    ty: Some("color".into()),
1516                    value,
1517                    description: Some(format!("Generated from {}.", seed.color.to_hex())),
1518                    extensions: None,
1519                },
1520            );
1521        }
1522    }
1523    out
1524}
1525
1526fn is_accent_scale(raw: &BTreeMap<String, RawToken>, scale: &str) -> bool {
1527    ACCENT_ROLES
1528        .iter()
1529        .all(|(_, step)| raw.contains_key(&format!("{scale}.{step}")))
1530}
1531
1532/// `$extensions` without the alpha modifier, `None` when nothing else
1533/// is left.
1534fn without_alpha(extensions: Option<&Json>) -> Option<Json> {
1535    let mut e = extensions?.clone();
1536    if let Some(map) = e.as_object_mut() {
1537        map.remove(ALPHA_EXTENSION);
1538        if map.is_empty() {
1539            return None;
1540        }
1541    }
1542    Some(e)
1543}
1544
1545/// A token's alpha modifier ([`ALPHA_EXTENSION`]), if it carries one.
1546fn alpha_of(path: &str, token: &RawToken) -> Result<Option<f32>, Error> {
1547    let Some(a) = token
1548        .extensions
1549        .as_ref()
1550        .and_then(|e| e.get(ALPHA_EXTENSION))
1551    else {
1552        return Ok(None);
1553    };
1554    match a.as_f64() {
1555        Some(a) if (0.0..=1.0).contains(&a) => Ok(Some(a as f32)),
1556        _ => Err(Error::InvalidModifier {
1557            path: path.to_string(),
1558            reason: format!("`{ALPHA_EXTENSION}` is {a}, not a number from 0 to 1"),
1559        }),
1560    }
1561}
1562
1563/// A token's type and value, aliases followed, alpha modifiers applied.
1564fn resolve_one(raw: &BTreeMap<String, RawToken>, path: &str) -> Result<(String, Value), Error> {
1565    let mut chain = vec![path.to_string()];
1566    let mut declared = raw.get(path).and_then(|t| t.ty.clone());
1567    let mut at = raw.get(path).ok_or_else(|| Error::Missing {
1568        path: path.to_string(),
1569    })?;
1570    // The alpha to multiply by, and the first token asking for it.
1571    let mut alpha = alpha_of(path, at)?.map(|a| (a, path.to_string()));
1572    while let Some(target) = alias_target(&at.value) {
1573        if chain.iter().any(|c| c == target) {
1574            chain.push(target.to_string());
1575            return Err(Error::AliasCycle { chain });
1576        }
1577        let next = raw.get(target).ok_or_else(|| Error::UnknownAlias {
1578            path: chain.last().cloned().unwrap_or_default(),
1579            target: target.to_string(),
1580        })?;
1581        if let (Some(d), Some(t)) = (&declared, &next.ty)
1582            && d != t
1583        {
1584            return Err(Error::TypeMismatch {
1585                path: path.to_string(),
1586                expected: d.clone(),
1587                found: format!("{t} (through `{{{target}}}`)"),
1588            });
1589        }
1590        declared = declared.or_else(|| next.ty.clone());
1591        if let Some(a) = alpha_of(target, next)? {
1592            alpha = Some(match alpha {
1593                Some((b, carrier)) => (a * b, carrier),
1594                None => (a, target.to_string()),
1595            });
1596        }
1597        chain.push(target.to_string());
1598        at = next;
1599    }
1600    let ty = declared.ok_or_else(|| Error::MissingType {
1601        path: path.to_string(),
1602    })?;
1603    let mut value = Value::parse(&ty, &at.value).map_err(|reason| Error::InvalidValue {
1604        path: path.to_string(),
1605        ty: ty.clone(),
1606        reason,
1607    })?;
1608    if let Some((a, carrier)) = alpha {
1609        match &mut value {
1610            Value::Color(c) => c.a *= a,
1611            _ => {
1612                return Err(Error::InvalidModifier {
1613                    path: carrier,
1614                    reason: format!("`{ALPHA_EXTENSION}` is for colours, this is a {ty}"),
1615                });
1616            }
1617        }
1618    }
1619    Ok((ty, value))
1620}