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
//! The `Theme` type plus a builder for custom themes.
//!
//! Mirrors how v3 themes are authored: override a handful of base CSS variables
//! and let every hover / soft / surface-level value derive from them.

use gpui::{Hsla, Pixels, SharedString, WindowAppearance};
use herogpui_core::Color;

use crate::layout::LayoutTheme;
use crate::semantic::{SurfaceColor, ThemeColors};

/// Visual appearance of a theme (`color-scheme`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "lowercase"))]
pub enum Appearance {
    /// The light `color-scheme`.
    Light,
    /// The dark `color-scheme`.
    Dark,
}

/// Collapses the OS appearance onto the two `color-scheme` values v3 has.
///
/// The vibrant variants are macOS `NSAppearanceNameVibrant{Light,Dark}`: they
/// are still light and dark, and forgetting them is the classic bug here
/// because they only appear on a vibrancy-enabled window, never in a test.
/// The match is deliberately exhaustive rather than `_ => Light`, so a future
/// GPUI variant fails the build instead of silently painting light tokens over
/// a dark desktop.
impl From<WindowAppearance> for Appearance {
    fn from(appearance: WindowAppearance) -> Self {
        match appearance {
            WindowAppearance::Light | WindowAppearance::VibrantLight => Self::Light,
            WindowAppearance::Dark | WindowAppearance::VibrantDark => Self::Dark,
        }
    }
}

/// A complete HeroUI v3 theme: semantic colors plus layout tokens.
#[derive(Clone, Debug)]
#[non_exhaustive]
pub struct Theme {
    /// Unique id the theme is registered and activated under.
    pub id: SharedString,
    /// Whether the theme is light or dark.
    pub appearance: Appearance,
    /// Semantic color tokens.
    pub colors: ThemeColors,
    /// Layout tokens: radii, border width, shadows, opacities and timings.
    pub layout: LayoutTheme,
    /// Typed component defaults and named recipes.
    pub components: crate::ComponentThemes,
}

impl Theme {
    /// The default light theme.
    pub fn light() -> Self {
        Self {
            id: "light".into(),
            appearance: Appearance::Light,
            colors: ThemeColors::light(),
            layout: LayoutTheme::light(),
            components: crate::ComponentThemes::default(),
        }
    }

    /// The default dark theme.
    pub fn dark() -> Self {
        Self {
            id: "dark".into(),
            appearance: Appearance::Dark,
            colors: ThemeColors::dark(),
            layout: LayoutTheme::dark(),
            components: crate::ComponentThemes::default(),
        }
    }

    /// Starts a custom theme extending `base` — the equivalent of overriding
    /// CSS variables under a `[data-theme]` selector.
    ///
    /// A JSON document of the same sparse overrides lives behind this crate's
    /// `serde` feature (`ThemeDocument`): it applies through this builder so
    /// derived hover / soft mixes stay live.
    pub fn builder(id: impl Into<SharedString>, base: Theme) -> ThemeBuilder {
        ThemeBuilder { theme: base }.id(id)
    }

    /// Whether this theme's appearance is [`Appearance::Dark`].
    pub fn is_dark(&self) -> bool {
        self.appearance == Appearance::Dark
    }
}

/// Builder for custom themes. `#[must_use]`: a chain whose result is never
/// built is an `unused_must_use` warning.
#[must_use = "a ThemeBuilder does nothing until `build` is called"]
pub struct ThemeBuilder {
    theme: Theme,
}

impl ThemeBuilder {
    /// Component defaults and named recipes, resolved by renderers on every frame.
    pub fn components(mut self, components: crate::ComponentThemes) -> Self {
        self.theme.components = components;
        self
    }

    /// Sets the theme id.
    pub fn id(mut self, id: impl Into<SharedString>) -> Self {
        self.theme.id = id.into();
        self
    }

    /// Sets the theme's [`Appearance`] (`color-scheme`).
    pub fn appearance(mut self, appearance: Appearance) -> Self {
        self.theme.appearance = appearance;
        self
    }

