herogpui-theme 0.14.0

HeroUI design tokens and theming system for HeroGPUI
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
//! Sparse theme documents, applied through [`ThemeBuilder`].
//!
//! A document records only the tokens a caller overrode, the same way v3
//! authors a `[data-theme]` block: the rest derive from the named `base`
//! (`light` or `dark`). Serializing a complete [`Theme`] would freeze every
//! derived hover / soft mix; going through the builder keeps those mixes live.
//!
//! The JSON keys are the [`ThemeBuilder`] methods. `.shots/theme_serde_audit.py`
//! fails if a builder method is added or renamed without a matching key here.

use std::fmt;

use gpui::{px, Hsla, Rgba};
use herogpui_core::{oklcha, Color};
use serde::{Deserialize, Serialize};

use crate::{Appearance, Theme, ThemeBuilder};

/// A sparse override document for a [`Theme`].
///
/// `id` and `base` are required. Every other field is optional and maps onto
/// one [`ThemeBuilder`] method of the same name (`role` is the map `roles`).
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct ThemeDocument {
    /// The theme id, as passed to `Theme::builder`.
    pub id: String,
    /// Which built-in theme the overrides extend: `"light"` or `"dark"`.
    pub base: Appearance,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    /// Overrides `ThemeBuilder::appearance`.
    pub appearance: Option<Appearance>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    /// Overrides `ThemeBuilder::radius`., in pixels.
    pub radius: Option<f32>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    /// Overrides `ThemeBuilder::field_radius`., in pixels.
    pub field_radius: Option<f32>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    /// Overrides `ThemeBuilder::border_width`., in pixels.
    pub border_width: Option<f32>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    /// Overrides `ThemeBuilder::disabled_opacity`.
    pub disabled_opacity: Option<f32>,
    /// The hover cursor for interactive controls, by gpui's `CursorStyle`
    /// variant name (`"PointingHand"` is v3's `cursor: pointer`, `"Arrow"`
    /// the platform default).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cursor_interactive: Option<gpui::CursorStyle>,
    /// The opacity a hovered `Tabs` item drops to; clamped to `0..=1`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tabs_hover_opacity: Option<f32>,
    /// The warm window after the pointer leaves a tooltip during which the
    /// next tip opens without its delay.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tooltip_cooldown_ms: Option<u64>,
    /// How long a `DropdownTrigger::LongPress` waits before it opens.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub long_press_ms: Option<u64>,
    /// The background fade duration of `anim::hover_fade`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub hover_fade_ms: Option<u64>,
    /// `--tooltip-delay`: how long a hover waits before the tip opens.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tooltip_delay_ms: Option<u64>,
    /// `--tooltip-close-delay`: the per-tooltip close delay default.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tooltip_close_delay_ms: Option<u64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    /// Overrides `ThemeBuilder::background`.; a color string (`oklch()`, `oklcha()` or hex).
    pub background: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    /// Overrides `ThemeBuilder::foreground`.; a color string (`oklch()`, `oklcha()` or hex).
    pub foreground: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    /// Overrides `ThemeBuilder::muted`.; a color string (`oklch()`, `oklcha()` or hex).
    pub muted: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    /// Overrides `ThemeBuilder::border`.; a color string (`oklch()`, `oklcha()` or hex).
    pub border: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    /// Overrides `ThemeBuilder::separator`.; a color string (`oklch()`, `oklcha()` or hex).
    pub separator: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    /// Overrides `ThemeBuilder::focus`.; a color string (`oklch()`, `oklcha()` or hex).
    pub focus: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    /// Overrides `ThemeBuilder::link`.; a color string (`oklch()`, `oklcha()` or hex).
    pub link: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    /// Overrides `ThemeBuilder::backdrop`.; a color string (`oklch()`, `oklcha()` or hex).
    pub backdrop: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    /// Overrides `ThemeBuilder::surface`..
    pub surface: Option<ColorPair>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    /// Overrides `ThemeBuilder::surface_levels`..
    pub surface_levels: Option<SurfaceLevels>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    /// Overrides `ThemeBuilder::overlay`..
    pub overlay: Option<ColorPair>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    /// Overrides `ThemeBuilder::segment`..
    pub segment: Option<ColorPair>,
    /// Shorthand for [`ThemeBuilder::accent`]: sets `--accent` and derives
    /// the foreground. Conflicts with `roles.accent`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub accent: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    /// Per-role overrides, applied through `ThemeBuilder::role`.
    pub roles: Option<Roles>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    /// Overrides `ThemeBuilder::field`..
    pub field: Option<ColorPair>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    /// Overrides `ThemeBuilder::field_placeholder`.; a color string.
    pub field_placeholder: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    /// Overrides `ThemeBuilder::field_border`.; a color string.
    pub field_border: Option<String>,
    /// HeroUI's `[data-vibrant-palette="true"]`: reweights the accent,
    /// success, warning and danger `*-soft-foreground` mixes to 92/8.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub vibrant_palette: Option<bool>,
}

