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 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
57const RADIUS_FULL: Pixels = px(9999.);
61
62const PLOT_APPEAR: Duration = Duration::from_millis(1000);
68
69fn plot_appear_easing(t: f32) -> f32 {
76 1. - (1. - t).powi(4)
77}
78
79const SCROLLBAR_IDLE: Duration = Duration::from_secs(2);
81const SCROLLBAR_ENTER: Duration = Duration::from_millis(300);
83const SCROLLBAR_EXIT: Duration = Duration::from_millis(500);
85const SCROLLBAR_EXPAND: Duration = Duration::from_millis(300);
87
88const MOBILE_SCROLLBAR_THUMB_WIDTH: Pixels = px(3.);
92const MOBILE_SCROLLBAR_THUMB_INSET: Pixels = px(2.);
95const SCROLLBAR_THUMB_HOVER_WIDTH: Pixels = px(6.);
98const SCROLLBAR_THUMB_ACTIVE_WIDTH: Pixels = px(8.);
100const SCROLLBAR_THUMB_INSET: Pixels = px(4.);
102
103fn 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
126fn 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#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
145pub struct Theme {
146 pub colors: ThemeColor,
147 #[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 pub font_family: SharedString,
161 pub font_size: Pixels,
163 pub mono_font_family: SharedString,
166 pub mono_font_size: Pixels,
168 pub radius: Pixels,
170 pub radius_lg: Pixels,
172 pub shadow: bool,
173 #[serde(default = "default_true")]
181 pub focus_ring: bool,
182 pub transparent: Hsla,
183 #[serde(alias = "scrollbar_show")]
185 pub scrollbar_mode: ScrollbarMode,
186 #[serde(skip)]
188 pub notification: NotificationSettings,
189 pub list: ListSettings,
191 pub sheet: SheetSettings,
193 #[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 #[inline(always)]
223 pub fn global(cx: &App) -> &Theme {
224 cx.global::<Theme>()
225 }
226
227 #[inline(always)]
235 pub fn global_mut(cx: &mut App) -> &mut Theme {
236 cx.global_mut::<Theme>()
237 }
238
239 pub fn update<R>(cx: &mut App, edit: impl FnOnce(&mut Theme) -> R) -> R {
273 Self::edit(cx, false, edit)
274 }
275
276 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 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 #[inline(always)]
317 pub fn is_dark(&self) -> bool {
318 self.mode.is_dark()
319 }
320
321 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 pub fn sync_system_appearance(window: Option<&mut Window>, cx: &mut App) {
332 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 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 pub fn set_scrollbar_mode(mode: ScrollbarMode, cx: &mut App) {
355 Self::update(cx, |theme| theme.scrollbar_mode = mode);
356 }
357
358 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 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 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 #[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 #[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 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 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 pub fn radius_full(&self) -> Pixels {
529 if self.radius.is_zero() {
530 px(0.)
531 } else {
532 RADIUS_FULL
533 }
534 }
535
536 pub fn radius_2xl(&self) -> Pixels {
541 self.radius * 2.5
542 }
543
544 pub fn radius_3xl(&self) -> Pixels {
546 self.radius * 3.
547 }
548
549 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 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 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 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 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 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 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 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 #[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 #[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 #[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 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 #[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 #[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 #[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 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}