    // -- layout -------------------------------------------------------------

    /// Sets `--radius`; `--field-radius` follows as `radius * 1.5` unless it is
    /// overridden afterwards with [`field_radius`](Self::field_radius).
    pub fn radius(mut self, radius: Pixels) -> Self {
        self.theme.layout.radius = radius;
        self.theme.layout.field_radius = radius * 1.5;
        self
    }

    /// Sets `--field-radius`, overriding the value derived from `--radius`.
    pub fn field_radius(mut self, radius: Pixels) -> Self {
        self.theme.layout.field_radius = radius;
        self
    }

    /// Sets `--border-width`.
    pub fn border_width(mut self, width: Pixels) -> Self {
        self.theme.layout.border_width = width;
        self
    }

    /// Sets `--disabled-opacity`.
    pub fn disabled_opacity(mut self, v: f32) -> Self {
        self.theme.layout.disabled_opacity = v;
        self
    }

    /// Sets the cursor every interactive control shows on hover. Defaults to
    /// [`gpui::CursorStyle::PointingHand`], v3's `cursor: pointer`.
    pub fn cursor_interactive(mut self, cursor: gpui::CursorStyle) -> Self {
        self.theme.layout.cursor_interactive = cursor;
        self
    }

    /// Sets the opacity a hovered `Tabs` item drops to. Finite values are
    /// clamped to `0..=1`; a non-finite value keeps the default `0.7`.
    pub fn tabs_hover_opacity(mut self, v: f32) -> Self {
        self.theme.layout.tabs_hover_opacity = if v.is_finite() {
            v.clamp(0.0, 1.0)
        } else {
            0.7
        };
        self
    }

    /// Sets the warm window after the pointer leaves a tooltip during which
    /// the next tip opens without its delay. A per-tooltip close delay
    /// extends the window via `max()`.
    pub fn tooltip_cooldown_ms(mut self, ms: u64) -> Self {
        self.theme.layout.tooltip_cooldown_ms = ms;
        self
    }

    /// Sets how long a `DropdownTrigger::LongPress` waits before it opens.
    pub fn long_press_ms(mut self, ms: u64) -> Self {
        self.theme.layout.long_press_ms = ms;
        self
    }

    /// Sets the background fade duration of `anim::hover_fade`. Zero resolves
    /// immediately, like reduced motion.
    pub fn hover_fade_ms(mut self, ms: u64) -> Self {
        self.theme.layout.hover_fade_ms = ms;
        self
    }

    /// `--tooltip-delay`: how long a hover waits before the tip opens.
    pub fn tooltip_delay_ms(mut self, ms: u64) -> Self {
        self.theme.layout.tooltip_delay_ms = ms;
        self
    }

    /// `--tooltip-close-delay`: the per-tooltip close delay default.
    pub fn tooltip_close_delay_ms(mut self, ms: u64) -> Self {
        self.theme.layout.tooltip_close_delay_ms = ms;
        self
    }

    // -- base colors --------------------------------------------------------

    /// Sets `--background`.
    pub fn background(mut self, c: Hsla) -> Self {
        self.theme.colors.background = c;
        self
    }

    /// Sets `--foreground`; the scrollbar color is re-derived from it at 15% alpha.
    pub fn foreground(mut self, c: Hsla) -> Self {
        self.theme.colors.foreground = c;
        self.theme.colors.scrollbar = herogpui_core::with_alpha(c, 0.15);
        self
    }

    /// Sets `--muted`.
    pub fn muted(mut self, c: Hsla) -> Self {
        self.theme.colors.muted = c;
        self
    }

    /// Sets `--border`.
    pub fn border(mut self, c: Hsla) -> Self {
        self.theme.colors.border = c;
        self
    }

    /// Sets `--separator`. Defaults to the same value as `--border`.
    pub fn separator(mut self, c: Hsla) -> Self {
        self.theme.colors.separator = c;
        self
    }