/// A background / foreground pair, matching the two-argument builder methods.
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct ColorPair {
    /// Background color string.
    pub background: String,
    /// Foreground color string.
    pub foreground: String,
}

/// `--surface-secondary` and `--surface-tertiary`.
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct SurfaceLevels {
    /// Color string for `--surface-secondary`.
    pub secondary: String,
    /// Color string for `--surface-tertiary`.
    pub tertiary: String,
}

/// The five role slots [`ThemeBuilder::role`] accepts.
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct Roles {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    /// Override for the `default` role.
    pub default: Option<RoleOverride>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    /// Override for the `accent` role.
    pub accent: Option<RoleOverride>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    /// Override for the `success` role.
    pub success: Option<RoleOverride>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    /// Override for the `warning` role.
    pub warning: Option<RoleOverride>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    /// Override for the `danger` role.
    pub danger: Option<RoleOverride>,
}

/// One role's base colour and its on-colour foreground.
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct RoleOverride {
    /// The role's base color string.
    pub color: String,
    /// The on-color foreground string.
    pub foreground: String,
    /// An explicit `*-hover` for the role, in place of the mix-toward-
    /// foreground derivation — the JSON spelling of
    /// [`ThemeBuilder::role_hover`]. Unset keeps the derived shade.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub hover: Option<String>,
}

/// Why a document could not become a [`Theme`].
#[derive(Debug)]
pub enum ThemeDocumentError {
    /// The input was not valid JSON for a [`ThemeDocument`].
    Json(serde_json::Error),
    /// A color string could not be parsed.
    Color {
        /// The document field the value came from.
        field: String,
        /// The rejected color string.
        value: String,
        /// Why the color string was rejected.
        detail: String,
    },
    /// Both `accent` and `roles.accent` were set.
    AccentConflict,
}

impl fmt::Display for ThemeDocumentError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Json(err) => write!(f, "theme document: {err}"),
            Self::Color {
                field,
                value,
                detail,
            } => {
                write!(
                    f,
                    "theme document: {field} value {value:?} is not a colour ({detail})"
                )
            }
            Self::AccentConflict => write!(
                f,
                "theme document: `accent` and `roles.accent` cannot both be set"
            ),
        }
    }
}

impl std::error::Error for ThemeDocumentError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Json(err) => Some(err),
            Self::Color { .. } | Self::AccentConflict => None,
        }
    }
}

impl From<serde_json::Error> for ThemeDocumentError {
    fn from(err: serde_json::Error) -> Self {
        Self::Json(err)
    }
}

impl ThemeDocument {
    /// Parse a JSON document.
    pub fn from_json(json: &str) -> Result<Self, ThemeDocumentError> {
        Ok(serde_json::from_str(json)?)
    }

    /// Parse a JSON document and apply it through [`ThemeBuilder`].
    pub fn theme_from_json(json: &str) -> Result<Theme, ThemeDocumentError> {
        Self::from_json(json)?.to_theme()
    }

    /// Serialize this sparse document. Derived tokens are not written.
    pub fn to_json(&self) -> Result<String, ThemeDocumentError> {
        Ok(serde_json::to_string_pretty(self)?)
    }

