1use std::borrow::Cow;
8use std::fmt;
9use std::sync::OnceLock;
10
11use iced::font::Weight;
12use iced::theme::Palette;
13use iced::theme::palette::{Extended, Pair, Secondary, deviate};
14use iced::widget::container;
15use iced::{Background, Border, Color, Element, Font, Theme, color};
16
17static BASE_FONT: OnceLock<Font> = OnceLock::new();
18
19pub fn set_font(font: Font) -> bool {
26 BASE_FONT.set(font).is_ok()
27}
28
29pub fn font() -> Font {
31 BASE_FONT.get().copied().unwrap_or(Font::DEFAULT)
32}
33
34pub fn semibold() -> Font {
36 Font {
37 weight: Weight::Semibold,
38 ..font()
39 }
40}
41
42#[cfg(any(feature = "card", feature = "dialog"))]
45pub(crate) fn heading<'a>(
46 content: impl iced::widget::text::IntoFragment<'a>,
47 size: f32,
48) -> iced::widget::Text<'a> {
49 iced::widget::text(content).size(size).font(semibold())
50}
51
52#[cfg(any(feature = "card", feature = "dialog"))]
54pub(crate) fn supporting<'a>(
55 content: impl iced::widget::text::IntoFragment<'a>,
56) -> iced::widget::Text<'a> {
57 iced::widget::text(content)
58 .size(text_size::SM)
59 .style(|theme: &Theme| iced::widget::text::Style {
60 color: Some(Tokens::of(theme).muted_foreground),
61 })
62}
63
64pub mod radius {
66 pub const SM: f32 = 4.0;
67 pub const MD: f32 = 6.0;
68 pub const LG: f32 = 8.0;
69 pub const FULL: f32 = 9999.0;
70}
71
72pub mod space {
74 pub const XS: f32 = 4.0;
75 pub const SM: f32 = 8.0;
76 pub const MD: f32 = 12.0;
77 pub const LG: f32 = 16.0;
78 pub const XL: f32 = 24.0;
79}
80
81pub mod text_size {
83 pub const XS: f32 = 12.0;
84 pub const SM: f32 = 14.0;
85 pub const MD: f32 = 16.0;
86 pub const LG: f32 = 18.0;
87}
88
89const POPOVER_LIFT: f32 = 0.06;
92
93#[derive(Debug, Clone, Copy, PartialEq)]
95pub struct Tokens {
96 pub background: Color,
97 pub foreground: Color,
98 pub popover: Color,
102 pub muted: Color,
103 pub muted_foreground: Color,
104 pub accent: Color,
105 pub accent_foreground: Color,
106 pub border: Color,
107 pub ring: Color,
108 pub primary: Color,
109 pub primary_foreground: Color,
110 pub secondary: Color,
111 pub secondary_foreground: Color,
112 pub destructive: Color,
113 pub destructive_foreground: Color,
114 pub destructive_text: Color,
118 pub success: Color,
119 pub warning: Color,
120 pub is_dark: bool,
121}
122
123impl Tokens {
124 pub fn of(theme: &Theme) -> Self {
126 let ext = theme.extended_palette();
127 let background = ext.background.base.color;
128 let foreground = ext.background.base.text;
129
130 let popover = if ext.is_dark {
131 mix(background, foreground, POPOVER_LIFT)
132 } else {
133 background
134 };
135
136 Self {
137 background,
138 foreground,
139 popover,
140 muted: ext.background.weak.color,
141 muted_foreground: mix(foreground, background, 0.4),
142 accent: ext.secondary.weak.color,
143 accent_foreground: on(ext.secondary.weak.color),
144 border: ext.background.strong.color,
145 ring: Color {
146 a: 0.5,
147 ..ext.primary.base.color
148 },
149 primary: ext.primary.base.color,
150 primary_foreground: on(ext.primary.base.color),
151 secondary: ext.secondary.base.color,
152 secondary_foreground: on(ext.secondary.base.color),
153 destructive: ext.danger.base.color,
154 destructive_foreground: on(ext.danger.base.color),
155 destructive_text: readable(ext.danger.base.color, background),
156 success: ext.success.base.color,
157 warning: ext.warning.base.color,
158 is_dark: ext.is_dark,
159 }
160 }
161
162 pub fn disabled_field(&self) -> Color {
164 mix(self.background, self.muted, 0.5)
165 }
166}
167
168#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
172pub enum Tone {
173 #[default]
174 Primary,
175 Neutral,
176 Success,
177 Warning,
178 Destructive,
179}
180
181impl Tone {
182 pub const ALL: [Tone; 5] = [
183 Tone::Primary,
184 Tone::Neutral,
185 Tone::Success,
186 Tone::Warning,
187 Tone::Destructive,
188 ];
189
190 pub fn colour(self, tokens: &Tokens) -> Color {
192 match self {
193 Tone::Primary => tokens.primary,
194 Tone::Neutral => tokens.muted_foreground,
195 Tone::Success => tokens.success,
196 Tone::Warning => tokens.warning,
197 Tone::Destructive => tokens.destructive,
198 }
199 }
200}
201
202pub fn light() -> Theme {
204 Config::light().build()
205}
206
207pub fn dark() -> Theme {
209 Config::dark().build()
210}
211
212#[derive(Debug, Clone, PartialEq)]
229pub struct Config {
230 name: Cow<'static, str>,
231 background: Color,
232 foreground: Color,
233 primary: Color,
234 secondary: Option<Color>,
235 accent: Option<Color>,
236 destructive: Color,
237 success: Color,
238 warning: Color,
239 border: Option<Color>,
240}
241
242impl Config {
243 pub fn light() -> Self {
245 Self {
246 name: Cow::Borrowed("Cube Light"),
247 background: color!(0xffffff),
248 foreground: color!(0x09090b),
249 primary: color!(0x18181b),
250 secondary: None,
251 accent: None,
252 destructive: color!(0xdc2626),
253 success: color!(0x16a34a),
254 warning: color!(0xd97706),
255 border: None,
256 }
257 }
258
259 pub fn dark() -> Self {
261 Self {
262 name: Cow::Borrowed("Cube Dark"),
263 background: color!(0x09090b),
264 foreground: color!(0xfafafa),
265 primary: color!(0xfafafa),
266 secondary: None,
267 accent: None,
268 destructive: color!(0xdc2626),
269 success: color!(0x22c55e),
270 warning: color!(0xf59e0b),
271 border: None,
272 }
273 }
274
275 pub fn name(mut self, name: impl Into<Cow<'static, str>>) -> Self {
277 self.name = name.into();
278 self
279 }
280
281 pub fn primary(mut self, colour: Color) -> Self {
283 self.primary = colour;
284 self
285 }
286
287 pub fn secondary(mut self, colour: Color) -> Self {
289 self.secondary = Some(colour);
290 self
291 }
292
293 pub fn accent(mut self, colour: Color) -> Self {
296 self.accent = Some(colour);
297 self
298 }
299
300 pub fn destructive(mut self, colour: Color) -> Self {
302 self.destructive = colour;
303 self
304 }
305
306 pub fn success(mut self, colour: Color) -> Self {
307 self.success = colour;
308 self
309 }
310
311 pub fn warning(mut self, colour: Color) -> Self {
312 self.warning = colour;
313 self
314 }
315
316 pub fn background(mut self, colour: Color) -> Self {
319 self.background = colour;
320 self
321 }
322
323 pub fn foreground(mut self, colour: Color) -> Self {
325 self.foreground = colour;
326 self
327 }
328
329 pub fn border(mut self, colour: Color) -> Self {
332 self.border = Some(colour);
333 self
334 }
335
336 pub fn palette(&self) -> Palette {
338 Palette {
339 background: self.background,
340 text: self.foreground,
341 primary: self.primary,
342 success: self.success,
343 warning: self.warning,
344 danger: self.destructive,
345 }
346 }
347
348 pub fn extended(&self) -> Extended {
352 let mut extended = Extended::generate(self.palette());
353 let shade = extended.background.weak.color;
354 let secondary = self.secondary.unwrap_or(shade);
355 let accent = self.accent.unwrap_or(shade);
356 let strong = deviate(secondary, 0.1);
357
358 extended.secondary = Secondary {
359 base: Pair::new(secondary, on(secondary)),
360 weak: Pair::new(accent, on(accent)),
361 strong: Pair::new(strong, on(strong)),
362 };
363 if let Some(border) = self.border {
364 extended.background.strong = Pair::new(border, self.foreground);
365 }
366 extended
367 }
368
369 pub fn build(&self) -> Theme {
371 let extended = self.extended();
372 Theme::custom_with_fn(self.name.clone(), self.palette(), move |_| extended)
373 }
374}
375
376pub const SWATCH_SIZE: f32 = 12.0;
378
379pub struct Swatch<'a> {
382 colour: Box<dyn Fn(&Theme) -> Color + 'a>,
383 size: f32,
384}
385
386impl fmt::Debug for Swatch<'_> {
387 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
388 f.debug_struct("Swatch").field("size", &self.size).finish()
389 }
390}
391
392pub fn swatch<'a>(colour: impl Fn(&Theme) -> Color + 'a) -> Swatch<'a> {
402 Swatch {
403 colour: Box::new(colour),
404 size: SWATCH_SIZE,
405 }
406}
407
408pub fn swatch_color<'a>(colour: Color) -> Swatch<'a> {
410 swatch(move |_| colour)
411}
412
413impl Swatch<'_> {
414 pub fn size(mut self, size: f32) -> Self {
416 self.size = size;
417 self
418 }
419
420 pub fn diameter(&self) -> f32 {
422 self.size
423 }
424
425 pub fn colour(&self, theme: &Theme) -> Color {
427 (self.colour)(theme)
428 }
429}
430
431impl<'a, Message: 'a> From<Swatch<'a>> for Element<'a, Message> {
432 fn from(swatch: Swatch<'a>) -> Self {
433 let Swatch { colour, size } = swatch;
434 container(iced::widget::space())
435 .width(size)
436 .height(size)
437 .style(move |theme| container::Style {
438 background: Some(Background::Color(colour(theme))),
439 border: Border {
440 radius: radius::FULL.into(),
441 ..Border::default()
442 },
443 ..container::Style::default()
444 })
445 .into()
446 }
447}
448
449pub fn mix(a: Color, b: Color, t: f32) -> Color {
451 let t = t.clamp(0.0, 1.0);
452 Color {
453 r: a.r + (b.r - a.r) * t,
454 g: a.g + (b.g - a.g) * t,
455 b: a.b + (b.b - a.b) * t,
456 a: a.a + (b.a - a.a) * t,
457 }
458}
459
460pub fn on(background: Color) -> Color {
463 let (dark, light) = (color!(0x09090b), color!(0xfafafa));
464 if contrast(dark, background) >= contrast(light, background) {
465 dark
466 } else {
467 light
468 }
469}
470
471pub fn luminance(colour: Color) -> f32 {
474 let linear = |channel: f32| {
475 if channel <= 0.040_45 {
476 channel / 12.92
477 } else {
478 ((channel + 0.055) / 1.055).powf(2.4)
479 }
480 };
481 0.2126 * linear(colour.r) + 0.7152 * linear(colour.g) + 0.0722 * linear(colour.b)
482}
483
484pub fn contrast(a: Color, b: Color) -> f32 {
486 let (a, b) = (luminance(a), luminance(b));
487 (a.max(b) + 0.05) / (a.min(b) + 0.05)
488}
489
490pub const TEXT_CONTRAST: f32 = 4.5;
492
493pub fn readable(colour: Color, background: Color) -> Color {
497 let towards = on(background);
498 (0..=20)
499 .map(|step| mix(colour, towards, step as f32 / 20.0))
500 .find(|candidate| contrast(*candidate, background) >= TEXT_CONTRAST)
501 .unwrap_or(towards)
502}
503
504pub fn fade(color: Color, alpha: f32) -> Color {
506 Color {
507 a: color.a * alpha.clamp(0.0, 1.0),
508 ..color
509 }
510}
511
512#[cfg(test)]
513mod tests {
514 use super::*;
515
516 #[test]
517 fn every_tone_has_its_own_colour_in_light_and_dark() {
518 for theme in [light(), dark()] {
519 let tokens = Tokens::of(&theme);
520 let colours: Vec<Color> = Tone::ALL.iter().map(|t| t.colour(&tokens)).collect();
521 for (i, a) in colours.iter().enumerate() {
522 for b in &colours[i + 1..] {
523 assert_ne!(a, b);
524 }
525 }
526 assert_eq!(Tone::Destructive.colour(&tokens), tokens.destructive);
527 }
528 assert_eq!(Tone::default(), Tone::Primary);
529 }
530
531 #[test]
532 fn semibold_keeps_the_base_family() {
533 let font = semibold();
534 assert_eq!(font.weight, Weight::Semibold);
535 assert_eq!(font.family, super::font().family);
536 }
537
538 #[test]
539 fn contrast_follows_the_wcag_formula() {
540 assert!((contrast(Color::BLACK, Color::WHITE) - 21.0).abs() < 0.01);
541 assert!((contrast(Color::WHITE, Color::WHITE) - 1.0).abs() < 1e-6);
542 assert_eq!(
543 contrast(Color::BLACK, Color::WHITE),
544 contrast(Color::WHITE, Color::BLACK)
545 );
546 }
547
548 #[test]
549 fn text_on_a_colour_takes_whichever_reads_better() {
550 let green = color!(0x16a34a);
552 assert_eq!(on(green), color!(0x09090b));
553 assert!(contrast(on(green), green) >= TEXT_CONTRAST);
554 assert_eq!(on(Color::BLACK), color!(0xfafafa));
555 assert_eq!(on(Color::WHITE), color!(0x09090b));
556 }
557
558 #[test]
559 fn destructive_text_reads_on_the_page_in_both_themes() {
560 for theme in [light(), dark()] {
561 let tokens = Tokens::of(&theme);
562 assert!(contrast(tokens.destructive_text, tokens.background) >= TEXT_CONTRAST);
563 assert_eq!(
565 tokens.destructive,
566 theme.extended_palette().danger.base.color
567 );
568 }
569 let tokens = Tokens::of(&dark());
570 assert_ne!(
571 tokens.destructive_text, tokens.destructive,
572 "lightened on dark"
573 );
574 }
575
576 #[test]
577 fn a_colour_that_already_reads_is_left_alone() {
578 let ink = color!(0x1d4ed8);
579 assert_eq!(readable(ink, Color::WHITE), ink);
580 }
581
582 #[test]
583 fn mix_endpoints_return_inputs() {
584 let a = Color::from_rgb(0.0, 0.2, 0.4);
585 let b = Color::from_rgb(1.0, 0.8, 0.6);
586 assert_eq!(mix(a, b, 0.0), a);
587 assert_eq!(mix(a, b, 1.0), b);
588 }
589
590 #[test]
591 fn mix_clamps_out_of_range_factor() {
592 let a = Color::BLACK;
593 let b = Color::WHITE;
594 assert_eq!(mix(a, b, -1.0), a);
595 assert_eq!(mix(a, b, 2.0), b);
596 }
597
598 #[test]
599 fn fade_scales_alpha_only() {
600 let faded = fade(Color::from_rgba(0.1, 0.2, 0.3, 0.8), 0.5);
601 assert_eq!((faded.r, faded.g, faded.b), (0.1, 0.2, 0.3));
602 assert!((faded.a - 0.4).abs() < f32::EPSILON);
603 }
604
605 #[test]
606 fn on_picks_dark_text_for_light_backgrounds() {
607 assert_eq!(on(Color::WHITE), color!(0x09090b));
608 assert_eq!(on(Color::BLACK), color!(0xfafafa));
609 assert_eq!(on(color!(0xdc2626)), color!(0xfafafa));
610 }
611
612 #[test]
613 fn popover_is_the_background_in_light_and_lifted_in_dark() {
614 let light = Tokens::of(&light());
615 assert_eq!(light.popover, light.background);
616
617 let dark = Tokens::of(&dark());
618 let card = mix(dark.background, dark.foreground, 0.04);
619 let brightness = |colour: Color| colour.r + colour.g + colour.b;
620 assert!(brightness(dark.popover) > brightness(card));
621 assert!(brightness(dark.popover) < brightness(dark.foreground));
622 }
623
624 #[test]
625 fn light_and_dark_report_their_mode() {
626 assert!(!Tokens::of(&light()).is_dark);
627 assert!(Tokens::of(&dark()).is_dark);
628 }
629
630 #[test]
631 fn primary_foreground_contrasts_with_primary() {
632 for theme in [light(), dark()] {
633 let tokens = Tokens::of(&theme);
634 assert_ne!(tokens.primary, tokens.primary_foreground);
635 assert_ne!(tokens.background, tokens.foreground);
636 }
637 }
638
639 #[test]
640 fn defaults_match_the_original_palettes() {
641 let light = Tokens::of(&light());
642 assert_eq!(light.background, color!(0xffffff));
643 assert_eq!(light.foreground, color!(0x09090b));
644 assert_eq!(light.primary, color!(0x18181b));
645 assert_eq!(light.destructive, color!(0xdc2626));
646 assert_eq!(light.secondary, light.muted);
647 assert_eq!(light.accent, light.muted);
648 assert_eq!(light.secondary_foreground, light.foreground);
649 assert_eq!(light.accent_foreground, light.foreground);
650
651 let dark = Tokens::of(&dark());
652 assert_eq!(dark.background, color!(0x09090b));
653 assert_eq!(dark.primary, color!(0xfafafa));
654 assert_eq!(dark.success, color!(0x22c55e));
655 assert_eq!(dark.secondary, dark.muted);
656 assert_eq!(dark.secondary_foreground, dark.foreground);
657 assert_eq!(dark.accent_foreground, dark.foreground);
658 }
659
660 #[test]
661 fn defaults_keep_the_generated_border() {
662 for config in [Config::light(), Config::dark()] {
663 let generated = Extended::generate(config.palette());
664 let tokens = Tokens::of(&config.build());
665 assert_eq!(tokens.border, generated.background.strong.color);
666 assert_eq!(tokens.muted, generated.background.weak.color);
667 }
668 }
669
670 #[test]
671 fn config_colours_reach_tokens() {
672 let theme = Config::light()
673 .name("Brand")
674 .primary(color!(0x4f46e5))
675 .secondary(color!(0xe0e7ff))
676 .accent(color!(0xfef3c7))
677 .destructive(color!(0xbe123c))
678 .success(color!(0x059669))
679 .warning(color!(0xca8a04))
680 .background(color!(0xfafaf9))
681 .foreground(color!(0x1c1917))
682 .border(color!(0xd6d3d1))
683 .build();
684 let tokens = Tokens::of(&theme);
685
686 assert_eq!(theme.to_string(), "Brand");
687 assert_eq!(tokens.primary, color!(0x4f46e5));
688 assert_eq!(tokens.primary_foreground, on(color!(0x4f46e5)));
689 assert_eq!(tokens.secondary, color!(0xe0e7ff));
690 assert_eq!(tokens.secondary_foreground, on(color!(0xe0e7ff)));
691 assert_eq!(tokens.accent, color!(0xfef3c7));
692 assert_eq!(tokens.destructive, color!(0xbe123c));
693 assert_eq!(tokens.success, color!(0x059669));
694 assert_eq!(tokens.warning, color!(0xca8a04));
695 assert_eq!(tokens.background, color!(0xfafaf9));
696 assert_eq!(tokens.foreground, color!(0x1c1917));
697 assert_eq!(tokens.border, color!(0xd6d3d1));
698 }
699
700 #[test]
701 fn unset_surfaces_follow_a_new_background() {
702 let background = color!(0xf5f5f4);
703 let tokens = Tokens::of(&Config::light().background(background).build());
704 let shade = Extended::generate(Palette {
705 background,
706 ..Config::light().palette()
707 })
708 .background
709 .weak
710 .color;
711 assert_eq!(tokens.secondary, shade);
712 assert_eq!(tokens.accent, shade);
713 }
714
715 #[test]
716 fn dark_mode_follows_the_background() {
717 assert!(!Tokens::of(&Config::light().build()).is_dark);
718 assert!(Tokens::of(&Config::dark().build()).is_dark);
719 let night = Config::light()
720 .background(color!(0x0f172a))
721 .foreground(color!(0xf8fafc))
722 .build();
723 assert!(Tokens::of(&night).is_dark);
724 let paper = Config::dark()
725 .background(color!(0xfffbeb))
726 .foreground(color!(0x292524))
727 .build();
728 assert!(!Tokens::of(&paper).is_dark);
729 }
730
731 #[test]
732 fn tokens_resolve_for_builtin_iced_themes() {
733 for theme in Theme::ALL {
734 let tokens = Tokens::of(theme);
735 assert_ne!(tokens.background, tokens.foreground, "{theme}");
736 }
737 }
738
739 #[test]
740 fn a_swatch_is_twelve_pixels_unless_sized() {
741 let swatch = swatch(|theme| Tokens::of(theme).primary);
742 assert_eq!(swatch.diameter(), SWATCH_SIZE);
743 assert_eq!(swatch.size(20.0).diameter(), 20.0);
744 }
745
746 #[test]
747 fn a_swatch_resolves_its_colour_from_each_theme() {
748 let swatch = swatch(|theme| Tokens::of(theme).primary);
749 assert_eq!(swatch.colour(&light()), Tokens::of(&light()).primary);
750 assert_eq!(swatch.colour(&dark()), Tokens::of(&dark()).primary);
751 assert_ne!(swatch.colour(&light()), swatch.colour(&dark()));
752 }
753
754 #[test]
755 fn a_fixed_swatch_ignores_the_theme() {
756 let teal = color!(0x14b8a6);
757 let swatch = swatch_color(teal);
758 assert_eq!(swatch.colour(&light()), teal);
759 assert_eq!(swatch.colour(&dark()), teal);
760 }
761}