    /// Sets `--focus`.
    pub fn focus(mut self, c: Hsla) -> Self {
        self.theme.colors.focus = c;
        self
    }

    /// Sets `--link`.
    pub fn link(mut self, c: Hsla) -> Self {
        self.theme.colors.link = c;
        self
    }

    /// Sets `--backdrop`.
    pub fn backdrop(mut self, c: Hsla) -> Self {
        self.theme.colors.backdrop = c;
        self
    }

    // -- containers ---------------------------------------------------------

    /// Sets `--surface` and `--surface-foreground`.
    pub fn surface(mut self, background: Hsla, foreground: Hsla) -> Self {
        self.theme.colors.surface = SurfaceColor {
            background,
            foreground,
        };
        self
    }

    /// Sets `--surface-secondary` and `--surface-tertiary`.
    pub fn surface_levels(mut self, secondary: Hsla, tertiary: Hsla) -> Self {
        self.theme.colors.surface_secondary = secondary;
        self.theme.colors.surface_tertiary = tertiary;
        self
    }

    /// Sets `--overlay` and `--overlay-foreground`.
    pub fn overlay(mut self, background: Hsla, foreground: Hsla) -> Self {
        self.theme.colors.overlay = SurfaceColor {
            background,
            foreground,
        };
        self
    }

    /// Sets `--segment` and `--segment-foreground`.
    pub fn segment(mut self, background: Hsla, foreground: Hsla) -> Self {
        self.theme.colors.segment = SurfaceColor {
            background,
            foreground,
        };
        self
    }

    // -- roles --------------------------------------------------------------

    /// Sets a role's base value and foreground. Like overriding a CSS
    /// variable, the role's hover and soft mix weights carry over — only the
    /// inputs change. `--focus` tracks `--accent` unless it is overridden
    /// afterwards, and `--field-background` tracks `--default`.
    ///
    /// The role is the typed [`Color`], so a misspelt role cannot compile.
    /// Parse a name from configuration with `name.parse::<Color>()`, which
    /// rejects an unknown name instead of falling back to `accent`.
    pub fn role(mut self, role: Color, color: Hsla, foreground: Hsla) -> Self {
        let slot = self.theme.colors.role_mut(role);
        slot.color = color;
        slot.foreground = foreground;
        match role {
            Color::Default => self.theme.colors.field.background = color,
            Color::Accent => self.theme.colors.focus = color,
            Color::Success | Color::Warning | Color::Danger => {}
        }
        self
    }

    /// HeroUI's opt-in `[data-vibrant-palette="true"]` block
    /// (variables.css:317-330): the accent, success, warning and danger
    /// `*-soft-foreground` mixes become `92%` role over `8%` page foreground in
    /// both appearances, for more saturated soft text with less contrast.
    /// `--default-soft-foreground` is not in that block and is left alone.
    /// Off by default, like the attribute.
    pub fn vibrant_palette(mut self, vibrant: bool) -> Self {
        self.theme.colors.set_vibrant_palette(vibrant);
        self
    }

    /// Sets `--accent` and `--accent-foreground`, deriving the foreground for
    /// readability when it is not supplied.
    pub fn accent(self, color: Hsla) -> Self {
        let fg = herogpui_core::readable_color(color);
        self.role(Color::Accent, color, fg)
    }

    /// Names a role's `*-hover` shade outright, in place of the derived mix.
    ///
    /// Upstream mixes a role toward its own foreground for hover, so a design
    /// system whose hover moves the other way has no weight that expresses it.
    /// Naming it here reaches every component that hovers the role, so
    /// `Variant::Primary` is correct by construction rather than by converting
    /// call sites to a named recipe carrying a
    /// [`crate::ComponentColor::Literal`]. `*-soft-hover` is unaffected.
    ///
    /// The role is the typed [`Color`], as for [`ThemeBuilder::role`].
    pub fn role_hover(mut self, role: Color, hover: Hsla) -> Self {
        let slot = self.theme.colors.role_mut(role);
        *slot = slot.with_hover(hover);
        self
    }