    /// Apply the overrides through [`ThemeBuilder`].
    pub fn to_theme(&self) -> Result<Theme, ThemeDocumentError> {
        let base = match self.base {
            Appearance::Light => Theme::light(),
            Appearance::Dark => Theme::dark(),
        };
        let mut builder = Theme::builder(self.id.clone(), base);
        if let Some(appearance) = self.appearance {
            builder = builder.appearance(appearance);
        }
        if let Some(radius) = self.radius {
            builder = builder.radius(px(radius));
        }
        if let Some(radius) = self.field_radius {
            builder = builder.field_radius(px(radius));
        }
        if let Some(width) = self.border_width {
            builder = builder.border_width(px(width));
        }
        if let Some(opacity) = self.disabled_opacity {
            builder = builder.disabled_opacity(opacity);
        }
        if let Some(cursor) = self.cursor_interactive {
            builder = builder.cursor_interactive(cursor);
        }
        if let Some(opacity) = self.tabs_hover_opacity {
            builder = builder.tabs_hover_opacity(opacity);
        }
        if let Some(ms) = self.tooltip_cooldown_ms {
            builder = builder.tooltip_cooldown_ms(ms);
        }
        if let Some(ms) = self.long_press_ms {
            builder = builder.long_press_ms(ms);
        }
        if let Some(ms) = self.hover_fade_ms {
            builder = builder.hover_fade_ms(ms);
        }
        if let Some(ms) = self.tooltip_delay_ms {
            builder = builder.tooltip_delay_ms(ms);
        }
        if let Some(vibrant) = self.vibrant_palette {
            builder = builder.vibrant_palette(vibrant);
        }
        if let Some(ms) = self.tooltip_close_delay_ms {
            builder = builder.tooltip_close_delay_ms(ms);
        }
        builder = apply_color(
            builder,
            "background",
            self.background.as_deref(),
            ThemeBuilder::background,
        )?;
        builder = apply_color(
            builder,
            "foreground",
            self.foreground.as_deref(),
            ThemeBuilder::foreground,
        )?;
        builder = apply_color(builder, "muted", self.muted.as_deref(), ThemeBuilder::muted)?;
        builder = apply_color(
            builder,
            "border",
            self.border.as_deref(),
            ThemeBuilder::border,
        )?;
        builder = apply_color(
            builder,
            "separator",
            self.separator.as_deref(),
            ThemeBuilder::separator,
        )?;
        builder = apply_color(builder, "focus", self.focus.as_deref(), ThemeBuilder::focus)?;
        builder = apply_color(builder, "link", self.link.as_deref(), ThemeBuilder::link)?;
        builder = apply_color(
            builder,
            "backdrop",
            self.backdrop.as_deref(),
            ThemeBuilder::backdrop,
        )?;
        if let Some(pair) = &self.surface {
            builder = builder.surface(
                parse_color("surface.background", &pair.background)?,
                parse_color("surface.foreground", &pair.foreground)?,
            );
        }
        if let Some(levels) = &self.surface_levels {
            builder = builder.surface_levels(
                parse_color("surface_levels.secondary", &levels.secondary)?,
                parse_color("surface_levels.tertiary", &levels.tertiary)?,
            );
        }
        if let Some(pair) = &self.overlay {
            builder = builder.overlay(
                parse_color("overlay.background", &pair.background)?,
                parse_color("overlay.foreground", &pair.foreground)?,
            );
        }
        if let Some(pair) = &self.segment {
            builder = builder.segment(
                parse_color("segment.background", &pair.background)?,
                parse_color("segment.foreground", &pair.foreground)?,
            );
        }
        if self.accent.is_some() && self.roles.as_ref().is_some_and(|r| r.accent.is_some()) {
            return Err(ThemeDocumentError::AccentConflict);
        }
        if let Some(accent) = &self.accent {
            builder = builder.accent(parse_color("accent", accent)?);
        }
        if let Some(roles) = &self.roles {
            builder = apply_role(builder, Color::Default, roles.default.as_ref())?;
            builder = apply_role(builder, Color::Accent, roles.accent.as_ref())?;
            builder = apply_role(builder, Color::Success, roles.success.as_ref())?;
            builder = apply_role(builder, Color::Warning, roles.warning.as_ref())?;
            builder = apply_role(builder, Color::Danger, roles.danger.as_ref())?;
        }
        if let Some(pair) = &self.field {
            builder = builder.field(
                parse_color("field.background", &pair.background)?,
                parse_color("field.foreground", &pair.foreground)?,
            );
        }
        builder = apply_color(
            builder,
            "field_placeholder",
            self.field_placeholder.as_deref(),
            ThemeBuilder::field_placeholder,
        )?;
        builder = apply_color(
            builder,
            "field_border",
            self.field_border.as_deref(),
            ThemeBuilder::field_border,
        )?;
        Ok(builder.build())
    }
}

