Skip to main content

egui_pop_tokens/
draft.rs

1//! A theme being edited: a base theme, the tokens changed over it, and
2//! the history of those changes. What a theme editor works on, with no
3//! egui in it.
4//!
5//! A draft is saved as an ordinary token file ([`TokenFile`]): `$extends`
6//! names the base theme, and the file gives the changed tokens only, with
7//! their types. Any file egui-pop loads can be read back as a draft.
8//!
9//! A theme with a light and a dark variant is edited as a pair
10//! ([`ThemeDraft::pair`], [`ThemeDraft::from_pair_spec`]): the draft
11//! holds both variants, each with its own changes and history, and edits
12//! one at a time ([`ThemeDraft::switch`]). It is saved as one file, the
13//! first variant's, carrying the other
14//! ([`crate::COUNTERPART_EXTENSION`]).
15//!
16//! ```
17//! use egui_pop_tokens::{ThemeDraft, Themes};
18//! use serde_json::json;
19//!
20//! let themes = Themes::default();
21//! let mut draft = ThemeDraft::new("pop-light");
22//! let edit = draft.edit(&themes, "accent.default", Some(json!("#2060c0")));
23//! draft.apply(edit.unwrap().expect("a change"));
24//! let text = draft.export(&themes, "my-theme");
25//! let (back, skipped) = ThemeDraft::import(&themes, "my-theme", &text).unwrap();
26//! assert!(skipped.is_empty());
27//! assert_eq!(back.overrides(), draft.overrides());
28//! assert!(draft.undo().is_some());
29//! assert!(draft.overrides().is_empty());
30//! ```
31
32use std::collections::BTreeMap;
33
34use serde_json::{Value as Json, json};
35
36use crate::file::{RawToken, TokenFile, alias_target};
37use crate::palette::{Ramp, Seed};
38use crate::theme::{
39    COUNTERPART_EXTENSION, Counterpart, FALLBACK_THEME, ThemeSpec, Themes, in_scales,
40    seed_backdrop, seeded_scales,
41};
42use crate::{Error, Value, Warning};
43
44/// The `$extensions` key the theme editor stamped its files with before
45/// the format stamp; still read.
46#[deprecated(note = "the editor stamps its files with `FORMAT_EXTENSION` (`FormatStamp`)")]
47pub const DRAFT_EXTENSION: &str = LEGACY_EXTENSION;
48
49/// The version the theme editor wrote under its former stamp.
50#[deprecated(note = "the editor stamps its files with `FORMAT_EXTENSION` (`FormatStamp`)")]
51pub const DRAFT_VERSION: u64 = LEGACY_VERSION;
52
53/// The editor's former stamp, read in files written before the format
54/// stamp.
55const LEGACY_EXTENSION: &str = "org.egui-pop.theme-editor";
56const LEGACY_VERSION: u64 = 1;
57
58/// How many edits a draft's history keeps by default, the oldest
59/// dropped first ([`ThemeDraft::set_history_cap`]).
60pub const DRAFT_HISTORY_CAP: usize = 500;
61
62/// One change of one token: from a value to another. `None` is the
63/// value the base theme gives (no override).
64#[derive(Clone, Debug, PartialEq)]
65pub struct TokenEdit {
66    pub path: String,
67    pub from: Option<Json>,
68    pub to: Option<Json>,
69}
70
71impl TokenEdit {
72    /// The edit taking this one back.
73    pub fn inverse(&self) -> TokenEdit {
74        TokenEdit {
75            path: self.path.clone(),
76            from: self.to.clone(),
77            to: self.from.clone(),
78        }
79    }
80
81    /// As JSON: `{path, from, to}`, `null` for the base theme's value.
82    pub fn to_json(&self) -> Json {
83        json!({ "path": self.path, "from": self.from, "to": self.to })
84    }
85}
86
87/// A pair's other variant generated from the one edited
88/// ([`ThemeDraft::generate_counterpart`]): a proposal, for a preview,
89/// that changes nothing until recorded.
90#[derive(Clone, Debug, Default, PartialEq)]
91pub struct GeneratedVariant {
92    /// The edits making the other variant: each checked against its
93    /// base, from its own values. Recorded on it as one change (the
94    /// first with [`ThemeDraft::record`], the others with
95    /// [`ThemeDraft::record_joined`]).
96    pub edits: Vec<TokenEdit>,
97    /// The seeds its scales are generated from, for its scheme: what it
98    /// records ([`ThemeDraft::set_seed`]) in place of its own.
99    pub seeds: BTreeMap<String, Seed>,
100    /// The tokens, or seeded scales, of the variant edited not carried
101    /// over: the other base has no such token, or the value does not
102    /// check there.
103    pub skipped: Vec<String>,
104}
105
106/// A theme being edited: one theme, or a light and dark pair.
107///
108/// Its methods read and change the variant edited: its base, its
109/// overrides, its history and its seeds. A pair's other variant keeps
110/// its own ([`ThemeDraft::counterpart`]) until [`ThemeDraft::switch`]
111/// makes it the one edited.
112///
113/// ```
114/// use egui_pop_tokens::{ThemeDraft, Themes};
115/// use serde_json::json;
116///
117/// let themes = Themes::default();
118/// let mut draft = ThemeDraft::for_theme(&themes, "pop-dark");
119/// assert_eq!(draft.counterpart().map(ThemeDraft::base), Some("pop-light"));
120/// let edit = draft.edit(&themes, "danger", Some(json!("#ff4040"))).unwrap();
121/// draft.apply(edit.unwrap());
122/// draft.switch();
123/// assert_eq!(draft.base(), "pop-light");
124/// assert!(draft.overrides().is_empty());
125/// assert!(!draft.can_undo(), "each variant its own history");
126/// let edit = draft.edit(&themes, "danger", Some(json!("#c00000"))).unwrap();
127/// draft.apply(edit.unwrap());
128/// // Installed as a pair, each variant with its own overrides.
129/// let spec = draft.pair_spec(&Default::default());
130/// assert_eq!(spec.base, "pop-dark");
131/// assert_eq!(spec.overrides["danger"], json!("#ff4040"));
132/// assert_eq!(spec.counterpart_overrides.unwrap()["danger"], json!("#c00000"));
133/// ```
134#[derive(Clone, Debug, PartialEq)]
135pub struct ThemeDraft {
136    base: String,
137    overrides: BTreeMap<String, Json>,
138    undo: Vec<TokenEdit>,
139    redo: Vec<TokenEdit>,
140    /// Per edit of `undo` and `redo`: whether it goes with the edit made
141    /// just before it, as one change ([`ThemeDraft::record_joined`]).
142    joined_undo: Vec<bool>,
143    joined_redo: Vec<bool>,
144    /// The scales generated from a seed ([`ThemeDraft::set_seed`]), by
145    /// scale: saved as their seed while their values are still the ones
146    /// it gives ([`ThemeDraft::to_file`]).
147    seeds: BTreeMap<String, Seed>,
148    /// A pair's other variant, light or dark: its own base, overrides,
149    /// history and seeds (its own `other` is `None`). `None` for a theme
150    /// alone.
151    other: Option<Box<ThemeDraft>>,
152    /// Whether the variant edited is the pair's second, the counterpart
153    /// of the theme named first.
154    second: bool,
155    /// How many edits the history keeps ([`ThemeDraft::set_history_cap`]).
156    cap: usize,
157}
158
159impl Default for ThemeDraft {
160    fn default() -> Self {
161        ThemeDraft::new(FALLBACK_THEME)
162    }
163}
164
165impl ThemeDraft {
166    /// A draft over a base theme, nothing changed yet.
167    pub fn new(base: impl Into<String>) -> ThemeDraft {
168        ThemeDraft {
169            base: base.into(),
170            overrides: BTreeMap::new(),
171            undo: Vec::new(),
172            redo: Vec::new(),
173            joined_undo: Vec::new(),
174            joined_redo: Vec::new(),
175            seeds: BTreeMap::new(),
176            other: None,
177            second: false,
178            cap: DRAFT_HISTORY_CAP,
179        }
180    }
181
182    /// A draft from a spec: its base and its overrides, no history; the
183    /// base alone (see [`ThemeDraft::from_pair_spec`] for its pair).
184    pub fn from_spec(spec: &ThemeSpec) -> ThemeDraft {
185        ThemeDraft {
186            overrides: spec.overrides.clone(),
187            ..ThemeDraft::new(spec.base.clone())
188        }
189    }
190
191    /// A draft over a light and dark pair, nothing changed in either:
192    /// `first` the theme named first (shown when nothing asks for the
193    /// other mode), edited first; `second` its counterpart.
194    pub fn pair(first: impl Into<String>, second: impl Into<String>) -> ThemeDraft {
195        ThemeDraft {
196            other: Some(Box::new(ThemeDraft::new(second))),
197            ..ThemeDraft::new(first)
198        }
199    }
200
201    /// A draft over a theme and, when it has one of the other mode, its
202    /// counterpart ([`Themes::counterpart_of`]), nothing changed: what
203    /// "start from a theme" gives.
204    pub fn for_theme(themes: &Themes, base: &str) -> ThemeDraft {
205        ThemeDraft::from_pair_spec(themes, &ThemeSpec::new(base))
206    }
207
208    /// A draft from a spec and its counterpart ([`Themes::counterpart`]),
209    /// no history: the base edited, with the spec's overrides; the
210    /// counterpart with its own overrides, or the spec's when it has
211    /// none of its own ([`ThemeSpec::counterpart_overrides`]). A
212    /// counterpart of the same mode as the base is not one: the draft is
213    /// the base alone.
214    pub fn from_pair_spec(themes: &Themes, spec: &ThemeSpec) -> ThemeDraft {
215        let mut draft = ThemeDraft::from_spec(spec);
216        if let Some(other) = themes
217            .counterpart(spec)
218            .filter(|other| is_dark(themes, other) != is_dark(themes, &spec.base))
219        {
220            draft.other = Some(Box::new(ThemeDraft {
221                overrides: spec
222                    .counterpart_overrides
223                    .clone()
224                    .unwrap_or_else(|| spec.overrides.clone()),
225                ..ThemeDraft::new(other)
226            }));
227        }
228        draft
229    }
230
231    /// Whether the draft is a light and dark pair.
232    pub fn is_paired(&self) -> bool {
233        self.other.is_some()
234    }
235
236    /// The pair's other variant, as it is: its base, overrides, history
237    /// and seeds. `None` for a theme alone.
238    pub fn counterpart(&self) -> Option<&ThemeDraft> {
239        self.other.as_deref()
240    }
241
242    /// Whether the variant edited is the pair's second (the counterpart
243    /// of the theme named first).
244    pub fn editing_second(&self) -> bool {
245        self.second
246    }
247
248    /// The pair's variants: the theme named first, then its counterpart
249    /// (`None` for a theme alone). Read their base, overrides, history
250    /// and seeds.
251    pub fn variants(&self) -> (&ThemeDraft, Option<&ThemeDraft>) {
252        match self.other.as_deref() {
253            None => (self, None),
254            Some(other) if self.second => (other, Some(self)),
255            Some(other) => (self, Some(other)),
256        }
257    }
258
259    /// The pair's other variant as generated from the one edited, so
260    /// that it becomes its counterpart: its base with the edited
261    /// variant's changes carried over, its own changes not among them
262    /// taken back. `None` for a theme alone. Deterministic, and nothing
263    /// is changed: record [`GeneratedVariant::edits`] on the other
264    /// variant (after [`ThemeDraft::switch`]) to apply it.
265    ///
266    /// How each change is carried over:
267    ///
268    /// - a colour value: mirrored ([`crate::palette::mirror`], the
269    ///   same OkHsl hue and saturation, the lightness `1 - l`);
270    /// - an alias (`{blue.9}`): as it is, so it names the other
271    ///   variant's own token;
272    /// - any other value (a dimension, a number, a duration, font
273    ///   families): as it is, shared by both;
274    /// - a scale generated from a seed ([`ThemeDraft::set_seed`], its
275    ///   step 9 still changed): the same seed for the other scheme,
276    ///   generated again ([`ThemeDraft::seeded_ramp`]) over the other
277    ///   variant with the changes above, its steps written; the seed is
278    ///   in [`GeneratedVariant::seeds`].
279    ///
280    /// ```
281    /// use egui_pop_tokens::{ThemeDraft, Themes};
282    /// use serde_json::json;
283    ///
284    /// let themes = Themes::default();
285    /// let mut draft = ThemeDraft::for_theme(&themes, "pop-dark");
286    /// let e = draft.edit(&themes, "surface.panel", Some(json!("#000000"))).unwrap();
287    /// draft.apply(e.unwrap());
288    /// let generated = draft.generate_counterpart(&themes).unwrap();
289    /// assert_eq!(generated.edits[0].path, "surface.panel");
290    /// assert_eq!(generated.edits[0].to, Some(json!("#ffffff")));
291    /// ```
292    pub fn generate_counterpart(&self, themes: &Themes) -> Option<GeneratedVariant> {
293        let other = self.other.as_deref()?;
294        let scheme = if is_dark(themes, &other.base) {
295            crate::palette::Scheme::Dark
296        } else {
297            crate::palette::Scheme::Light
298        };
299        let resolved = themes.resolve(&ThemeSpec::new(other.base.clone()));
300        let live: BTreeMap<&String, &Seed> = self
301            .seeds
302            .iter()
303            .filter(|(scale, _)| self.overrides.contains_key(&format!("{scale}.9")))
304            .collect();
305        let mut out = GeneratedVariant::default();
306        let mut wanted: BTreeMap<String, Json> = BTreeMap::new();
307        for (path, value) in &self.overrides {
308            if in_scales(live.keys().copied(), path) {
309                continue;
310            }
311            let is_color = resolved.get(path).is_some_and(|t| t.ty == "color");
312            let carried = match Value::parse("color", value) {
313                Ok(Value::Color(c)) if is_color && alias_target(value).is_none() => {
314                    json!(crate::palette::mirror(c).to_hex())
315                }
316                _ => value.clone(),
317            };
318            match check(themes, &other.base, path, &carried) {
319                Ok(()) => {
320                    wanted.insert(path.clone(), carried);
321                }
322                Err(_) => out.skipped.push(path.clone()),
323            }
324        }
325        // The seeded scales, fitted to the other variant as generated.
326        let fitted = ThemeDraft {
327            overrides: wanted.clone(),
328            ..ThemeDraft::new(other.base.clone())
329        };
330        for (scale, seed) in live {
331            if resolved.get(&format!("{scale}.9")).is_none() {
332                out.skipped.push(scale.clone());
333                continue;
334            }
335            let seed = Seed::new(seed.color, scheme);
336            let ramp = fitted.seeded_ramp(themes, scale, seed);
337            for (path, value) in ramp.tokens(scale) {
338                if resolved.get(&path).is_some() {
339                    wanted.insert(path, value);
340                }
341            }
342            out.seeds.insert(scale.clone(), seed);
343        }
344        let paths: std::collections::BTreeSet<&String> =
345            other.overrides.keys().chain(wanted.keys()).collect();
346        for path in paths {
347            let from = other.overrides.get(path).cloned();
348            let to = wanted.get(path).cloned();
349            if from != to {
350                out.edits.push(TokenEdit {
351                    path: path.clone(),
352                    from,
353                    to,
354                });
355            }
356        }
357        Some(out)
358    }
359
360    /// Edits the pair's other variant: what was edited keeps its changes
361    /// and history, and gets them back when switched to again. `false`
362    /// for a theme alone (nothing to switch to).
363    pub fn switch(&mut self) -> bool {
364        let Some(mut other) = self.other.take() else {
365            return false;
366        };
367        std::mem::swap(self, &mut *other);
368        self.second = !other.second;
369        other.second = false;
370        self.other = Some(other);
371        true
372    }
373
374    pub fn base(&self) -> &str {
375        &self.base
376    }
377
378    /// The tokens changed over the base theme, raw DTCG values by path.
379    pub fn overrides(&self) -> &BTreeMap<String, Json> {
380        &self.overrides
381    }
382
383    /// A token's own value in this draft, `None` when the base theme
384    /// gives it.
385    pub fn value(&self, path: &str) -> Option<&Json> {
386        self.overrides.get(path)
387    }
388
389    /// `template` with the variant edited's base and overrides (its
390    /// density, accent and reduced motion kept): what the variant edited
391    /// resolves from.
392    pub fn spec(&self, template: &ThemeSpec) -> ThemeSpec {
393        let mut spec = template.clone();
394        spec.base = self.base.clone();
395        spec.overrides = self.overrides.clone();
396        spec.counterpart_overrides = None;
397        spec
398    }
399
400    /// `template` with the whole draft, as it is installed: the theme
401    /// named first, its overrides, and its counterpart with overrides of
402    /// its own ([`ThemeSpec::counterpart_overrides`]); a theme alone has
403    /// no counterpart (its overrides are not another theme's).
404    pub fn pair_spec(&self, template: &ThemeSpec) -> ThemeSpec {
405        let (first, second) = self.variants();
406        let mut spec = template.clone();
407        spec.base = first.base.clone();
408        spec.overrides = first.overrides.clone();
409        match second {
410            Some(second) => {
411                spec.counterpart = Counterpart::Theme(second.base.clone());
412                spec.counterpart_overrides = Some(second.overrides.clone());
413            }
414            None => {
415                spec.counterpart = Counterpart::None;
416                spec.counterpart_overrides = None;
417            }
418        }
419        spec
420    }
421
422    /// Checks a new value for a token and gives the edit setting it, or
423    /// why it cannot be: the token must be one of the base theme's, and
424    /// the value one of its type or an alias of a token of that type.
425    /// `None` goes back to the base theme's value. `Ok(None)`: nothing
426    /// would change.
427    pub fn edit(
428        &self,
429        themes: &Themes,
430        path: &str,
431        to: Option<Json>,
432    ) -> Result<Option<TokenEdit>, String> {
433        if let Some(value) = &to {
434            check(themes, &self.base, path, value)?;
435        } else if !base_has(themes, &self.base, path) {
436            return Err(format!("`{}` has no token `{path}`", self.base));
437        }
438        let from = self.overrides.get(path).cloned();
439        if from == to {
440            return Ok(None);
441        }
442        Ok(Some(TokenEdit {
443            path: path.to_string(),
444            from,
445            to,
446        }))
447    }
448
449    /// Sets a token without recording it: a gesture in progress, shown
450    /// live, recorded once at its end with [`ThemeDraft::record`].
451    pub fn preview(&mut self, path: &str, to: Option<Json>) {
452        match to {
453            Some(v) => self.overrides.insert(path.to_string(), v),
454            None => self.overrides.remove(path),
455        };
456    }
457
458    /// Records an edit already shown (by [`ThemeDraft::preview`]): it
459    /// becomes the next to undo, and nothing is left to redo.
460    pub fn record(&mut self, edit: TokenEdit) {
461        self.push(edit, false);
462    }
463
464    /// Records an edit as part of the change recorded just before it (a
465    /// palette generated at once): [`ThemeDraft::undo_group`] and
466    /// [`ThemeDraft::redo_group`] count them as one.
467    pub fn record_joined(&mut self, edit: TokenEdit) {
468        let joined = !self.undo.is_empty();
469        self.push(edit, joined);
470    }
471
472    fn push(&mut self, edit: TokenEdit, joined: bool) {
473        self.preview(&edit.path.clone(), edit.to.clone());
474        self.undo.push(edit);
475        self.joined_undo.push(joined);
476        self.redo.clear();
477        self.joined_redo.clear();
478        self.trim_history();
479    }
480
481    /// How many edits the next undo takes back as one change: 1, or the
482    /// edits recorded together ([`ThemeDraft::record_joined`]); 0 when
483    /// there is nothing to undo.
484    pub fn undo_group(&self) -> usize {
485        if self.undo.is_empty() {
486            return 0;
487        }
488        1 + self.joined_undo.iter().rev().take_while(|j| **j).count()
489    }
490
491    /// How many edits the next redo makes again as one change.
492    pub fn redo_group(&self) -> usize {
493        if self.redo.is_empty() {
494            return 0;
495        }
496        1 + self
497            .joined_redo
498            .iter()
499            .rev()
500            .skip(1)
501            .take_while(|j| **j)
502            .count()
503    }
504
505    /// How many edits the history keeps ([`DRAFT_HISTORY_CAP`] by default).
506    pub fn history_cap(&self) -> usize {
507        self.cap
508    }
509
510    /// Keeps at most `cap` edits to undo (and as many to redo), for this
511    /// variant and a pair's other one, dropping the oldest now and
512    /// whenever a new edit goes over it. Edits recorded together
513    /// ([`ThemeDraft::record_joined`]) go as one: the oldest change goes
514    /// whole, and the newest stays whole even when it alone is over the
515    /// cap (a generated scale). 0 keeps none.
516    pub fn set_history_cap(&mut self, cap: usize) {
517        self.cap = cap;
518        self.trim_history();
519        if let Some(other) = self.other.as_deref_mut() {
520            other.set_history_cap(cap);
521        }
522    }
523
524    fn trim_history(&mut self) {
525        let cap = self.cap;
526        // `undo` runs oldest first, each change a `false` then its joined
527        // `true`s; `redo` runs farthest first, each change its `true`s then
528        // its `false`.
529        trim(&mut self.undo, &mut self.joined_undo, cap, |j| {
530            j.iter()
531                .skip(1)
532                .position(|j| !*j)
533                .map_or(j.len(), |n| n + 1)
534        });
535        trim(&mut self.redo, &mut self.joined_redo, cap, |j| {
536            j.iter().position(|j| !*j).map_or(j.len(), |n| n + 1)
537        });
538    }
539
540    /// Makes an edit and records it (the same as [`ThemeDraft::record`],
541    /// named for edits not previewed first).
542    pub fn apply(&mut self, edit: TokenEdit) {
543        self.record(edit);
544    }
545
546    /// The edits writing a generated scale over one of the base theme's
547    /// scales (`blue`, `gray`): its steps 1 to 12 and its `contrast`,
548    /// those the base has, each checked as [`ThemeDraft::edit`] does,
549    /// those already at that value left out. Record them with
550    /// [`ThemeDraft::record`] then [`ThemeDraft::record_joined`] so they
551    /// undo as one change.
552    ///
553    /// ```
554    /// use egui_pop_tokens::palette::{Ramp, Scheme};
555    /// use egui_pop_tokens::{Color, ThemeDraft, Themes};
556    ///
557    /// let themes = Themes::default();
558    /// let mut draft = ThemeDraft::new("pop-light");
559    /// let ramp = Ramp::new(Color::from_hex("#8e44ad").unwrap(), Scheme::Light);
560    /// let edits = draft.scale_edits(&themes, "blue", &ramp).unwrap();
561    /// assert_eq!(edits.len(), 13);
562    /// for (i, e) in edits.into_iter().enumerate() {
563    ///     if i == 0 { draft.record(e) } else { draft.record_joined(e) }
564    /// }
565    /// assert_eq!(draft.undo_group(), 13);
566    /// ```
567    pub fn scale_edits(
568        &self,
569        themes: &Themes,
570        scale: &str,
571        ramp: &crate::palette::Ramp,
572    ) -> Result<Vec<TokenEdit>, String> {
573        if !base_has(themes, &self.base, &format!("{scale}.9")) {
574            return Err(format!("`{}` has no colour scale `{scale}`", self.base));
575        }
576        let mut edits = Vec::new();
577        for (path, value) in ramp.tokens(scale) {
578            if !base_has(themes, &self.base, &path) {
579                continue;
580            }
581            if let Some(e) = self.edit(themes, &path, Some(value))? {
582                edits.push(e);
583            }
584        }
585        Ok(edits)
586    }
587
588    /// The ramp a seed gives for one of the base theme's scales, as a
589    /// file giving that scale by its seed is resolved: fitted to the
590    /// draft's theme without that scale's own tokens
591    /// ([`crate::palette::SEEDS_EXTENSION`]). Write it with
592    /// [`ThemeDraft::scale_edits`], then [`ThemeDraft::set_seed`], so the
593    /// file saves the seed rather than twelve values.
594    pub fn seeded_ramp(&self, themes: &Themes, scale: &str, seed: Seed) -> Ramp {
595        let under = themes.flatten(&self.base, &mut Vec::new());
596        let one = BTreeMap::from([(scale.to_string(), seed)]);
597        let (backdrop, scheme) = seed_backdrop(&under, &own_tokens(&self.overrides), &one);
598        Ramp::fitted(seed.color, seed.scheme.unwrap_or(scheme), &backdrop)
599    }
600
601    /// Records that a scale was generated from a seed (`None` forgets
602    /// it). Not an edit: the scale's values are ([`ThemeDraft::scale_edits`]).
603    /// The file saves the seed in place of the scale's values as long as
604    /// they are the ones it gives; once changed by hand or undone, the
605    /// values are saved as they are.
606    pub fn set_seed(&mut self, scale: &str, seed: Option<Seed>) {
607        match seed {
608            Some(seed) => self.seeds.insert(scale.to_string(), seed),
609            None => self.seeds.remove(scale),
610        };
611    }
612
613    /// The seed a scale was generated from, as recorded.
614    pub fn seed(&self, scale: &str) -> Option<Seed> {
615        self.seeds.get(scale).copied()
616    }
617
618    /// The seeds recorded, by scale.
619    pub fn seeds(&self) -> &BTreeMap<String, Seed> {
620        &self.seeds
621    }
622
623    /// The changes an undo walks back, oldest first: each the edits
624    /// recorded together ([`ThemeDraft::record_joined`]), in the order
625    /// they were made.
626    pub fn undo_changes(&self) -> Vec<Vec<TokenEdit>> {
627        let mut out: Vec<Vec<TokenEdit>> = Vec::new();
628        for (edit, joined) in self.undo.iter().zip(&self.joined_undo) {
629            match out.last_mut() {
630                Some(group) if *joined => group.push(edit.clone()),
631                _ => out.push(vec![edit.clone()]),
632            }
633        }
634        out
635    }
636
637    /// The changes a redo makes again, the next one last, each in the
638    /// order its edits were made.
639    pub fn redo_changes(&self) -> Vec<Vec<TokenEdit>> {
640        let mut out = Vec::new();
641        let mut end = self.redo.len();
642        while end > 0 {
643            // The change's first edit is the nearest; the edits joined
644            // to it lie before it in the list.
645            let first = end - 1;
646            let mut start = first;
647            while start > 0 && self.joined_redo.get(start - 1).copied().unwrap_or(false) {
648                start -= 1;
649            }
650            out.push(self.redo[start..=first].iter().rev().cloned().collect());
651            end = start;
652        }
653        out.reverse();
654        out
655    }
656
657    /// The edit an undo would make (the last one's inverse).
658    pub fn undo_edit(&self) -> Option<TokenEdit> {
659        self.undo.last().map(TokenEdit::inverse)
660    }
661
662    /// The edit a redo would make.
663    pub fn redo_edit(&self) -> Option<TokenEdit> {
664        self.redo.last().cloned()
665    }
666
667    /// Takes the last edit back; returns the edit made (its inverse).
668    pub fn undo(&mut self) -> Option<TokenEdit> {
669        let edit = self.undo.pop()?;
670        let joined = self.joined_undo.pop().unwrap_or(false);
671        self.preview(&edit.path, edit.from.clone());
672        let made = edit.inverse();
673        self.redo.push(edit);
674        self.joined_redo.push(joined);
675        Some(made)
676    }
677
678    /// Makes the last undone edit again; returns it.
679    pub fn redo(&mut self) -> Option<TokenEdit> {
680        let edit = self.redo.pop()?;
681        let joined = self.joined_redo.pop().unwrap_or(false);
682        self.preview(&edit.path, edit.to.clone());
683        self.undo.push(edit.clone());
684        self.joined_undo.push(joined);
685        Some(edit)
686    }
687
688    pub fn can_undo(&self) -> bool {
689        !self.undo.is_empty()
690    }
691
692    pub fn can_redo(&self) -> bool {
693        !self.redo.is_empty()
694    }
695
696    /// The edits made, oldest first (what an undo takes back last).
697    pub fn history(&self) -> &[TokenEdit] {
698        &self.undo
699    }
700
701    /// The draft as a token file named `name`: `$extends` its base, its
702    /// overrides with their types, stamped with the current format
703    /// ([`crate::FormatStamp`]). A scale generated from a seed
704    /// ([`ThemeDraft::set_seed`]) is saved as its seed
705    /// ([`crate::palette::SEEDS_EXTENSION`]): the steps whose value is the
706    /// one the seed gives are left out (regenerated when the file is
707    /// loaded), a step changed since is written as it is. A seed none of
708    /// whose steps still has its value (undone, or the theme changed
709    /// under it) is not saved. Loading the file gives the draft's values.
710    ///
711    /// A pair is saved as a new pair: the file is the theme named first's,
712    /// named `name`, and carries its counterpart, named `name` and its
713    /// mode (`ocean-light`), each naming the other
714    /// ([`TokenFile::set_counterpart_file`]); loaded with
715    /// [`Themes::add_text`], both are added.
716    pub fn to_file(&self, themes: &Themes, name: &str) -> TokenFile {
717        let (first, second) = self.variants();
718        let mut file = first.variant_file(themes, name);
719        if let Some(second) = second {
720            let mode = if is_dark(themes, &second.base) {
721                "dark"
722            } else {
723                "light"
724            };
725            file.set_counterpart_file(Some(second.variant_file(themes, &format!("{name}-{mode}"))));
726        }
727        file
728    }
729
730    /// The variant edited as a token file, alone.
731    fn variant_file(&self, themes: &Themes, name: &str) -> TokenFile {
732        let base = themes.resolve(&ThemeSpec::new(self.base.clone()));
733        let mut file = TokenFile::new(name);
734        file.description = Some(format!("Edited from {}", self.base));
735        file.extends = Some(self.base.clone());
736        file.stamp();
737        for (path, value) in &self.overrides {
738            file.tokens.insert(
739                path.clone(),
740                RawToken {
741                    ty: base.get(path).map(|t| t.ty.clone()),
742                    value: value.clone(),
743                    description: None,
744                    extensions: None,
745                },
746            );
747        }
748        if self.seeds.is_empty() {
749            return file;
750        }
751        // The seeds still giving the draft's values, until that holds for
752        // every seed kept (which seeds are kept changes what the others
753        // are fitted to).
754        let under = themes.flatten(&self.base, &mut Vec::new());
755        let own = own_tokens(&self.overrides);
756        let mut kept = self.seeds.clone();
757        let generated = loop {
758            let generated = seeded_scales(&under, &own, &kept);
759            let stale: Vec<String> = kept
760                .keys()
761                .filter(|scale| {
762                    !generated.iter().any(|(path, t)| {
763                        in_scales(std::iter::once(*scale), path)
764                            && self.overrides.get(path) == Some(&t.value)
765                    })
766                })
767                .cloned()
768                .collect();
769            if stale.is_empty() {
770                break generated;
771            }
772            for scale in stale {
773                kept.remove(&scale);
774            }
775        };
776        for (path, t) in generated {
777            match self.overrides.get(&path) {
778                Some(v) if *v == t.value => {
779                    file.tokens.remove(&path);
780                }
781                Some(_) => {}
782                // The base's value, which the seed would replace.
783                None => {
784                    if let Some(raw) = under.get(&path) {
785                        file.tokens.insert(path, raw.clone());
786                    }
787                }
788            }
789        }
790        for (scale, seed) in kept {
791            file.set_seed(&scale, Some(seed));
792        }
793        file
794    }
795
796    /// The draft as the text of a `.tokens.json` file.
797    pub fn export(&self, themes: &Themes, name: &str) -> String {
798        self.to_file(themes, name).to_json_pretty()
799    }
800
801    /// Reads a token file as a draft: its `$extends` becomes the base
802    /// (the fallback theme when it has none), its tokens the overrides.
803    /// The file loads over its base as any theme file does
804    /// ([`Themes::check_file`]): brought to the current contract, a token
805    /// whose value does not check left out, the base's value kept. A
806    /// draft changes its base's tokens only, so a token the base does
807    /// not have is left out too. Each is a warning, as is a file stamped
808    /// newer than this egui-pop knows (read best-effort). Only an
809    /// unreadable file or an unknown base is an error.
810    ///
811    /// A file carrying its counterpart ([`COUNTERPART_EXTENSION`]) is a
812    /// pair: the draft holds both variants, the file's own edited first.
813    /// A counterpart that cannot be read, of an unknown base or of the
814    /// same mode is a warning, the file's variant read alone.
815    pub fn import(
816        themes: &Themes,
817        name: &str,
818        text: &str,
819    ) -> Result<(ThemeDraft, Vec<Warning>), Error> {
820        let file = TokenFile::parse(name, text)?;
821        let counterpart = file.counterpart_file();
822        let (mut draft, mut warnings) = ThemeDraft::import_file(themes, file)?;
823        let at = format!("$extensions.{COUNTERPART_EXTENSION}");
824        match counterpart.map(|c| c.and_then(|c| ThemeDraft::import_file(themes, c))) {
825            None => {}
826            Some(Ok((other, more))) => {
827                if is_dark(themes, &other.base) == is_dark(themes, &draft.base) {
828                    warnings.push(Warning::Invalid {
829                        path: at,
830                        reason: format!(
831                            "`{}` and `{}` are both light or both dark",
832                            draft.base, other.base
833                        ),
834                    });
835                } else {
836                    warnings.extend(more);
837                    draft.other = Some(Box::new(other));
838                }
839            }
840            Some(Err(e)) => warnings.push(Warning::Invalid {
841                path: at,
842                reason: e.to_string(),
843            }),
844        }
845        Ok((draft, warnings))
846    }
847
848    /// Reads one variant's token file as a draft alone.
849    fn import_file(
850        themes: &Themes,
851        mut file: TokenFile,
852    ) -> Result<(ThemeDraft, Vec<Warning>), Error> {
853        let mut warnings = file.upgrade();
854        if let Some(v) = file
855            .extensions
856            .as_ref()
857            .and_then(|x| x.get(LEGACY_EXTENSION))
858            .and_then(|x| x.get("version"))
859            .and_then(Json::as_u64)
860            && v > LEGACY_VERSION
861        {
862            warnings.push(Warning::Newer {
863                path: format!("$extensions.{LEGACY_EXTENSION}.version"),
864                found: v,
865                known: LEGACY_VERSION,
866            });
867        }
868        let base = file
869            .extends
870            .clone()
871            .unwrap_or_else(|| FALLBACK_THEME.to_string());
872        if themes.get(&base).is_none() {
873            return Err(Error::UnknownTheme { name: base });
874        }
875        let resolved = themes.resolve(&ThemeSpec::new(base.clone()));
876        let mut draft = ThemeDraft::new(base);
877        let (mut seeds, seed_warnings) = file.seeds();
878        warnings.extend(seed_warnings);
879        // A draft changes its base's scales only.
880        seeds.retain(|scale, _| {
881            let known = resolved.get(&format!("{scale}.1")).is_some();
882            if !known {
883                warnings.push(Warning::Unknown {
884                    path: format!("$extensions.{}.{scale}", crate::palette::SEEDS_EXTENSION),
885                    base: draft.base.clone(),
886                    kept: false,
887                });
888            }
889            known
890        });
891        for (path, token) in file.tokens {
892            if resolved.get(&path).is_none() {
893                warnings.push(Warning::Unknown {
894                    path,
895                    base: draft.base.clone(),
896                    kept: false,
897                });
898                continue;
899            }
900            match check(themes, &draft.base, &path, &token.value) {
901                Ok(()) => {
902                    draft.overrides.insert(path, token.value);
903                }
904                Err(reason) => warnings.push(Warning::Invalid { path, reason }),
905            }
906        }
907        // The seeded scales' steps the file does not give, as the file
908        // resolves them.
909        if !seeds.is_empty() {
910            let under = themes.flatten(&draft.base, &mut Vec::new());
911            for (path, t) in seeded_scales(&under, &own_tokens(&draft.overrides), &seeds) {
912                if !draft.overrides.contains_key(&path) && resolved.get(&path).is_some() {
913                    draft.overrides.insert(path, t.value);
914                }
915            }
916            draft.seeds = seeds;
917        }
918        Ok((draft, warnings))
919    }
920}
921
922/// A draft's overrides as raw tokens (their types from the tokens they
923/// override).
924/// Drops the oldest changes of a history until it holds at most `cap`
925/// edits, each change whole: `first` gives where the oldest change ends.
926/// The newest change stays, even over the cap, unless the cap is 0.
927fn trim(
928    edits: &mut Vec<TokenEdit>,
929    joined: &mut Vec<bool>,
930    cap: usize,
931    first: impl Fn(&[bool]) -> usize,
932) {
933    while edits.len() > cap {
934        let end = first(joined).min(edits.len());
935        if end == edits.len() && cap > 0 {
936            break;
937        }
938        edits.drain(..end);
939        joined.drain(..end.min(joined.len()));
940    }
941}
942
943fn own_tokens(overrides: &BTreeMap<String, Json>) -> BTreeMap<String, RawToken> {
944    overrides
945        .iter()
946        .map(|(path, value)| {
947            (
948                path.clone(),
949                RawToken {
950                    ty: None,
951                    value: value.clone(),
952                    description: None,
953                    extensions: None,
954                },
955            )
956        })
957        .collect()
958}
959
960/// Whether a theme is a dark one (its panels are), alone.
961fn is_dark(themes: &Themes, name: &str) -> bool {
962    themes.resolve(&ThemeSpec::new(name).alone()).is_dark()
963}
964
965/// Whether the base theme has the token.
966fn base_has(themes: &Themes, base: &str, path: &str) -> bool {
967    themes
968        .resolve(&ThemeSpec::new(base.to_string()))
969        .get(path)
970        .is_some()
971}
972
973/// Whether `value` may be `path`'s in the base theme.
974fn check(themes: &Themes, base: &str, path: &str, value: &Json) -> Result<(), String> {
975    let resolved = themes.resolve(&ThemeSpec::new(base.to_string()));
976    let token = resolved
977        .get(path)
978        .ok_or_else(|| format!("`{base}` has no token `{path}`"))?;
979    match alias_target(value) {
980        Some(target) => {
981            let to = resolved
982                .get(target)
983                .ok_or_else(|| format!("`{target}` is not a token of `{base}`"))?;
984            if target == path {
985                return Err(format!("`{path}` cannot alias itself"));
986            }
987            if to.ty != token.ty {
988                return Err(format!(
989                    "`{target}` is a {}, `{path}` a {}",
990                    to.ty, token.ty
991                ));
992            }
993            // An alias back to the token being edited would loop.
994            let mut at = to;
995            let mut seen = 0;
996            while let Some(next) = at.alias.as_deref() {
997                if next == path || seen > 64 {
998                    return Err(format!("`{target}` leads back to `{path}`"));
999                }
1000                match resolved.get(next) {
1001                    Some(t) => at = t,
1002                    None => break,
1003                }
1004                seen += 1;
1005            }
1006            Ok(())
1007        }
1008        None => Value::parse(&token.ty, value).map(|_| ()),
1009    }
1010}
1011
1012#[cfg(test)]
1013mod tests {
1014    use super::*;
1015
1016    fn themes() -> Themes {
1017        Themes::default()
1018    }
1019
1020    #[test]
1021    fn edits_undo_and_redo_in_order() {
1022        let t = themes();
1023        let mut d = ThemeDraft::new("pop-dark");
1024        let a = d
1025            .edit(&t, "surface.panel", Some(json!("#101010")))
1026            .unwrap()
1027            .unwrap();
1028        d.apply(a);
1029        let b = d
1030            .edit(&t, "surface.panel", Some(json!("#202020")))
1031            .unwrap()
1032            .unwrap();
1033        assert_eq!(b.from, Some(json!("#101010")));
1034        d.apply(b);
1035        assert_eq!(d.value("surface.panel"), Some(&json!("#202020")));
1036        let undone = d.undo().unwrap();
1037        assert_eq!(undone.to, Some(json!("#101010")));
1038        d.undo();
1039        assert!(d.overrides().is_empty());
1040        assert!(!d.can_undo());
1041        d.redo();
1042        assert_eq!(d.value("surface.panel"), Some(&json!("#101010")));
1043        // A new edit drops what was left to redo.
1044        let c = d.edit(&t, "text.default", Some(json!("#eeeeee"))).unwrap();
1045        d.apply(c.unwrap());
1046        assert!(!d.can_redo());
1047    }
1048
1049    #[test]
1050    fn the_history_keeps_its_newest_edits_up_to_its_cap() {
1051        let t = themes();
1052        let mut d = ThemeDraft::new("pop-dark");
1053        assert_eq!(d.history_cap(), DRAFT_HISTORY_CAP);
1054        let grey = |n: usize| json!(format!("#{n:06x}"));
1055        for n in 1..=DRAFT_HISTORY_CAP + 5 {
1056            let e = d.edit(&t, "surface.panel", Some(grey(n))).unwrap();
1057            d.apply(e.unwrap());
1058        }
1059        assert_eq!(
1060            d.history().len(),
1061            DRAFT_HISTORY_CAP,
1062            "the oldest five dropped"
1063        );
1064        assert_eq!(d.history()[0].to, Some(grey(6)));
1065        d.undo();
1066        d.set_history_cap(2);
1067        assert_eq!(d.history().len(), 2);
1068        assert!(d.can_redo());
1069        d.undo();
1070        d.undo();
1071        assert!(!d.can_undo());
1072        assert_eq!(d.value("surface.panel"), Some(&grey(DRAFT_HISTORY_CAP + 2)));
1073    }
1074
1075    #[test]
1076    fn the_cap_drops_and_keeps_joined_edits_as_one_change() {
1077        let edit = |path: &str| TokenEdit {
1078            path: path.to_string(),
1079            from: None,
1080            to: Some(json!("#000000")),
1081        };
1082        let mut d = ThemeDraft::pair("pop-dark", "pop-light");
1083        d.record(edit("a"));
1084        d.record(edit("b"));
1085        d.record(edit("g1"));
1086        d.record_joined(edit("g2"));
1087        d.record_joined(edit("g3"));
1088        // A cap of two drops `a` and `b`, and keeps the newest change
1089        // whole although it alone is over the cap.
1090        d.set_history_cap(2);
1091        assert_eq!(d.history().len(), 3);
1092        assert_eq!(d.undo_group(), 3);
1093        assert_eq!(d.counterpart().unwrap().history_cap(), 2);
1094        // The redo list, farthest first: c, then the joined change.
1095        d.set_history_cap(10);
1096        d.record(edit("c"));
1097        for _ in 0..4 {
1098            d.undo();
1099        }
1100        assert_eq!(d.redo_group(), 3);
1101        d.set_history_cap(3);
1102        assert_eq!(d.redo_group(), 3);
1103        assert_eq!(d.redo_edit().unwrap().path, "g1");
1104        d.set_history_cap(1);
1105        assert_eq!(d.redo_group(), 3, "the nearest change stays whole");
1106        d.set_history_cap(0);
1107        assert!(!d.can_undo() && !d.can_redo());
1108    }
1109
1110    #[test]
1111    fn values_are_checked_against_the_token_type() {
1112        let t = themes();
1113        let d = ThemeDraft::new("pop-dark");
1114        assert!(d.edit(&t, "surface.panel", Some(json!("blue"))).is_err());
1115        assert!(d.edit(&t, "surface.panel", Some(json!(4))).is_err());
1116        assert!(d.edit(&t, "no.such", Some(json!("#000000"))).is_err());
1117        assert!(
1118            d.edit(&t, "surface.panel", Some(json!("{space.m}")))
1119                .is_err()
1120        );
1121        assert!(
1122            d.edit(&t, "surface.panel", Some(json!("{surface.panel}")))
1123                .is_err()
1124        );
1125        assert!(
1126            d.edit(&t, "gray.2", Some(json!("{surface.panel}")))
1127                .is_err(),
1128            "surface.panel aliases gray.2: a loop"
1129        );
1130        assert!(
1131            d.edit(&t, "surface.panel", Some(json!("{gray.3}")))
1132                .unwrap()
1133                .is_some()
1134        );
1135        assert!(
1136            d.edit(
1137                &t,
1138                "radius.widget",
1139                Some(json!({ "value": 2, "unit": "px" }))
1140            )
1141            .unwrap()
1142            .is_some()
1143        );
1144        // Going back to the base value when nothing is changed: no edit.
1145        assert_eq!(d.edit(&t, "surface.panel", None), Ok(None));
1146    }
1147
1148    #[test]
1149    fn a_draft_exports_and_imports_as_a_token_file() {
1150        let t = themes();
1151        let mut d = ThemeDraft::new("pop-light");
1152        for (path, v) in [
1153            ("accent.default", json!("#2060c0")),
1154            ("radius.widget", json!({ "value": 2, "unit": "px" })),
1155            ("button.rest.border-color", json!("{border.strong}")),
1156        ] {
1157            let e = d.edit(&t, path, Some(v)).unwrap().unwrap();
1158            d.apply(e);
1159        }
1160        let text = d.export(&t, "mine");
1161        let file = TokenFile::parse("mine", &text).unwrap();
1162        assert_eq!(file.extends.as_deref(), Some("pop-light"));
1163        assert_eq!(file.tokens["accent.default"].ty.as_deref(), Some("color"));
1164        assert!(text.contains(crate::FORMAT_EXTENSION));
1165        let (back, warnings) = ThemeDraft::import(&t, "mine", &text).unwrap();
1166        assert!(warnings.is_empty(), "{warnings:?}");
1167        assert_eq!(back.base(), "pop-light");
1168        assert_eq!(back.overrides(), d.overrides());
1169        // The file resolves as a theme like any other.
1170        let mut with = t.clone();
1171        assert_eq!(with.add_text("mine", &text), Ok(vec![]));
1172        let r = with.resolve(&ThemeSpec::new("mine"));
1173        assert!(r.problems().is_empty(), "{:?}", r.problems());
1174        assert_eq!(r.color("accent.default"), crate::Color::from_hex("#2060c0"));
1175    }
1176
1177    #[test]
1178    fn imports_leave_out_what_does_not_fit_and_refuse_unknown_bases() {
1179        let t = themes();
1180        let (d, warnings) = ThemeDraft::import(
1181            &t,
1182            "x",
1183            r##"{ "surface": { "$type": "color", "panel": { "$value": "#000000" }, "nope": { "$value": "#000000" }, "sunken": { "$value": "blue" } } }"##,
1184        )
1185        .unwrap();
1186        assert_eq!(d.base(), FALLBACK_THEME);
1187        assert_eq!(d.value("surface.panel"), Some(&json!("#000000")));
1188        let left: Vec<&str> = warnings.iter().filter_map(Warning::path).collect();
1189        assert_eq!(left, ["surface.nope", "surface.sunken"]);
1190        assert!(warnings.iter().all(Warning::left_out));
1191        assert!(
1192            warnings[1]
1193                .to_string()
1194                .starts_with("`surface.sunken` left out"),
1195            "{}",
1196            warnings[1]
1197        );
1198        assert!(matches!(
1199            ThemeDraft::import(&t, "x", r#"{ "$extends": "nowhere" }"#),
1200            Err(Error::UnknownTheme { .. })
1201        ));
1202        // A file from a newer editor, or for a newer contract, loads
1203        // best-effort and says so.
1204        for newer in [
1205            format!(
1206                r#"{{ "$extends": "pop-dark", "$extensions": {{ "{LEGACY_EXTENSION}": {{ "version": 99 }} }} }}"#
1207            ),
1208            format!(
1209                r#"{{ "$extends": "pop-dark", "$extensions": {{ "{}": {{ "version": 1, "contract": 99 }} }} }}"#,
1210                crate::FORMAT_EXTENSION
1211            ),
1212        ] {
1213            let (d, warnings) = ThemeDraft::import(&t, "x", &newer).unwrap();
1214            assert_eq!(d.base(), "pop-dark");
1215            assert!(
1216                matches!(&warnings[..], [Warning::Newer { found: 99, .. }]),
1217                "{warnings:?}"
1218            );
1219        }
1220    }
1221
1222    #[test]
1223    fn joined_edits_undo_and_redo_as_one_change() {
1224        let themes = Themes::default();
1225        let mut d = ThemeDraft::new("pop-dark");
1226        let e =
1227            |d: &ThemeDraft, p: &str, v: &str| d.edit(&themes, p, Some(json!(v))).unwrap().unwrap();
1228        let first = e(&d, "accent.default", "#102030");
1229        d.record(first);
1230        let a = e(&d, "gold.1", "#111111");
1231        d.record(a);
1232        let b = e(&d, "gold.2", "#222222");
1233        d.record_joined(b);
1234        assert_eq!(d.undo_group(), 2);
1235        d.undo();
1236        d.undo();
1237        assert_eq!(d.undo_group(), 1);
1238        assert_eq!(d.redo_group(), 2);
1239        d.redo();
1240        d.redo();
1241        assert_eq!(d.redo_group(), 0);
1242        assert_eq!(d.undo_group(), 2);
1243        // A new edit after an undo starts a group of its own.
1244        d.undo();
1245        d.undo();
1246        let c = e(&d, "gold.3", "#333333");
1247        d.record(c);
1248        assert_eq!((d.undo_group(), d.redo_group()), (1, 0));
1249    }
1250
1251    #[test]
1252    fn the_changes_list_joined_edits_as_one_in_the_order_made() {
1253        let themes = Themes::default();
1254        let mut d = ThemeDraft::new("pop-dark");
1255        let e =
1256            |d: &ThemeDraft, p: &str, v: &str| d.edit(&themes, p, Some(json!(v))).unwrap().unwrap();
1257        let first = e(&d, "accent.default", "#102030");
1258        d.record(first);
1259        let a = e(&d, "gold.1", "#111111");
1260        d.record(a);
1261        let b = e(&d, "gold.2", "#222222");
1262        d.record_joined(b);
1263        let paths = |changes: Vec<Vec<TokenEdit>>| -> Vec<Vec<String>> {
1264            changes
1265                .into_iter()
1266                .map(|c| c.into_iter().map(|e| e.path).collect())
1267                .collect()
1268        };
1269        assert_eq!(
1270            paths(d.undo_changes()),
1271            [vec!["accent.default"], vec!["gold.1", "gold.2"]]
1272        );
1273        assert!(d.redo_changes().is_empty());
1274        // Both undone: the scale is the next redo, the accent after it.
1275        d.undo();
1276        d.undo();
1277        d.undo();
1278        assert_eq!(
1279            paths(d.redo_changes()),
1280            [vec!["gold.1", "gold.2"], vec!["accent.default"]]
1281        );
1282        d.redo();
1283        assert_eq!(paths(d.redo_changes()), [vec!["gold.1", "gold.2"]]);
1284        assert_eq!(paths(d.undo_changes()), [vec!["accent.default"]]);
1285    }
1286
1287    /// Generates `scale` from `hex` as the theme editor does: the edits,
1288    /// one change, and the seed recorded.
1289    fn generate(d: &mut ThemeDraft, themes: &Themes, scale: &str, hex: &str) {
1290        use crate::Color;
1291        use crate::palette::Scheme;
1292        let seed = Seed::new(Color::from_hex(hex).unwrap(), Scheme::Light);
1293        let ramp = d.seeded_ramp(themes, scale, seed);
1294        let edits = d.scale_edits(themes, scale, &ramp).unwrap();
1295        assert!(!edits.is_empty());
1296        for (i, e) in edits.into_iter().enumerate() {
1297            if i == 0 {
1298                d.record(e)
1299            } else {
1300                d.record_joined(e)
1301            }
1302        }
1303        d.set_seed(scale, Some(seed));
1304    }
1305
1306    #[test]
1307    fn a_generated_scale_is_saved_as_its_seed() {
1308        let t = themes();
1309        let mut d = ThemeDraft::new("pop-light");
1310        let e = d.edit(&t, "surface.panel", Some(json!("#f4f0ea"))).unwrap();
1311        d.apply(e.unwrap());
1312        generate(&mut d, &t, "blue", "#8e44ad");
1313        let file = d.to_file(&t, "mine");
1314        // The seed, not the twelve values.
1315        assert!(
1316            !file.tokens.keys().any(|p| p.starts_with("blue.")),
1317            "{:?}",
1318            file.tokens.keys()
1319        );
1320        assert_eq!(file.seeds().0.keys().collect::<Vec<_>>(), ["blue"]);
1321        assert!(file.tokens.contains_key("surface.panel"));
1322        // Loaded as a theme, the file gives the draft's values.
1323        let text = file.to_json_pretty();
1324        let mut with = t.clone();
1325        assert_eq!(with.add_text("mine", &text), Ok(vec![]));
1326        let loaded = with.resolve(&ThemeSpec::new("mine"));
1327        let drafted = t.resolve(&d.spec(&ThemeSpec::new("pop-light")));
1328        for i in 1..=12 {
1329            let path = format!("blue.{i}");
1330            assert_eq!(loaded.color(&path), drafted.color(&path), "{path}");
1331        }
1332        assert_eq!(
1333            loaded.color("blue.contrast"),
1334            drafted.color("blue.contrast")
1335        );
1336        // Imported, it is the same draft, its seed recorded.
1337        let (back, warnings) = ThemeDraft::import(&t, "mine", &text).unwrap();
1338        assert!(warnings.is_empty(), "{warnings:?}");
1339        assert_eq!(back.overrides(), d.overrides());
1340        assert_eq!(back.seed("blue"), d.seed("blue"));
1341    }
1342
1343    #[test]
1344    fn a_seeded_scale_changed_or_undone_is_saved_as_it_is() {
1345        let t = themes();
1346        let mut d = ThemeDraft::new("pop-light");
1347        generate(&mut d, &t, "blue", "#8e44ad");
1348        // A step changed by hand is written; the others still come from
1349        // the seed.
1350        let e = d.edit(&t, "blue.4", Some(json!("#010203"))).unwrap();
1351        d.apply(e.unwrap());
1352        let file = d.to_file(&t, "mine");
1353        assert_eq!(file.tokens["blue.4"].value, json!("#010203"));
1354        assert!(!file.tokens.contains_key("blue.9"));
1355        assert!(file.seeds().0.contains_key("blue"));
1356        let (back, _) = ThemeDraft::import(&t, "mine", &file.to_json_pretty()).unwrap();
1357        assert_eq!(back.overrides(), d.overrides());
1358        // Undone, the seed is not saved: the file gives the base's scale.
1359        d.undo();
1360        while d.undo_group() > 0 {
1361            for _ in 0..d.undo_group() {
1362                d.undo();
1363            }
1364        }
1365        assert!(d.overrides().is_empty());
1366        let file = d.to_file(&t, "mine");
1367        assert!(file.seeds().0.is_empty());
1368        assert!(file.tokens.is_empty(), "{:?}", file.tokens.keys());
1369    }
1370
1371    #[test]
1372    fn a_seed_for_a_scale_the_base_lacks_is_left_out() {
1373        let t = themes();
1374        let (d, warnings) = ThemeDraft::import(
1375            &t,
1376            "x",
1377            r##"{ "$extends": "pop-dark", "$extensions": { "org.egui-pop.seeds": {
1378                "brick": { "seed": "#c0392b" }, "blue": { "seed": "#c0392b", "scheme": "dusk" } } } }"##,
1379        )
1380        .unwrap();
1381        assert!(d.overrides().is_empty());
1382        assert!(d.seeds().is_empty());
1383        assert_eq!(warnings.len(), 2, "{warnings:?}");
1384        assert!(warnings.iter().all(Warning::left_out), "{warnings:?}");
1385    }
1386
1387    #[test]
1388    fn a_scale_is_written_from_a_ramp() {
1389        use crate::Color;
1390        use crate::palette::{Ramp, Scheme};
1391        let themes = Themes::default();
1392        let d = ThemeDraft::new("pop-dark");
1393        let ramp = Ramp::new(Color::from_hex("#27ae60").unwrap(), Scheme::Dark);
1394        let edits = d.scale_edits(&themes, "green", &ramp).unwrap();
1395        assert_eq!(edits.len(), 13);
1396        assert!(d.scale_edits(&themes, "nope", &ramp).is_err());
1397        // The neutral scale has no `contrast`: its twelve steps only.
1398        let grey = Ramp::new(Color::from_hex("#808080").unwrap(), Scheme::Dark);
1399        assert_eq!(d.scale_edits(&themes, "gray", &grey).unwrap().len(), 12);
1400    }
1401
1402    #[test]
1403    fn a_pair_draft_holds_both_variants_edits() {
1404        let t = themes();
1405        let mut d = ThemeDraft::for_theme(&t, "pop-dark");
1406        assert!(d.is_paired());
1407        assert!(!d.editing_second());
1408        let e = d.edit(&t, "danger", Some(json!("#ff4040"))).unwrap();
1409        d.apply(e.unwrap());
1410        let e = d.edit(
1411            &t,
1412            "radius.widget",
1413            Some(json!({ "value": 2, "unit": "px" })),
1414        );
1415        d.apply(e.unwrap().unwrap());
1416        assert!(d.switch());
1417        assert!(d.editing_second());
1418        assert_eq!(d.base(), "pop-light");
1419        assert!(d.overrides().is_empty());
1420        assert!(!d.can_undo());
1421        // Checked against the variant edited's base.
1422        let e = d.edit(&t, "danger", Some(json!("#a00000"))).unwrap();
1423        d.apply(e.unwrap());
1424        assert_eq!(d.counterpart().unwrap().overrides().len(), 2);
1425        // Back: the first variant's edits and history are kept.
1426        assert!(d.switch());
1427        assert_eq!(d.base(), "pop-dark");
1428        assert_eq!(d.value("danger"), Some(&json!("#ff4040")));
1429        assert_eq!(d.history().len(), 2);
1430        d.undo();
1431        assert_eq!(d.overrides().len(), 1);
1432        assert_eq!(
1433            d.counterpart().unwrap().value("danger"),
1434            Some(&json!("#a00000"))
1435        );
1436        let (first, second) = d.variants();
1437        assert_eq!(
1438            (first.base(), second.map(ThemeDraft::base)),
1439            ("pop-dark", Some("pop-light"))
1440        );
1441        // A theme alone has nothing to switch to.
1442        let mut alone = ThemeDraft::for_theme(&t, "pop-high-contrast");
1443        assert!(!alone.is_paired());
1444        assert!(!alone.switch());
1445        assert_eq!(alone.base(), "pop-high-contrast");
1446    }
1447
1448    #[test]
1449    fn a_pair_draft_comes_from_a_spec_and_installs_as_a_pair() {
1450        let t = themes();
1451        // The spec's overrides apply to both, until the counterpart has
1452        // its own.
1453        let spec = ThemeSpec::new("gruvbox-light").override_token("danger", json!("#ff0000"));
1454        let d = ThemeDraft::from_pair_spec(&t, &spec);
1455        assert_eq!(d.base(), "gruvbox-light");
1456        let other = d.counterpart().unwrap();
1457        assert_eq!(other.base(), "gruvbox-dark");
1458        assert_eq!(other.value("danger"), Some(&json!("#ff0000")));
1459        let spec = spec.counterpart_override("info", json!("#0000ff"));
1460        let mut d = ThemeDraft::from_pair_spec(&t, &spec);
1461        assert_eq!(
1462            d.counterpart()
1463                .unwrap()
1464                .overrides()
1465                .keys()
1466                .collect::<Vec<_>>(),
1467            ["info"]
1468        );
1469        // Installed: the theme named first stays first, whichever is
1470        // edited; the variant edited resolves alone.
1471        d.switch();
1472        let installed = d.pair_spec(&ThemeSpec::new("pop-dark").density(crate::Density::Compact));
1473        assert_eq!(installed.base, "gruvbox-light");
1474        assert_eq!(
1475            installed.counterpart,
1476            Counterpart::Theme("gruvbox-dark".into())
1477        );
1478        assert_eq!(installed.density, crate::Density::Compact);
1479        assert_eq!(
1480            installed.counterpart_overrides.as_ref().map(BTreeMap::len),
1481            Some(1)
1482        );
1483        let resolved = t.resolve_counterpart(&installed).unwrap();
1484        assert_eq!(resolved.color("info"), crate::Color::from_hex("#0000ff"));
1485        assert_eq!(d.spec(&installed).base, "gruvbox-dark");
1486        // A counterpart of the same mode is not one; alone, no
1487        // counterpart is installed.
1488        let d = ThemeDraft::from_pair_spec(&t, &ThemeSpec::pair("pop-dark", "gruvbox-dark"));
1489        assert!(!d.is_paired());
1490        assert_eq!(
1491            d.pair_spec(&ThemeSpec::default()).counterpart,
1492            Counterpart::None
1493        );
1494    }
1495
1496    #[test]
1497    fn a_pair_is_saved_as_a_new_pair_and_imported_back() {
1498        let t = themes();
1499        let mut d = ThemeDraft::for_theme(&t, "pop-dark");
1500        let e = d
1501            .edit(&t, "accent.default", Some(json!("#40a0ff")))
1502            .unwrap();
1503        d.apply(e.unwrap());
1504        d.switch();
1505        let e = d
1506            .edit(&t, "accent.default", Some(json!("#2060c0")))
1507            .unwrap();
1508        d.apply(e.unwrap());
1509        generate(&mut d, &t, "blue", "#8e44ad");
1510        // Saved from either variant: the theme named first's file,
1511        // carrying its counterpart.
1512        let file = d.to_file(&t, "ocean");
1513        assert_eq!(file.name, "ocean");
1514        assert_eq!(file.extends.as_deref(), Some("pop-dark"));
1515        assert_eq!(file.tokens["accent.default"].value, json!("#40a0ff"));
1516        let x = file.extensions.as_ref().unwrap();
1517        assert_eq!(x[crate::VARIANT_OF_EXTENSION], json!("ocean-light"));
1518        let inner = file.counterpart_file().unwrap().unwrap();
1519        assert_eq!(inner.name, "ocean-light");
1520        assert_eq!(inner.extends.as_deref(), Some("pop-light"));
1521        assert_eq!(inner.tokens["accent.default"].value, json!("#2060c0"));
1522        assert_eq!(inner.seeds().0.keys().collect::<Vec<_>>(), ["blue"]);
1523        let ix = inner.extensions.as_ref().unwrap();
1524        assert_eq!(ix[crate::VARIANT_OF_EXTENSION], json!("ocean"));
1525        assert!(ix.get(crate::FORMAT_EXTENSION).is_some(), "its own stamp");
1526
1527        // Imported: the same pair, the file's variant edited first.
1528        let text = file.to_json_pretty();
1529        let (back, warnings) = ThemeDraft::import(&t, "ocean", &text).unwrap();
1530        assert!(warnings.is_empty(), "{warnings:?}");
1531        assert!(!back.editing_second());
1532        let (first, second) = back.variants();
1533        let (want_first, want_second) = d.variants();
1534        assert_eq!(first.overrides(), want_first.overrides());
1535        let second = second.unwrap();
1536        assert_eq!(second.base(), "pop-light");
1537        assert_eq!(second.overrides(), want_second.unwrap().overrides());
1538        assert_eq!(second.seed("blue"), want_second.unwrap().seed("blue"));
1539
1540        // Loaded in an application: both themes, a pair.
1541        let mut with = t.clone();
1542        assert_eq!(with.add_text("ocean", &text), Ok(vec![]));
1543        assert_eq!(with.counterpart_of("ocean"), Some("ocean-light"));
1544        assert_eq!(with.counterpart_of("ocean-light"), Some("ocean"));
1545        let light = with.resolve_counterpart(&ThemeSpec::new("ocean")).unwrap();
1546        assert!(light.problems().is_empty(), "{:?}", light.problems());
1547        assert_eq!(
1548            light.color("accent.default"),
1549            crate::Color::from_hex("#2060c0")
1550        );
1551    }
1552
1553    #[test]
1554    fn a_counterpart_that_does_not_fit_is_left_out() {
1555        let t = themes();
1556        for (inner, said) in [
1557            (r#"{ "name": "x-light" }"#, "no `file`"),
1558            (
1559                r#"{ "name": "x-dark", "file": { "$extends": "gruvbox-dark" } }"#,
1560                "both light or both dark",
1561            ),
1562            (
1563                r#"{ "name": "x-light", "file": { "$extends": "nowhere" } }"#,
1564                "nowhere",
1565            ),
1566        ] {
1567            let text = format!(
1568                r#"{{ "$extends": "pop-dark", "$extensions": {{ "{COUNTERPART_EXTENSION}": {inner} }} }}"#
1569            );
1570            let (d, warnings) = ThemeDraft::import(&t, "x", &text).unwrap();
1571            assert!(!d.is_paired(), "{inner}");
1572            assert_eq!(d.base(), "pop-dark");
1573            assert_eq!(warnings.len(), 1, "{warnings:?}");
1574            assert!(warnings[0].to_string().contains(said), "{}", warnings[0]);
1575        }
1576    }
1577
1578    #[test]
1579    fn the_other_variant_is_generated_from_the_one_edited() {
1580        use crate::Color;
1581        use crate::palette::{Scheme, mirror};
1582        let t = themes();
1583        let mut d = ThemeDraft::for_theme(&t, "pop-dark");
1584        assert!(
1585            ThemeDraft::new("pop-dark")
1586                .generate_counterpart(&t)
1587                .is_none()
1588        );
1589        for (path, v) in [
1590            ("surface.panel", json!("#000000")),
1591            ("danger", json!("#1a3a6e")),
1592            ("button.rest.border-color", json!("{border.strong}")),
1593            ("radius.widget", json!({ "value": 2, "unit": "px" })),
1594        ] {
1595            let e = d.edit(&t, path, Some(v)).unwrap().unwrap();
1596            d.apply(e);
1597        }
1598        // A seeded scale, for the dark scheme.
1599        let seed = Seed::new(Color::from_hex("#27ae60").unwrap(), Scheme::Dark);
1600        let ramp = d.seeded_ramp(&t, "green", seed);
1601        for e in d.scale_edits(&t, "green", &ramp).unwrap() {
1602            d.record_joined(e);
1603        }
1604        d.set_seed("green", Some(seed));
1605        // The other variant has a change of its own, not carried over.
1606        d.switch();
1607        let e = d.edit(&t, "info", Some(json!("#00ffff"))).unwrap();
1608        d.apply(e.unwrap());
1609        d.switch();
1610
1611        let g = d.generate_counterpart(&t).unwrap();
1612        assert!(g.skipped.is_empty(), "{:?}", g.skipped);
1613        let to = |path: &str| {
1614            g.edits
1615                .iter()
1616                .find(|e| e.path == path)
1617                .unwrap_or_else(|| panic!("no edit of {path}"))
1618                .to
1619                .clone()
1620        };
1621        assert_eq!(to("surface.panel"), Some(json!("#ffffff")));
1622        let deep = Color::from_hex("#1a3a6e").unwrap();
1623        assert_eq!(to("danger"), Some(json!(mirror(deep).to_hex())));
1624        assert_eq!(
1625            to("button.rest.border-color"),
1626            Some(json!("{border.strong}"))
1627        );
1628        assert_eq!(
1629            to("radius.widget"),
1630            Some(json!({ "value": 2, "unit": "px" }))
1631        );
1632        assert_eq!(to("info"), None, "taken back");
1633        // The seed for the light scheme, its ramp fitted to the other
1634        // variant as generated (white panels).
1635        let light = Seed::new(seed.color, Scheme::Light);
1636        assert_eq!(g.seeds, BTreeMap::from([("green".to_string(), light)]));
1637        let mut fitted = ThemeDraft::new("pop-light");
1638        fitted.preview("surface.panel", Some(json!("#ffffff")));
1639        fitted.preview("danger", to("danger"));
1640        fitted.preview("button.rest.border-color", Some(json!("{border.strong}")));
1641        fitted.preview("radius.widget", Some(json!({ "value": 2, "unit": "px" })));
1642        for (path, value) in fitted.seeded_ramp(&t, "green", light).tokens("green") {
1643            assert_eq!(to(&path), Some(value), "{path}");
1644        }
1645        // Deterministic: the same proposal again.
1646        assert_eq!(d.generate_counterpart(&t), Some(g.clone()));
1647
1648        // Recorded on the other variant: one change, and it becomes the
1649        // edited one's counterpart.
1650        d.switch();
1651        for (i, e) in g.edits.iter().cloned().enumerate() {
1652            if i == 0 {
1653                d.record(e)
1654            } else {
1655                d.record_joined(e)
1656            }
1657        }
1658        assert_eq!(d.undo_group(), g.edits.len());
1659        assert_eq!(d.value("surface.panel"), Some(&json!("#ffffff")));
1660        assert_eq!(d.value("info"), None);
1661        let r = t.resolve(&d.spec(&ThemeSpec::default()));
1662        assert!(r.problems().is_empty(), "{:?}", r.problems());
1663    }
1664}