    /// [`ThemeBuilder::role_hover`] for `accent`, the role `Variant::Primary`
    /// and the focus ring resolve.
    pub fn accent_hover(self, hover: Hsla) -> Self {
        self.role_hover(Color::Accent, hover)
    }

    // -- fields -------------------------------------------------------------

    /// Sets `--field-background` and `--field-foreground`.
    pub fn field(mut self, background: Hsla, foreground: Hsla) -> Self {
        self.theme.colors.field.background = background;
        self.theme.colors.field.foreground = foreground;
        self
    }

    /// Sets `--field-placeholder`.
    pub fn field_placeholder(mut self, c: Hsla) -> Self {
        self.theme.colors.field.placeholder = c;
        self
    }

    /// Sets `--field-border`.
    pub fn field_border(mut self, c: Hsla) -> Self {
        self.theme.colors.field.border = c;
        self
    }

    /// Finishes the builder and returns the [`Theme`].
    pub fn build(self) -> Theme {
        self.theme
    }
}

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

    #[test]
    fn the_builder_overrides_the_interactive_cursor_and_nothing_else() {
        let base = Theme::light();
        assert_eq!(
            base.layout.cursor_interactive,
            gpui::CursorStyle::PointingHand
        );

        let theme = Theme::builder("arrow", base.clone())
            .cursor_interactive(gpui::CursorStyle::Arrow)
            .build();

        assert_eq!(theme.layout.cursor_interactive, gpui::CursorStyle::Arrow);
        assert_eq!(theme.layout.radius, base.layout.radius);
        assert!(
            (theme.layout.disabled_opacity - base.layout.disabled_opacity).abs() < f32::EPSILON
        );
        assert_eq!(theme.colors.background, base.colors.background);
    }

    #[test]
    fn customisation_tokens_flow_through_the_builder_and_clamp() {
        let theme = Theme::builder("custom", Theme::light())
            .tabs_hover_opacity(2.0)
            .tooltip_cooldown_ms(250)
            .long_press_ms(350)
            .hover_fade_ms(0)
            .tooltip_delay_ms(50)
            .tooltip_close_delay_ms(75)
            .build();
        assert!((theme.layout.tabs_hover_opacity - 1.0).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);

        let nan = Theme::builder("nan", Theme::light())
            .tabs_hover_opacity(f32::NAN)
            .build();
        assert!((nan.layout.tabs_hover_opacity - 0.7).abs() < f32::EPSILON);
    }

    #[test]
    fn overriding_foreground_recomputes_scrollbar_without_changing_other_tokens() {
        let base = Theme::light();
        let foreground = oklch(0.30, 0.05, 120.0);
        let background = oklch(0.90, 0.01, 286.0);
        let unchanged = (
            base.colors.muted,
            base.colors.border,
            base.colors.separator,
            base.colors.focus,
            base.layout.radius,
            base.layout.disabled_opacity,
        );
        let theme = Theme::builder("brand", base)
            .background(background)
            .foreground(foreground)
            .build();

        assert_eq!(
            (
                theme.colors.scrollbar,
                theme.colors.background,
                theme.colors.muted,
                theme.colors.border,
                theme.colors.separator,
                theme.colors.focus,
                theme.layout.radius,
                theme.layout.disabled_opacity,
            ),
            (
                with_alpha(foreground, 0.15),
                background,
                unchanged.0,
                unchanged.1,
                unchanged.2,
                unchanged.3,
                unchanged.4,
                unchanged.5,
            )
        );
    }

    #[test]
    fn overriding_a_role_keeps_its_soft_semantics() {
        // v3's soft variables are `color-mix`es of the role variables: an
        // override replaces the input, never the weights.
        let theme = Theme::builder("brand", Theme::light())
            .role(
                Color::Success,
                oklch(0.55, 0.18, 145.0),
                oklch(1.0, 0.0, 0.0),
            )
            .build();
        assert!((theme.colors.success.soft().a - 0.15).abs() < 1e-4);
        assert!((theme.colors.success.soft_hover().a - 0.20).abs() < 1e-4);
        assert_eq!(
            theme
                .colors
                .success
                .soft_foreground(theme.colors.foreground),
            mix_oklab(
                theme.colors.success.color,
                theme.colors.foreground,
                60.0 / 140.0
            )
        );
    }

    #[test]
    fn a_default_role_override_keeps_the_half_strength_soft() {
        let theme = Theme::builder("brand", Theme::light())
            .role(
                Color::Default,
                oklch(0.90, 0.01, 286.0),
                oklch(0.20, 0.01, 286.0),
            )
            .build();
        assert!((theme.colors.default.soft().a - 0.50).abs() < 1e-4);
        assert!((theme.colors.default.soft_hover().a - 0.60).abs() < 1e-4);
        assert_eq!(
            theme
                .colors
                .default
                .soft_foreground(theme.colors.foreground),
            theme.colors.default.foreground
        );
    }

    #[test]
    fn the_vibrant_palette_reweights_only_the_soft_foregrounds() {
        // variables.css:317-330 lists accent, danger, warning and success in
        // both the light and the dark block, at 92% role / 8% foreground.
        for base in [Theme::light(), Theme::dark()] {
            let plain = Theme::builder("plain", base.clone()).build();
            let vibrant = Theme::builder("vibrant", base.clone())
                .vibrant_palette(true)
                .build();
            assert!(!plain.colors.vibrant_palette());
            assert!(vibrant.colors.vibrant_palette());

            for role in [Color::Accent, Color::Success, Color::Warning, Color::Danger] {
                let r = vibrant.colors.role(role);
                assert_eq!(
                    r.soft_foreground(vibrant.colors.foreground),
                    mix_oklab(r.color, vibrant.colors.foreground, 0.08),
                    "{role:?} soft-foreground is not the 92/8 vibrant mix"
                );
                assert_ne!(
                    r.soft_foreground(vibrant.colors.foreground),
                    plain
                        .colors
                        .role(role)
                        .soft_foreground(plain.colors.foreground),
                    "{role:?} soft-foreground did not move"
                );
            }

            // `default` is absent from both vibrant blocks: it still resolves
            // to `--default-foreground`.
            assert_eq!(
                vibrant
                    .colors
                    .default
                    .soft_foreground(vibrant.colors.foreground),
                plain.colors.default.foreground
            );

            // Nothing else derived moves.
            for role in Color::ALL {
                let (a, b) = (plain.colors.role(role), vibrant.colors.role(role));
                assert_eq!(a.color, b.color, "{role:?} base moved");
                assert_eq!(a.foreground, b.foreground, "{role:?} foreground moved");
                assert_eq!(a.hover(), b.hover(), "{role:?} hover moved");
                assert_eq!(a.soft(), b.soft(), "{role:?} soft moved");
                assert_eq!(a.soft_hover(), b.soft_hover(), "{role:?} soft-hover moved");
            }
            assert_eq!(plain.colors.foreground, vibrant.colors.foreground);
            assert_eq!(plain.colors.background, vibrant.colors.background);
            assert_eq!(plain.colors.focus, vibrant.colors.focus);
            assert_eq!(plain.colors.surface.hover(), vibrant.colors.surface.hover());
            assert_eq!(plain.colors.field.hover(), vibrant.colors.field.hover());

            // The flag is an opt-in that can be turned back off.
            let off = Theme::builder("off", base)
                .vibrant_palette(true)
                .vibrant_palette(false)
                .build();
            assert!(!off.colors.vibrant_palette());
            assert_eq!(
                off.colors.accent.soft_foreground(off.colors.foreground),
                plain.colors.accent.soft_foreground(plain.colors.foreground)
            );
        }
    }
}