fn apply_color(
    builder: ThemeBuilder,
    field: &str,
    raw: Option<&str>,
    apply: fn(ThemeBuilder, Hsla) -> ThemeBuilder,
) -> Result<ThemeBuilder, ThemeDocumentError> {
    match raw {
        Some(value) => Ok(apply(builder, parse_color(field, value)?)),
        None => Ok(builder),
    }
}

fn apply_role(
    builder: ThemeBuilder,
    slot: Color,
    role: Option<&RoleOverride>,
) -> Result<ThemeBuilder, ThemeDocumentError> {
    let name = slot.token();
    match role {
        Some(role) => {
            let builder = builder.role(
                slot,
                parse_color(&format!("roles.{name}.color"), &role.color)?,
                parse_color(&format!("roles.{name}.foreground"), &role.foreground)?,
            );
            match &role.hover {
                Some(hover) => {
                    Ok(builder
                        .role_hover(slot, parse_color(&format!("roles.{name}.hover"), hover)?))
                }
                None => Ok(builder),
            }
        }
        None => Ok(builder),
    }
}

/// Colours are CSS `oklch()` / `oklcha()` or `#RGB` / `#RRGGBB` / `#RRGGBBAA`.
fn parse_color(field: &str, raw: &str) -> Result<Hsla, ThemeDocumentError> {
    let value = raw.trim();
    if let Some(hex) = value.strip_prefix('#') {
        return parse_hex(field, value, hex);
    }
    if let Some(inner) = value
        .strip_prefix("oklch(")
        .and_then(|rest| rest.strip_suffix(')'))
    {
        return parse_oklch(field, value, inner);
    }
    if let Some(inner) = value
        .strip_prefix("oklcha(")
        .and_then(|rest| rest.strip_suffix(')'))
    {
        return parse_oklch(field, value, inner);
    }
    Err(ThemeDocumentError::Color {
        field: field.to_owned(),
        value: value.to_owned(),
        detail: "expected oklch(...), oklcha(...) or #hex".into(),
    })
}

fn parse_oklch(field: &str, raw: &str, inner: &str) -> Result<Hsla, ThemeDocumentError> {
    let normalized = inner.replace('/', " ");
    let parts: Vec<&str> = normalized.split_whitespace().collect();
    if parts.len() < 3 || parts.len() > 4 {
        return Err(ThemeDocumentError::Color {
            field: field.to_owned(),
            value: raw.to_owned(),
            detail: "oklch takes L C H, optionally / alpha".into(),
        });
    }
    let l = parse_component(field, raw, parts[0], true)?;
    let c = parse_component(field, raw, parts[1], false)?;
    let h = parse_component(field, raw, parts[2], false)?;
    let a = match parts.get(3) {
        Some(part) => parse_component(field, raw, part, false)?,
        None => 1.0,
    };
    Ok(oklcha(l, c, h, a))
}

