Skip to main content

wgpui_component/theme/
mod.rs

1use crate::{
2    highlighter::HighlightTheme, list::ListSettings, notification::NotificationSettings,
3    scroll::ScrollbarMode, sheet::SheetSettings,
4};
5use schemars::JsonSchema;
6use serde::{Deserialize, Serialize};
7use std::{
8    ops::{Deref, DerefMut},
9    rc::Rc,
10    sync::Arc,
11    time::Duration,
12};
13use wgpui::{
14    App, Global, Hsla, IsZero as _, Pixels, SharedString, Window, WindowAppearance,
15    prelude::FluentBuilder as _, px,
16};
17pub use wgpui_base::{
18    ColorTokens, RadiusTokens, SemanticThemeTokens, ShadowTokens, SpacingTokens, TextStyleToken,
19    TypographyTokens,
20};
21
22mod color;
23mod motion;
24mod registry;
25mod schema;
26mod theme_color;
27
28pub use color::*;
29pub use motion::*;
30pub use registry::*;
31pub use schema::*;
32pub use theme_color::*;
33
34pub fn init(cx: &mut App) {
35    registry::init(cx);
36
37    // Ensure theme is loaded directly on startup for WASM compatibility
38    Theme::change(ThemeMode::Light, None, cx);
39    Theme::sync_scrollbar_appearance(cx);
40}
41
42pub trait ActiveTheme {
43    fn theme(&self) -> &Theme;
44}
45
46impl ActiveTheme for App {
47    #[inline(always)]
48    fn theme(&self) -> &Theme {
49        Theme::global(self)
50    }
51}
52
53fn default_true() -> bool {
54    true
55}
56
57/// The radius that rounds a shape as far as its own size allows, giving a
58/// circle or a pill. Any value past half the shorter side is clamped by the
59/// renderer, so this is simply "as round as it goes".
60const RADIUS_FULL: Pixels = px(9999.);
61
62/// How long a chart's data takes to draw in the first time it is painted.
63///
64/// The mainstream chart libraries agree on about a second: ECharts, Chart.js
65/// and Highcharts all default to 1000 ms, ApexCharts to 800 ms and Recharts to
66/// 1500 ms.
67const PLOT_APPEAR: Duration = Duration::from_millis(1000);
68
69/// The curve a chart's data draws in on: Chart.js' default `easeOutQuart`.
70///
71/// Not the design system's enter curve. That one is an exponential ease-out
72/// built for a popover, done nine-tenths of the way in the first quarter, which
73/// makes a second of drawing in read as a flash. The quartic still leads with
74/// most of the motion but leaves the data a visible glide into place.
75fn plot_appear_easing(t: f32) -> f32 {
76    1. - (1. - t).powi(4)
77}
78
79/// How long the scrollbar stays visible after the last scroll, drag, or hover.
80const SCROLLBAR_IDLE: Duration = Duration::from_secs(2);
81/// How long the scrollbar takes to appear.
82const SCROLLBAR_ENTER: Duration = Duration::from_millis(300);
83/// How long the scrollbar takes to fade away once the idle hold expires.
84const SCROLLBAR_EXIT: Duration = Duration::from_millis(500);
85/// How long the thumb takes to reach its hovered or resting width.
86const SCROLLBAR_EXPAND: Duration = Duration::from_millis(300);
87
88/// The resting thumb width on iOS and Android, matching the 3pt indicator
89/// those platforms draw. Hover and drag keep Base's desktop widths, so a
90/// grabbed thumb still grows under the finger.
91const MOBILE_SCROLLBAR_THUMB_WIDTH: Pixels = px(3.);
92/// How far the resting thumb sits from the edge on iOS and Android. Base's
93/// desktop inset leaves a 3px thumb floating too far from the edge.
94const MOBILE_SCROLLBAR_THUMB_INSET: Pixels = px(2.);
95/// Base's resting thumb width, restated so the hovered thumb keeps it when
96/// the mobile resting width would otherwise cascade into it.
97const SCROLLBAR_THUMB_HOVER_WIDTH: Pixels = px(6.);
98/// Base's dragged thumb width, restated for the same reason.
99const SCROLLBAR_THUMB_ACTIVE_WIDTH: Pixels = px(8.);
100/// Base's hovered and dragged thumb inset, restated for the same reason.
101const SCROLLBAR_THUMB_INSET: Pixels = px(4.);
102
103/// The plot hover motion this design system projects onto Base.
104///
105/// A pointer chases the cursor across neighbouring data, so it has to arrive
106/// well within the time the cursor takes to reach the next datum: ECharts moves
107/// its axis pointer over 200 ms on an exponential ease-out, which is most of
108/// the way there in the first third. The fast tier as a critically damped
109/// response lands in the same place, and the tolerance is sub-pixel so the
110/// spring rests once nothing visible moves. The hover fades on the same tier.
111/// The data draws in over [`PLOT_APPEAR`] on [`plot_appear_easing`].
112fn plot_motion(motion: &MotionTokens) -> wgpui_base::PlotMotion {
113    wgpui_base::PlotMotion::default()
114        .with_pointer(wgpui_base::Spring::new(motion.duration_fast).with_epsilon(0.1))
115        .with_enter(
116            wgpui_base::motion::Transition::new(motion.duration_fast)
117                .easing(motion.easing_enter.clone()),
118        )
119        .with_exit(
120            wgpui_base::motion::Transition::new(motion.duration_fast)
121                .easing(motion.easing_exit.clone()),
122        )
123        .with_appear(wgpui_base::motion::Transition::new(PLOT_APPEAR).ease(plot_appear_easing))
124}
125
126/// The scrollbar motion this design system projects onto Base.
127///
128/// Scrolling and track hover reveal a scrollbar by fading it in place. In hover
129/// mode, pointing at the thumb slides it in from the nearest edge as it fades.
130fn scrollbar_motion(mode: ScrollbarMode) -> wgpui_base::ScrollbarMotion {
131    wgpui_base::ScrollbarMotion::default()
132        .with_idle(SCROLLBAR_IDLE)
133        .with_enter(SCROLLBAR_ENTER)
134        .with_exit(SCROLLBAR_EXIT)
135        .with_expand(SCROLLBAR_EXPAND)
136        .with_entrance(wgpui_base::ScrollbarEntrance::Fade)
137        .with_thumb_hover_entrance(match mode {
138            ScrollbarMode::Scrolling | ScrollbarMode::Always => wgpui_base::ScrollbarEntrance::Fade,
139            ScrollbarMode::Hover => wgpui_base::ScrollbarEntrance::SlideAndFade,
140        })
141}
142
143/// The global theme configuration.
144#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
145pub struct Theme {
146    pub colors: ThemeColor,
147    /// Component-specific resolved tokens retained for legacy compatibility.
148    ///
149    /// New application-owned presentation should use [`Self::semantic_tokens`]
150    /// rather than extending this legacy surface.
151    #[serde(default)]
152    pub tokens: ThemeTokens,
153    pub highlight_theme: Arc<HighlightTheme>,
154    pub light_theme: Rc<ThemeConfig>,
155    pub dark_theme: Rc<ThemeConfig>,
156
157    pub mode: ThemeMode,
158    /// The application UI family; `.SystemUIFont` resolves to the OS default.
159    /// Explicit application and theme families override the system default.
160    pub font_family: SharedString,
161    /// The base font size for the application, default is 16px.
162    pub font_size: Pixels,
163    /// The application monospace family; `.SystemMonospaceFont` resolves to
164    /// the OS default. Explicit application and theme families remain overrides.
165    pub mono_font_family: SharedString,
166    /// The monospace font size for the application, default is 13px.
167    pub mono_font_size: Pixels,
168    /// Radius for the general elements.
169    pub radius: Pixels,
170    /// Radius for the large elements, e.g.: Dialog, Notification border radius.
171    pub radius_lg: Pixels,
172    pub shadow: bool,
173    /// Whether focused controls draw a ring outside their border, default true.
174    ///
175    /// The ring is painted outside the element, so any ancestor that clips its
176    /// content will cut it off. An application whose layout clips heavily can
177    /// turn it off here: focused controls then show only their tinted border,
178    /// or a 1px ring just inside their edge when they have none. Neither costs
179    /// space or can be clipped.
180    #[serde(default = "default_true")]
181    pub focus_ring: bool,
182    pub transparent: Hsla,
183    /// Show the scrollbar mode, default: Scrolling
184    #[serde(alias = "scrollbar_show")]
185    pub scrollbar_mode: ScrollbarMode,
186    /// The notification setting.
187    #[serde(skip)]
188    pub notification: NotificationSettings,
189    /// The list settings.
190    pub list: ListSettings,
191    /// The sheet settings.
192    pub sheet: SheetSettings,
193    /// Semantic motion policy for styled components.
194    #[serde(skip)]
195    pub motion: MotionTokens,
196}
197
198impl Default for Theme {
199    fn default() -> Self {
200        Self::from(&ThemeColor::default())
201    }
202}
203
204impl Deref for Theme {
205    type Target = ThemeColor;
206
207    fn deref(&self) -> &Self::Target {
208        &self.colors
209    }
210}
211
212impl DerefMut for Theme {
213    fn deref_mut(&mut self) -> &mut Self::Target {
214        &mut self.colors
215    }
216}
217
218impl Global for Theme {}
219
220impl Theme {
221    /// Returns the global theme reference
222    #[inline(always)]
223    pub fn global(cx: &App) -> &Theme {
224        cx.global::<Theme>()
225    }
226
227    /// Returns the global theme mutable reference.
228    ///
229    /// An edit made through this reference reaches nothing but the field it
230    /// touches: [`Theme::tokens`] keeps the colors it had, and so does the
231    /// Base projection until [`Theme::sync_base`] rebuilds it. Prefer
232    /// [`Theme::update`], which does both after the edit and refreshes every
233    /// window. Keep this for an edit that must not trigger any of that.
234    #[inline(always)]
235    pub fn global_mut(cx: &mut App) -> &mut Theme {
236        cx.global_mut::<Theme>()
237    }
238
239    /// Edits the global theme and keeps every copy of it in step.
240    ///
241    /// The theme holds the same colors twice — [`Theme::colors`] as solid
242    /// colors and [`Theme::tokens`] as renderable backgrounds that may carry a
243    /// gradient — and the Base layer keeps a projection of its own for the
244    /// scrollbar and resize handles. Editing one of them through
245    /// [`Theme::global_mut`] leaves the others where they were, so a sidebar
246    /// can paint its text from the new colors and its background from the old
247    /// tokens. This is the write path that cannot drift:
248    ///
249    /// ```ignore
250    /// Theme::update(cx, |theme| {
251    ///     theme.colors = my_colors;
252    ///     theme.radius = px(8.);
253    /// });
254    /// ```
255    ///
256    /// After the closure returns, a color edited on `colors` replaces its
257    /// token (dropping any gradient — the edit asked for that solid color), a
258    /// token edited on its own writes its solid color back to `colors`, an
259    /// untouched field keeps the gradient a theme file gave it, the Base
260    /// projection is rebuilt, and every window is refreshed.
261    ///
262    /// A field the closure sets to the value it already had counts as
263    /// untouched: assigning a whole palette keeps the gradient of any field
264    /// whose color did not change. Edit the token to replace one.
265    ///
266    /// Setting [`Theme::mode`] loads that mode's registered theme, the same
267    /// as [`Theme::change`]; that load replaces the colors, so edit colors in
268    /// a second `update` after switching mode rather than in the same closure.
269    /// [`Theme::apply_config`] installs a theme file and switches to its mode
270    /// in one step, and the closure may go on editing after it — nothing is
271    /// loaded over its edits.
272    pub fn update<R>(cx: &mut App, edit: impl FnOnce(&mut Theme) -> R) -> R {
273        Self::edit(cx, false, edit)
274    }
275
276    /// The write path behind [`Theme::update`] and [`Theme::change`].
277    ///
278    /// `reload_mode` loads the current mode's registered theme even when the
279    /// mode did not change, which is what `change` promises: a caller that
280    /// swapped [`Theme::light_theme`] or [`Theme::dark_theme`] and then asks
281    /// for that mode gets the new theme applied.
282    fn edit<R>(cx: &mut App, reload_mode: bool, edit: impl FnOnce(&mut Theme) -> R) -> R {
283        let theme = Theme::global_mut(cx);
284        let colors_before = theme.colors;
285        let tokens_before = theme.tokens;
286        let mode_before = theme.mode;
287        let light_before = theme.light_theme.clone();
288        let dark_before = theme.dark_theme.clone();
289
290        let result = edit(theme);
291
292        theme
293            .tokens
294            .reconcile(&mut theme.colors, &colors_before, &tokens_before);
295        let mode_changed = theme.mode != mode_before;
296        let (config, config_before) = if theme.mode.is_dark() {
297            (&theme.dark_theme, &dark_before)
298        } else {
299            (&theme.light_theme, &light_before)
300        };
301        // `apply_config` registers the file it applies and switches to its
302        // mode, so a mode change that arrives with a newly registered config
303        // has already loaded it. Loading it again would put the file's radius,
304        // fonts and colors back over whatever the closure edited after it.
305        let installed_by_edit = mode_changed && !Rc::ptr_eq(config, config_before);
306        if (mode_changed || reload_mode) && !installed_by_edit {
307            let config = config.clone();
308            theme.apply_config(&config);
309        }
310        Self::sync_base(cx);
311        cx.refresh_windows();
312        result
313    }
314
315    /// Returns true if the theme is dark.
316    #[inline(always)]
317    pub fn is_dark(&self) -> bool {
318        self.mode.is_dark()
319    }
320
321    /// Returns the current theme name.
322    pub fn theme_name(&self) -> &SharedString {
323        if self.is_dark() {
324            &self.dark_theme.name
325        } else {
326            &self.light_theme.name
327        }
328    }
329
330    /// Sync the theme with the system appearance
331    pub fn sync_system_appearance(window: Option<&mut Window>, cx: &mut App) {
332        // Better use window.appearance() for avoid error on Linux.
333        // https://github.com/longbridge/gpui-kit/issues/104
334        let appearance = window
335            .as_ref()
336            .map(|window| window.appearance())
337            .unwrap_or_else(|| cx.window_appearance());
338
339        Self::change(appearance, window, cx);
340    }
341
342    /// Sync the Scrollbar showing behavior with the system
343    pub fn sync_scrollbar_appearance(cx: &mut App) {
344        let mode = if cx.should_auto_hide_scrollbars() {
345            ScrollbarMode::Scrolling
346        } else {
347            ScrollbarMode::Hover
348        };
349        Self::set_scrollbar_mode(mode, cx);
350    }
351
352    /// Changes the scrollbar display mode through [`Theme::update`], which
353    /// projects it onto the Base scrollbar and refreshes every window.
354    pub fn set_scrollbar_mode(mode: ScrollbarMode, cx: &mut App) {
355        Self::update(cx, |theme| theme.scrollbar_mode = mode);
356    }
357
358    /// Change the theme mode.
359    ///
360    /// Loads the registered theme for `mode` — even when `mode` is already
361    /// current, so a caller that swapped [`Theme::light_theme`] or
362    /// [`Theme::dark_theme`] sees the new theme — through [`Theme::update`],
363    /// which keeps every copy of the theme in step and refreshes every
364    /// window. `window` is accepted for compatibility; every window is
365    /// refreshed either way, so it is not read.
366    pub fn change(mode: impl Into<ThemeMode>, _window: Option<&mut Window>, cx: &mut App) {
367        let mode = mode.into();
368        if !cx.has_global::<Theme>() {
369            let mut theme = Theme::default();
370            theme.light_theme = ThemeRegistry::global(cx).default_light_theme().clone();
371            theme.dark_theme = ThemeRegistry::global(cx).default_dark_theme().clone();
372            cx.set_global(theme);
373        }
374
375        Self::edit(cx, true, |theme| theme.mode = mode);
376    }
377
378    /// This theme projected onto the Base layer, which owns the scrollbar and
379    /// resize handles and reads the semantic tokens.
380    fn base_theme(&self) -> wgpui_base::Theme {
381        wgpui_base::Theme {
382            appearance: if self.mode.is_dark() {
383                wgpui_base::ThemeAppearance::Dark
384            } else {
385                wgpui_base::ThemeAppearance::Light
386            },
387            tokens: self.semantic_tokens(),
388            scrollbar: wgpui_base::ScrollbarTheme::new()
389                .with_mode(self.scrollbar_mode)
390                .with_motion(scrollbar_motion(self.scrollbar_mode))
391                .with_styles(
392                    wgpui_base::ScrollbarStyles::default()
393                        .track(|style| style.bg(self.scrollbar))
394                        .track_hover(|style| style.bg(self.scrollbar))
395                        .track_active(|style| style.bg(self.scrollbar).border_color(self.border))
396                        .thumb(|style| {
397                            style
398                                .bg(self.tokens.scrollbar_thumb)
399                                .radius(self.radius)
400                                .when(wgpui_base::is_mobile(), |style| {
401                                    style
402                                        .width(MOBILE_SCROLLBAR_THUMB_WIDTH)
403                                        .inset(MOBILE_SCROLLBAR_THUMB_INSET)
404                                        .radius(RADIUS_FULL)
405                                })
406                        })
407                        .thumb_hover(|style| {
408                            style
409                                .bg(self.tokens.scrollbar_thumb_hover)
410                                .radius(self.radius)
411                                .when(wgpui_base::is_mobile(), |style| {
412                                    style
413                                        .width(SCROLLBAR_THUMB_HOVER_WIDTH)
414                                        .inset(SCROLLBAR_THUMB_INSET)
415                                })
416                        })
417                        .thumb_active(|style| {
418                            style
419                                .bg(self.tokens.scrollbar_thumb_hover)
420                                .radius(self.radius)
421                                .when(wgpui_base::is_mobile(), |style| {
422                                    style
423                                        .width(SCROLLBAR_THUMB_ACTIVE_WIDTH)
424                                        .inset(SCROLLBAR_THUMB_INSET)
425                                })
426                        }),
427                ),
428            resizable: wgpui_base::ResizableTheme {
429                handle: Some(self.border),
430                active_handle: Some(self.drag_border),
431            },
432            plot: wgpui_base::PlotTheme::new().with_motion(plot_motion(&self.motion)),
433        }
434    }
435
436    /// Push the current theme down to the Base layer.
437    ///
438    /// The Base layer holds its own copy of the theme — the semantic tokens
439    /// plus the scrollbar and resize-handle styles — because it paints those
440    /// without going through `gpui-component`. [`Theme::change`] refreshes that
441    /// copy, but writing to the theme's public fields directly does not, so a
442    /// scrollbar keeps painting with the radius and colors it was last given.
443    ///
444    /// [`Theme::update`] and [`Theme::change`] call this after their edits.
445    /// After editing through [`Theme::global_mut`], call it yourself, then
446    /// refresh the windows.
447    ///
448    /// It rebuilds the Base theme from scratch, so any style written straight
449    /// onto the Base global is replaced. It does not touch [`Theme::tokens`].
450    pub fn sync_base(cx: &mut App) {
451        let theme = Theme::global(cx).clone();
452        let base_theme = theme.base_theme();
453        cx.set_global(base_theme);
454        crate::text::install_text_view_defaults(&theme, cx);
455    }
456
457    /// Get the input background color.
458    ///
459    /// For dark, use a transparent color mixed with the input border: `cx.theme().input`,
460    /// otherwise use the `cx.theme().background` color.
461    #[inline]
462    pub fn input_background(&self) -> Hsla {
463        if self.is_dark() {
464            self.input.mix_oklab(self.transparent, 0.3)
465        } else {
466            self.background
467        }
468    }
469
470    /// Get the editor background color, if not set, use the input background color.
471    #[inline]
472    pub(crate) fn editor_background(&self) -> Hsla {
473        self.highlight_theme
474            .style
475            .editor_background
476            .unwrap_or_else(|| self.input_background())
477    }
478
479    /// Returns a snapshot of the semantic design tokens represented by this
480    /// theme. The snapshot is computed from the legacy public fields so direct
481    /// mutations of those fields are reflected immediately.
482    pub fn semantic_tokens(&self) -> SemanticThemeTokens {
483        SemanticThemeTokens {
484            colors: self.color_tokens(),
485            radius: self.radius_tokens(),
486            spacing: self.spacing_tokens(),
487            typography: self.typography_tokens(),
488            shadow: self.shadow_tokens(),
489        }
490    }
491
492    /// Returns the styled layer's semantic motion policy.
493    pub fn motion_tokens(&self) -> &MotionTokens {
494        &self.motion
495    }
496
497    pub fn color_tokens(&self) -> ColorTokens {
498        ColorTokens {
499            background: self.background,
500            foreground: self.foreground,
501            surface: self.popover,
502            surface_foreground: self.popover_foreground,
503            primary: self.primary,
504            primary_foreground: self.primary_foreground,
505            secondary: self.secondary,
506            secondary_foreground: self.secondary_foreground,
507            muted: self.muted,
508            muted_foreground: self.muted_foreground,
509            accent: self.accent,
510            accent_foreground: self.accent_foreground,
511            destructive: self.danger,
512            destructive_foreground: self.danger_foreground,
513            border: self.border,
514            input: self.input,
515            ring: self.ring,
516            selection: self.selection,
517        }
518    }
519
520    /// The radius of a shape that reads as a circle or a pill — an avatar, a
521    /// slider thumb, a badge dot, a pill tab.
522    ///
523    /// A theme whose [`Theme::radius`] is zero squares these off too, so one
524    /// setting governs the whole UI instead of leaving a handful of
525    /// permanently round elements behind. Use it in place of
526    /// [`wgpui::Styled::rounded_full`], or reach for
527    /// [`crate::ThemeStyled::rounded_full_style`] when styling an element.
528    pub fn radius_full(&self) -> Pixels {
529        if self.radius.is_zero() {
530            px(0.)
531        } else {
532            RADIUS_FULL
533        }
534    }
535
536    /// Returns the next surface radius above the existing `xl` theme tier.
537    ///
538    /// Larger surface tiers derive from the same application-controlled base
539    /// radius, so adjusting or squaring the theme updates every tier together.
540    pub fn radius_2xl(&self) -> Pixels {
541        self.radius * 2.5
542    }
543
544    /// Returns the surface radius above [`Self::radius_2xl`].
545    pub fn radius_3xl(&self) -> Pixels {
546        self.radius * 3.
547    }
548
549    /// Returns the surface radius above [`Self::radius_3xl`].
550    pub fn radius_4xl(&self) -> Pixels {
551        self.radius * 3.5
552    }
553
554    pub fn radius_tokens(&self) -> RadiusTokens {
555        RadiusTokens {
556            none: px(0.),
557            sm: self.radius / 2.,
558            md: self.radius,
559            lg: self.radius_lg,
560            xl: self.radius * 2.,
561            full: self.radius_full(),
562        }
563    }
564
565    pub fn spacing_tokens(&self) -> SpacingTokens {
566        SpacingTokens::default()
567    }
568
569    pub fn typography_tokens(&self) -> TypographyTokens {
570        let mut tokens = TypographyTokens::default();
571        tokens.sans = self.font_family.clone();
572        tokens.mono = self.mono_font_family.clone();
573        tokens.md.size = self.font_size;
574        tokens.mono_md.size = self.mono_font_size;
575        tokens
576    }
577
578    pub fn shadow_tokens(&self) -> ShadowTokens {
579        if self.shadow {
580            ShadowTokens::elevations(self.transparent.alpha(0.18))
581        } else {
582            ShadowTokens::default()
583        }
584    }
585
586    /// Applies the subset of semantic tokens representable by the legacy
587    /// theme. Scale-only spacing and elevation details have no legacy storage;
588    /// legacy components therefore keep their existing behavior.
589    pub fn apply_semantic_tokens(&mut self, tokens: &SemanticThemeTokens) {
590        let colors = tokens.colors;
591        self.background = colors.background;
592        self.foreground = colors.foreground;
593        self.popover = colors.surface;
594        self.popover_foreground = colors.surface_foreground;
595        self.primary = colors.primary;
596        self.primary_foreground = colors.primary_foreground;
597        self.secondary = colors.secondary;
598        self.secondary_foreground = colors.secondary_foreground;
599        self.muted = colors.muted;
600        self.muted_foreground = colors.muted_foreground;
601        self.accent = colors.accent;
602        self.accent_foreground = colors.accent_foreground;
603        self.danger = colors.destructive;
604        self.danger_foreground = colors.destructive_foreground;
605        self.border = colors.border;
606        self.input = colors.input;
607        self.ring = colors.ring;
608
609        self.tokens.background = colors.background.into();
610        self.tokens.popover = colors.surface.into();
611        self.tokens.primary = colors.primary.into();
612        self.tokens.secondary = colors.secondary.into();
613        self.tokens.muted = colors.muted.into();
614        self.tokens.accent = colors.accent.into();
615        self.tokens.danger = colors.destructive.into();
616
617        self.radius = tokens.radius.md;
618        self.radius_lg = tokens.radius.lg;
619        self.font_family = tokens.typography.sans.clone();
620        self.mono_font_family = tokens.typography.mono.clone();
621        self.font_size = tokens.typography.md.size;
622        self.mono_font_size = tokens.typography.mono_md.size;
623        self.shadow = !tokens.shadow.sm.is_empty()
624            || !tokens.shadow.md.is_empty()
625            || !tokens.shadow.lg.is_empty();
626    }
627
628    /// Resolves a standalone semantic configuration over the current legacy
629    /// theme without mutating either value.
630    pub fn resolve_semantic_config(&self, config: &SemanticThemeConfig) -> SemanticThemeTokens {
631        let mut tokens = self.semantic_tokens();
632        config.apply_to(&mut tokens);
633        tokens
634    }
635
636    /// Applies the legacy-representable part of a standalone semantic config
637    /// and returns the complete resolved snapshot for application-owned UI.
638    pub fn apply_semantic_config(&mut self, config: &SemanticThemeConfig) -> SemanticThemeTokens {
639        let tokens = self.resolve_semantic_config(config);
640        self.apply_semantic_tokens(&tokens);
641        tokens
642    }
643
644    /// Parses and applies a standalone `{ "tokens": ... }` semantic theme file.
645    pub fn apply_semantic_config_str(
646        &mut self,
647        content: &str,
648    ) -> anyhow::Result<SemanticThemeTokens> {
649        let config = serde_json::from_str::<SemanticThemeConfigFile>(content)?;
650        Ok(self.apply_semantic_config(&config.tokens))
651    }
652}
653
654#[cfg(test)]
655mod semantic_token_tests {
656    use wgpui::{Hsla, IsZero as _, px};
657
658    use super::{RADIUS_FULL, Theme};
659
660    #[test]
661    fn semantic_colors_are_a_live_projection_of_legacy_fields() {
662        let mut theme = Theme::default();
663        let primary = Hsla::default().alpha(0.42);
664        theme.primary = primary;
665
666        assert_eq!(theme.color_tokens().primary, primary);
667        assert_eq!(theme.semantic_tokens().colors.primary, primary);
668    }
669
670    #[test]
671    fn applying_semantic_tokens_only_updates_generic_legacy_colors() {
672        let mut theme = Theme::default();
673        let component_color = theme.button_primary;
674        let mut tokens = theme.semantic_tokens();
675        tokens.colors.primary = Hsla::default().alpha(0.25);
676        tokens.colors.destructive = Hsla::default().alpha(0.75);
677        tokens.radius.md = px(10.);
678
679        theme.apply_semantic_tokens(&tokens);
680
681        assert_eq!(theme.primary, tokens.colors.primary);
682        assert_eq!(theme.tokens.primary.color, tokens.colors.primary);
683        assert_eq!(theme.danger, tokens.colors.destructive);
684        assert_eq!(theme.radius, px(10.));
685        assert_eq!(theme.button_primary, component_color);
686    }
687
688    #[test]
689    fn square_themes_square_off_pills_and_circles() {
690        let mut theme = Theme::default();
691        assert_eq!(theme.radius_full(), RADIUS_FULL);
692        assert_eq!(theme.radius_tokens().full, RADIUS_FULL);
693
694        // An application asking for square corners gets them everywhere, not
695        // just on the elements whose radius happens to come from `radius`.
696        theme.radius = px(0.);
697        assert_eq!(theme.radius_full(), px(0.));
698        assert_eq!(theme.radius_tokens().full, px(0.));
699    }
700
701    #[test]
702    fn larger_surface_radii_follow_the_theme_radius() {
703        let mut theme = Theme::default();
704        assert!(theme.radius_tokens().xl < theme.radius_2xl());
705        assert!(theme.radius_2xl() < theme.radius_3xl());
706        assert!(theme.radius_3xl() < theme.radius_4xl());
707
708        theme.radius = px(10.);
709        assert_eq!(theme.radius_2xl(), px(25.));
710        assert_eq!(theme.radius_3xl(), px(30.));
711        assert_eq!(theme.radius_4xl(), px(35.));
712
713        theme.radius = px(0.);
714        assert_eq!(theme.radius_2xl(), px(0.));
715        assert_eq!(theme.radius_3xl(), px(0.));
716        assert_eq!(theme.radius_4xl(), px(0.));
717    }
718
719    #[test]
720    fn base_projection_carries_a_square_radius_to_the_scrollbar() {
721        let mut theme = Theme::default();
722        assert!(!theme.base_theme().tokens.radius.md.is_zero());
723
724        // The scrollbar paints from the Base layer's copy of the theme, so a
725        // square theme has to reach it or the thumb stays a pill.
726        theme.radius = px(0.);
727        assert!(theme.base_theme().tokens.radius.md.is_zero());
728    }
729
730    #[test]
731    fn disabled_legacy_shadows_project_to_empty_elevations() {
732        let mut theme = Theme::default();
733        theme.shadow = false;
734
735        let shadows = theme.shadow_tokens();
736        assert!(shadows.sm.is_empty());
737        assert!(shadows.md.is_empty());
738        assert!(shadows.lg.is_empty());
739    }
740}
741
742impl From<&ThemeColor> for Theme {
743    fn from(colors: &ThemeColor) -> Self {
744        Theme {
745            mode: ThemeMode::default(),
746            transparent: Hsla::transparent_black(),
747            font_family: ".SystemUIFont".into(),
748            font_size: px(16.),
749            mono_font_family: wgpui_base::TypographyTokens::default().mono,
750            mono_font_size: px(13.),
751            radius: px(6.),
752            radius_lg: px(8.),
753            shadow: true,
754            focus_ring: true,
755            scrollbar_mode: ScrollbarMode::default(),
756            notification: NotificationSettings::default(),
757            list: ListSettings::default(),
758            colors: *colors,
759            tokens: ThemeTokens::from(colors),
760            light_theme: Rc::new(ThemeConfig::default()),
761            dark_theme: Rc::new(ThemeConfig::default()),
762            highlight_theme: HighlightTheme::default_light(),
763            sheet: SheetSettings::default(),
764            motion: MotionTokens::default(),
765        }
766    }
767}
768
769#[derive(
770    Debug,
771    Clone,
772    Copy,
773    Default,
774    PartialEq,
775    PartialOrd,
776    Eq,
777    Ord,
778    Hash,
779    Serialize,
780    Deserialize,
781    JsonSchema,
782)]
783#[serde(rename_all = "snake_case")]
784pub enum ThemeMode {
785    #[default]
786    Light,
787    Dark,
788}
789
790impl ThemeMode {
791    #[inline(always)]
792    pub fn is_dark(&self) -> bool {
793        matches!(self, Self::Dark)
794    }
795
796    /// Return lower_case theme name: `light`, `dark`.
797    pub fn name(&self) -> &'static str {
798        match self {
799            ThemeMode::Light => "light",
800            ThemeMode::Dark => "dark",
801        }
802    }
803}
804
805impl From<WindowAppearance> for ThemeMode {
806    fn from(appearance: WindowAppearance) -> Self {
807        match appearance {
808            WindowAppearance::Dark | WindowAppearance::VibrantDark => Self::Dark,
809            WindowAppearance::Light | WindowAppearance::VibrantLight => Self::Light,
810        }
811    }
812}
813
814#[cfg(test)]
815mod update_tests {
816    use super::*;
817    use wgpui::{TestAppContext, linear_color_stop, linear_gradient};
818
819    fn gradient(from: Hsla, to: Hsla) -> ThemeToken {
820        ThemeToken::new(
821            from,
822            linear_gradient(135., linear_color_stop(from, 0.), linear_color_stop(to, 1.)),
823        )
824    }
825
826    /// A color edited on `colors` reaches the token the components paint
827    /// with, and the Base projection the scrollbar paints with.
828    #[wgpui::test]
829    fn editing_colors_updates_the_tokens_and_the_base_projection(cx: &mut TestAppContext) {
830        cx.update(|cx| {
831            init(cx);
832            let sidebar = wgpui::rgb(0x123456).into();
833            let primary = wgpui::rgb(0xabcdef).into();
834
835            Theme::update(cx, |theme| {
836                theme.sidebar = sidebar;
837                theme.colors.primary = primary;
838                theme.radius = px(0.);
839            });
840
841            let theme = Theme::global(cx);
842            assert_eq!(theme.tokens.sidebar.color, sidebar);
843            assert_eq!(theme.tokens.sidebar.background, sidebar.into());
844            assert_eq!(theme.tokens.primary.color, primary);
845            assert_eq!(wgpui_base::Theme::global(cx).tokens.colors.primary, primary);
846            assert!(wgpui_base::Theme::global(cx).tokens.radius.md.is_zero());
847        });
848    }
849
850    /// Replacing the whole `colors` struct, as an application installing its
851    /// own palette does, rewrites every token.
852    #[wgpui::test]
853    fn replacing_the_palette_rewrites_every_token(cx: &mut TestAppContext) {
854        cx.update(|cx| {
855            init(cx);
856            let palette = *ThemeColor::dark();
857
858            Theme::update(cx, |theme| theme.colors = palette);
859
860            assert_eq!(Theme::global(cx).tokens, ThemeTokens::from(palette));
861        });
862    }
863
864    /// A gradient a theme file gave a token survives edits to other fields;
865    /// editing that field's color replaces the gradient with the solid color.
866    #[wgpui::test]
867    fn a_gradient_survives_until_its_own_color_is_edited(cx: &mut TestAppContext) {
868        cx.update(|cx| {
869            init(cx);
870            let from = wgpui::rgb(0x4f46e5).into();
871            let to = wgpui::rgb(0x06b6d4).into();
872            let token = gradient(from, to);
873            Theme::update(cx, |theme| theme.tokens.primary = token);
874            // The token's solid color is written back, so text painted with
875            // `theme.primary` matches the gradient's representative color.
876            assert_eq!(Theme::global(cx).primary, from);
877
878            Theme::update(cx, |theme| theme.secondary = wgpui::rgb(0x222222).into());
879            assert_eq!(Theme::global(cx).tokens.primary, token);
880
881            let solid = wgpui::rgb(0x999999).into();
882            Theme::update(cx, |theme| theme.primary = solid);
883            assert_eq!(Theme::global(cx).tokens.primary, solid.into());
884        });
885    }
886
887    /// Setting `mode` through `update` loads that mode's theme, the same as
888    /// `change`, and the Base projection follows.
889    #[wgpui::test]
890    fn setting_the_mode_loads_that_modes_theme(cx: &mut TestAppContext) {
891        cx.update(|cx| {
892            init(cx);
893            let light_background = Theme::global(cx).background;
894
895            Theme::update(cx, |theme| theme.mode = ThemeMode::Dark);
896
897            let theme = Theme::global(cx);
898            assert!(theme.is_dark());
899            assert_ne!(theme.background, light_background);
900            assert_eq!(theme.tokens.background.color, theme.background);
901            assert_eq!(
902                wgpui_base::Theme::global(cx).appearance,
903                wgpui_base::ThemeAppearance::Dark
904            );
905            assert_eq!(
906                wgpui_base::Theme::global(cx).tokens.colors.background,
907                theme.background
908            );
909        });
910    }
911
912    /// Applying a theme file through `update` keeps the gradients it
913    /// declares: the config sets `colors` and `tokens` to one color, which is
914    /// not a conflict to resolve.
915    #[wgpui::test]
916    fn applying_a_config_keeps_its_gradients(cx: &mut TestAppContext) {
917        cx.update(|cx| {
918            init(cx);
919            let config: ThemeConfig = serde_json::from_value(serde_json::json!({
920                "name": "Gradient",
921                "mode": "light",
922                "colors": {
923                    "primary": "#4F46E5",
924                    "primary.background": "linear-gradient(135deg, #4F46E5, #06B6D4)"
925                }
926            }))
927            .unwrap();
928            let config = Rc::new(config);
929
930            Theme::update(cx, |theme| theme.apply_config(&config));
931
932            let theme = Theme::global(cx);
933            assert_eq!(theme.tokens.primary.color, theme.primary);
934            assert_ne!(
935                theme.tokens.primary.background,
936                theme.primary.into(),
937                "the gradient must survive the reconcile"
938            );
939        });
940    }
941
942    /// `apply_config` switches to the file's mode itself, so `edit` must not
943    /// load that mode's theme a second time over what the closure went on to
944    /// set — the same closure has to land the same result from either mode.
945    #[wgpui::test]
946    fn edits_after_applying_a_config_of_the_other_mode_survive(cx: &mut TestAppContext) {
947        cx.update(|cx| {
948            init(cx);
949            let config: ThemeConfig = serde_json::from_value(serde_json::json!({
950                "name": "Rounded Dark",
951                "mode": "dark",
952                "radius": 12,
953                "colors": { "primary": "#4F46E5" }
954            }))
955            .unwrap();
956            let config = Rc::new(config);
957            assert!(!Theme::global(cx).is_dark());
958
959            let red = wgpui::red();
960            Theme::update(cx, |theme| {
961                theme.apply_config(&config);
962                theme.radius = px(0.);
963                theme.colors.primary = red;
964            });
965
966            let theme = Theme::global(cx);
967            assert!(theme.is_dark());
968            assert!(Rc::ptr_eq(&theme.dark_theme, &config));
969            assert_eq!(theme.radius, px(0.), "the file's radius must not reload");
970            assert_eq!(theme.primary, red);
971            assert_eq!(theme.tokens.primary, red.into());
972            assert_eq!(wgpui_base::Theme::global(cx).tokens.colors.primary, red);
973        });
974    }
975
976    #[wgpui::test]
977    fn update_returns_the_closure_result(cx: &mut TestAppContext) {
978        cx.update(|cx| {
979            init(cx);
980            let radius = Theme::update(cx, |theme| {
981                theme.radius = px(6.);
982                theme.radius
983            });
984            assert_eq!(radius, px(6.));
985        });
986    }
987}
988
989#[cfg(test)]
990mod base_theme_projection_tests {
991    use super::*;
992    use wgpui::TestAppContext;
993
994    #[wgpui::test]
995    fn base_theme_tracks_initialization_and_mode_changes(cx: &mut TestAppContext) {
996        cx.update(|cx| {
997            init(cx);
998            assert_styled_projection(cx);
999
1000            Theme::change(ThemeMode::Dark, None, cx);
1001            assert_styled_projection(cx);
1002
1003            Theme::set_scrollbar_mode(ScrollbarMode::Always, cx);
1004            assert_eq!(Theme::global(cx).scrollbar_mode, ScrollbarMode::Always);
1005            assert_eq!(
1006                wgpui_base::Theme::global(cx).scrollbar.mode(),
1007                wgpui_base::ScrollbarMode::Always
1008            );
1009            assert_styled_projection(cx);
1010        });
1011    }
1012
1013    #[wgpui::test]
1014    fn scrollbar_motion_is_owned_here_and_projected_onto_base(cx: &mut TestAppContext) {
1015        cx.update(|cx| {
1016            init(cx);
1017
1018            // Base itself ships none of this timing.
1019            let bare = wgpui_base::ScrollbarMotion::default();
1020            assert_eq!(bare.enter(), Duration::ZERO);
1021            assert_eq!(bare.exit(), Duration::ZERO);
1022            assert_eq!(bare.expand(), Duration::ZERO);
1023
1024            Theme::set_scrollbar_mode(ScrollbarMode::Scrolling, cx);
1025            let motion = wgpui_base::Theme::global(cx).scrollbar.motion();
1026            assert_eq!(motion.idle(), SCROLLBAR_IDLE);
1027            assert_eq!(motion.enter(), SCROLLBAR_ENTER);
1028            assert_eq!(motion.exit(), SCROLLBAR_EXIT);
1029            assert_eq!(motion.expand(), SCROLLBAR_EXPAND);
1030            assert_eq!(
1031                motion.entrance(),
1032                wgpui_base::ScrollbarEntrance::Fade,
1033                "scroll-revealed scrollbars fade in without sliding"
1034            );
1035
1036            Theme::set_scrollbar_mode(ScrollbarMode::Hover, cx);
1037            let motion = wgpui_base::Theme::global(cx).scrollbar.motion();
1038            assert_eq!(motion.entrance(), wgpui_base::ScrollbarEntrance::Fade);
1039            assert_eq!(
1040                motion.thumb_hover_entrance(),
1041                wgpui_base::ScrollbarEntrance::SlideAndFade
1042            );
1043        });
1044    }
1045
1046    #[test]
1047    fn default_motion_tokens_form_a_coherent_semantic_scale() {
1048        let theme = Theme::default();
1049        let motion = theme.motion_tokens();
1050
1051        assert_eq!(motion.duration_instant, Duration::ZERO);
1052        assert!(motion.duration_fast < motion.duration_normal);
1053        assert!(motion.duration_normal < motion.duration_slow);
1054        assert!(motion.distance_short.0 < motion.distance_medium.0);
1055        assert_eq!(motion.easing_enter.sample(0.0), 0.0);
1056        assert_eq!(motion.easing_enter.sample(1.0), 1.0);
1057    }
1058
1059    fn assert_styled_projection(cx: &App) {
1060        let theme = Theme::global(cx);
1061        let base = wgpui_base::Theme::global(cx);
1062
1063        assert_eq!(base.tokens, theme.semantic_tokens());
1064        assert_eq!(base.scrollbar.mode(), theme.scrollbar_mode);
1065        assert_eq!(
1066            base.scrollbar.motion(),
1067            scrollbar_motion(theme.scrollbar_mode)
1068        );
1069        assert_eq!(base.resizable.handle, Some(theme.border));
1070        assert_eq!(base.resizable.active_handle, Some(theme.drag_border));
1071    }
1072
1073    #[wgpui::test]
1074    fn default_component_palettes_match_base_light_and_dark_tokens(cx: &mut wgpui::TestAppContext) {
1075        fn assert_close(left: ColorTokens, right: ColorTokens) {
1076            macro_rules! color {
1077                ($field:ident) => {
1078                    assert!(
1079                        (left.$field.h - right.$field.h).abs() < 1e-6
1080                            && (left.$field.s - right.$field.s).abs() < 1e-6
1081                            && (left.$field.l - right.$field.l).abs() < 1e-6
1082                            && (left.$field.a - right.$field.a).abs() < 1e-6,
1083                        "{} differs: {:?} != {:?}",
1084                        stringify!($field),
1085                        left.$field,
1086                        right.$field
1087                    );
1088                };
1089            }
1090            color!(background);
1091            color!(foreground);
1092            color!(surface);
1093            color!(surface_foreground);
1094            color!(primary);
1095            color!(primary_foreground);
1096            color!(secondary);
1097            color!(secondary_foreground);
1098            color!(muted);
1099            color!(muted_foreground);
1100            color!(accent);
1101            color!(accent_foreground);
1102            color!(destructive);
1103            color!(destructive_foreground);
1104            color!(border);
1105            color!(input);
1106            color!(ring);
1107            color!(selection);
1108        }
1109
1110        cx.update(crate::init);
1111        cx.update(|cx| {
1112            assert_close(Theme::global(cx).color_tokens(), ColorTokens::light());
1113        });
1114
1115        cx.update(|cx| Theme::change(ThemeMode::Dark, None, cx));
1116        cx.update(|cx| {
1117            assert_close(Theme::global(cx).color_tokens(), ColorTokens::dark());
1118        });
1119    }
1120}