fn parse_component(
    field: &str,
    raw: &str,
    part: &str,
    lightness: bool,
) -> Result<f32, ThemeDocumentError> {
    let percent = part.ends_with('%');
    let number = part.trim_end_matches('%');
    // `f32::from_str` also accepts `NaN` and `inf`; neither is a colour.
    let value: f32 = number
        .parse()
        .ok()
        .filter(|v: &f32| v.is_finite())
        .ok_or_else(|| ThemeDocumentError::Color {
            field: field.to_owned(),
            value: raw.to_owned(),
            detail: format!("cannot parse {part:?} as a finite number"),
        })?;
    if percent || (lightness && value > 1.0) {
        Ok(value / 100.0)
    } else {
        Ok(value)
    }
}

fn parse_hex(field: &str, raw: &str, hex: &str) -> Result<Hsla, ThemeDocumentError> {
    let hex = hex.trim();
    let fail = |detail: &str| ThemeDocumentError::Color {
        field: field.to_owned(),
        value: raw.to_owned(),
        detail: detail.into(),
    };
    let nibble = |ch: u8| match ch {
        b'0'..=b'9' => Ok(ch - b'0'),
        b'a'..=b'f' => Ok(ch - b'a' + 10),
        b'A'..=b'F' => Ok(ch - b'A' + 10),
        _ => Err(fail("hex digit is not 0-9A-F")),
    };
    let byte =
        |hi: u8, lo: u8| -> Result<u8, ThemeDocumentError> { Ok((nibble(hi)? << 4) | nibble(lo)?) };
    let bytes = hex.as_bytes();
    let (r, g, b, a) = match bytes {
        [r, g, b] => (nibble(*r)? * 17, nibble(*g)? * 17, nibble(*b)? * 17, 255),
        [r, g, b, a] => (
            nibble(*r)? * 17,
            nibble(*g)? * 17,
            nibble(*b)? * 17,
            nibble(*a)? * 17,
        ),
        [r1, r2, g1, g2, b1, b2] => (byte(*r1, *r2)?, byte(*g1, *g2)?, byte(*b1, *b2)?, 255),
        [r1, r2, g1, g2, b1, b2, a1, a2] => (
            byte(*r1, *r2)?,
            byte(*g1, *g2)?,
            byte(*b1, *b2)?,
            byte(*a1, *a2)?,
        ),
        _ => return Err(fail("hex is #RGB, #RGBA, #RRGGBB or #RRGGBBAA")),
    };
    Ok(Hsla::from(Rgba {
        r: r as f32 / 255.0,
        g: g as f32 / 255.0,
        b: b as f32 / 255.0,
        a: a as f32 / 255.0,
    }))
}

#[cfg(test)]
mod tests {
    use super::*;
    use herogpui_core::{oklch, with_alpha};

    /// `f32::from_str` accepts `NaN`, `inf` and `infinity`; a theme file is
    /// untrusted input, so a non-finite component is a parse error rather
    /// than a colour that poisons every blend derived from it.
    #[test]
    fn non_finite_color_components_are_rejected() {
        for raw in [
            "oklch(NaN 0.1 250)",
            "oklch(0.5 inf 250)",
            "oklch(0.5 0.1 -infinity)",
            "oklch(0.5 0.1 250 / nan)",
        ] {
            let json = format!(r#"{{ "id": "x", "base": "light", "accent": "{raw}" }}"#);
            let err = ThemeDocument::theme_from_json(&json).unwrap_err();
            assert!(
                matches!(err, ThemeDocumentError::Color { .. }),
                "{raw}: {err}"
            );
        }
    }

    #[test]
    fn an_empty_document_is_the_named_base_with_a_new_id() {
        let theme =
            ThemeDocument::theme_from_json(r#"{ "id": "brand", "base": "light" }"#).unwrap();
        let base = Theme::light();
        assert_eq!(theme.id.as_ref(), "brand");
        assert_eq!(theme.appearance, Appearance::Light);
        assert_eq!(theme.colors.background, base.colors.background);
        assert_eq!(theme.colors.accent.color, base.colors.accent.color);
        assert_eq!(theme.layout.radius, base.layout.radius);
    }

    #[test]
    fn overrides_go_through_the_builder_so_derived_mixes_stay_live() {
        let accent = oklch(0.55, 0.23, 295.0);
        let via_builder = Theme::builder("violet", Theme::light())
            .accent(accent)
            .foreground(oklch(0.30, 0.05, 120.0))
            .build();
        let via_json = ThemeDocument::theme_from_json(
            r#"{
                "id": "violet",
                "base": "light",
                "accent": "oklch(0.55 0.23 295)",
                "foreground": "oklch(0.30 0.05 120)"
            }"#,
        )
        .unwrap();
        assert_eq!(
            via_json.colors.accent.color,
            via_builder.colors.accent.color
        );
        assert_eq!(
            via_json.colors.accent.foreground,
            via_builder.colors.accent.foreground
        );
        assert_eq!(via_json.colors.scrollbar, via_builder.colors.scrollbar);
        assert_eq!(
            via_json.colors.scrollbar,
            with_alpha(oklch(0.30, 0.05, 120.0), 0.15)
        );
        assert!((via_json.colors.accent.soft().a - 0.15).abs() < 1e-4);
    }

    #[test]
    fn unknown_keys_are_rejected() {
        let err =
            ThemeDocument::from_json(r##"{ "id": "x", "base": "light", "primary": "#f00" }"##)
                .unwrap_err();
        let message = err.to_string();
        assert!(
            message.contains("primary") || message.contains("unknown"),
            "{message}"
        );
    }

    /// A misspelt role in `roles` is a parse error naming the key, never a
    /// silent recolour of `accent` (the old string builder's fallback).
    #[test]
    fn an_unknown_role_is_rejected() {
        let err = ThemeDocument::from_json(
            r##"{ "id": "x", "base": "light",
                  "roles": { "sucess": { "color": "#0f0", "foreground": "#fff" } } }"##,
        )
        .unwrap_err();
        let message = err.to_string();
        assert!(message.contains("sucess"), "{message}");
        assert!(matches!(err, ThemeDocumentError::Json(_)), "{err:?}");
    }

    #[test]
    fn accent_and_roles_accent_cannot_both_be_set() {
        let err = ThemeDocument::theme_from_json(
            r##"{
                "id": "x",
                "base": "light",
                "accent": "#006FEE",
                "roles": { "accent": { "color": "#006FEE", "foreground": "#fff" } }
            }"##,
        )
        .unwrap_err();
        assert!(matches!(err, ThemeDocumentError::AccentConflict));
    }

    #[test]
    fn hex_and_percent_lightness_parse() {
        let theme = ThemeDocument::theme_from_json(
            r##"{
                "id": "x",
                "base": "dark",
                "background": "#111",
                "link": "oklch(55% 0.2 250 / 0.9)"
            }"##,
        )
        .unwrap();
        assert_eq!(theme.id.as_ref(), "x");
        assert_eq!(theme.appearance, Appearance::Dark);
        assert!((theme.colors.link.a - 0.9).abs() < 1e-4);
    }

    #[test]
    fn customisation_tokens_apply_from_json_through_the_builder() {
        let json = r#"{
                "id": "x",
                "base": "light",
                "tabs_hover_opacity": 0.2,
                "tooltip_cooldown_ms": 250,
                "long_press_ms": 350,
                "hover_fade_ms": 0,
                "tooltip_delay_ms": 50,
                "tooltip_close_delay_ms": 75
            }"#;
        let theme = ThemeDocument::theme_from_json(json).unwrap();
        assert!((theme.layout.tabs_hover_opacity - 0.2).abs() < 1e-6);
        assert_eq!(theme.layout.tooltip_cooldown_ms, 250);
        assert_eq!(theme.layout.long_press_ms, 350);
        assert_eq!(theme.layout.hover_fade_ms, 0);
        assert_eq!(theme.layout.tooltip_delay_ms, 50);
        assert_eq!(theme.layout.tooltip_close_delay_ms, 75);

        // Round-trip the sparse document: serializing must not drop a token
        // and re-parsing must apply the same values.
        let round_tripped = ThemeDocument::from_json(json).unwrap().to_json().unwrap();
        let again = ThemeDocument::theme_from_json(&round_tripped).unwrap();
        assert!((again.layout.tabs_hover_opacity - 0.2).abs() < 1e-6);
        assert_eq!(again.layout.tooltip_cooldown_ms, 250);
        assert_eq!(again.layout.long_press_ms, 350);
        assert_eq!(again.layout.hover_fade_ms, 0);
        assert_eq!(again.layout.tooltip_delay_ms, 50);
        assert_eq!(again.layout.tooltip_close_delay_ms, 75);

        let clamped = ThemeDocument::theme_from_json(
            r#"{ "id": "x", "base": "light", "tabs_hover_opacity": 3.0 }"#,
        )
        .unwrap();
        assert!((clamped.layout.tabs_hover_opacity - 1.0).abs() < 1e-6);
    }

    #[test]
    fn the_vibrant_palette_key_round_trips_and_reaches_the_builder() {
        let json = r#"{ "id": "x", "base": "light", "vibrant_palette": true }"#;
        let theme = ThemeDocument::theme_from_json(json).unwrap();
        assert!(theme.colors.vibrant_palette());

        let round_tripped = ThemeDocument::from_json(json).unwrap().to_json().unwrap();
        assert!(round_tripped.contains("vibrant_palette"));
        let again = ThemeDocument::theme_from_json(&round_tripped).unwrap();
        assert!(again.colors.vibrant_palette());

        // Absent means off, like a document without the attribute.
        let plain = ThemeDocument::theme_from_json(r#"{ "id": "x", "base": "dark" }"#).unwrap();
        assert!(!plain.colors.vibrant_palette());
        assert!(
            !ThemeDocument::from_json(r#"{ "id": "x", "base": "dark" }"#)
                .unwrap()
                .to_json()
                .unwrap()
                .contains("vibrant_palette")
        );
    }

    #[test]
    fn a_role_hover_override_round_trips_and_reaches_the_builder() {
        let json = r##"{
                "id": "x",
                "base": "light",
                "roles": { "accent": { "color": "#006FEE", "foreground": "#fff", "hover": "#0058BE" } }
            }"##;
        let theme = ThemeDocument::theme_from_json(json).unwrap();
        let via_builder = Theme::builder("x", Theme::light())
            .role(
                Color::Accent,
                parse_color("c", "#006FEE").unwrap(),
                parse_color("f", "#fff").unwrap(),
            )
            .role_hover(Color::Accent, parse_color("h", "#0058BE").unwrap())
            .build();
        assert_eq!(
            theme.colors.accent.hover(),
            via_builder.colors.accent.hover()
        );
        assert_eq!(
            theme.colors.accent.hover_override(),
            via_builder.colors.accent.hover_override()
        );

        let round_tripped = ThemeDocument::from_json(json).unwrap().to_json().unwrap();
        assert!(round_tripped.contains("hover"));
        let again = ThemeDocument::theme_from_json(&round_tripped).unwrap();
        assert!(again.colors.accent.hover_override().is_some());

        // Absent means the derived shade, like a role without the key.
        let plain = ThemeDocument::theme_from_json(
            r##"{ "id": "x", "base": "light", "roles": { "accent": { "color": "#006FEE", "foreground": "#fff" } } }"##,
        )
        .unwrap();
        assert_eq!(plain.colors.accent.hover_override(), None);
        assert!(
            !ThemeDocument::from_json(
                r##"{ "id": "x", "base": "light", "roles": { "accent": { "color": "#006FEE", "foreground": "#fff" } } }"##,
            )
            .unwrap()
            .to_json()
            .unwrap()
            .contains("hover")
        );
    }

    #[test]
    fn a_document_round_trips_without_growing_derived_keys() {
        let original =
            ThemeDocument::from_json(r#"{ "id": "brand", "base": "light", "radius": 8 }"#).unwrap();
        let json = original.to_json().unwrap();
        assert!(!json.contains("scrollbar"));
        assert!(!json.contains("soft"));
        let again = ThemeDocument::from_json(&json).unwrap();
        assert_eq!(again.id, "brand");
        assert_eq!(again.radius, Some(8.0));
    }
}