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
168pub fn light() -> Theme {
170 Config::light().build()
171}
172
173pub fn dark() -> Theme {
175 Config::dark().build()
176}
177
178#[derive(Debug, Clone, PartialEq)]
195pub struct Config {
196 name: Cow<'static, str>,
197 background: Color,
198 foreground: Color,
199 primary: Color,
200 secondary: Option<Color>,
201 accent: Option<Color>,
202 destructive: Color,
203 success: Color,
204 warning: Color,
205 border: Option<Color>,
206}
207
208impl Config {
209 pub fn light() -> Self {
211 Self {
212 name: Cow::Borrowed("Cube Light"),
213 background: color!(0xffffff),
214 foreground: color!(0x09090b),
215 primary: color!(0x18181b),
216 secondary: None,
217 accent: None,
218 destructive: color!(0xdc2626),
219 success: color!(0x16a34a),
220 warning: color!(0xd97706),
221 border: None,
222 }
223 }
224
225 pub fn dark() -> Self {
227 Self {
228 name: Cow::Borrowed("Cube Dark"),
229 background: color!(0x09090b),
230 foreground: color!(0xfafafa),
231 primary: color!(0xfafafa),
232 secondary: None,
233 accent: None,
234 destructive: color!(0xdc2626),
235 success: color!(0x22c55e),
236 warning: color!(0xf59e0b),
237 border: None,
238 }
239 }
240
241 pub fn name(mut self, name: impl Into<Cow<'static, str>>) -> Self {
243 self.name = name.into();
244 self
245 }
246
247 pub fn primary(mut self, colour: Color) -> Self {
249 self.primary = colour;
250 self
251 }
252
253 pub fn secondary(mut self, colour: Color) -> Self {
255 self.secondary = Some(colour);
256 self
257 }
258
259 pub fn accent(mut self, colour: Color) -> Self {
262 self.accent = Some(colour);
263 self
264 }
265
266 pub fn destructive(mut self, colour: Color) -> Self {
268 self.destructive = colour;
269 self
270 }
271
272 pub fn success(mut self, colour: Color) -> Self {
273 self.success = colour;
274 self
275 }
276
277 pub fn warning(mut self, colour: Color) -> Self {
278 self.warning = colour;
279 self
280 }
281
282 pub fn background(mut self, colour: Color) -> Self {
285 self.background = colour;
286 self
287 }
288
289 pub fn foreground(mut self, colour: Color) -> Self {
291 self.foreground = colour;
292 self
293 }
294
295 pub fn border(mut self, colour: Color) -> Self {
298 self.border = Some(colour);
299 self
300 }
301
302 pub fn palette(&self) -> Palette {
304 Palette {
305 background: self.background,
306 text: self.foreground,
307 primary: self.primary,
308 success: self.success,
309 warning: self.warning,
310 danger: self.destructive,
311 }
312 }
313
314 pub fn extended(&self) -> Extended {
318 let mut extended = Extended::generate(self.palette());
319 let shade = extended.background.weak.color;
320 let secondary = self.secondary.unwrap_or(shade);
321 let accent = self.accent.unwrap_or(shade);
322 let strong = deviate(secondary, 0.1);
323
324 extended.secondary = Secondary {
325 base: Pair::new(secondary, on(secondary)),
326 weak: Pair::new(accent, on(accent)),
327 strong: Pair::new(strong, on(strong)),
328 };
329 if let Some(border) = self.border {
330 extended.background.strong = Pair::new(border, self.foreground);
331 }
332 extended
333 }
334
335 pub fn build(&self) -> Theme {
337 let extended = self.extended();
338 Theme::custom_with_fn(self.name.clone(), self.palette(), move |_| extended)
339 }
340}
341
342pub const SWATCH_SIZE: f32 = 12.0;
344
345pub struct Swatch<'a> {
348 colour: Box<dyn Fn(&Theme) -> Color + 'a>,
349 size: f32,
350}
351
352impl fmt::Debug for Swatch<'_> {
353 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
354 f.debug_struct("Swatch").field("size", &self.size).finish()
355 }
356}
357
358pub fn swatch<'a>(colour: impl Fn(&Theme) -> Color + 'a) -> Swatch<'a> {
368 Swatch {
369 colour: Box::new(colour),
370 size: SWATCH_SIZE,
371 }
372}
373
374pub fn swatch_color<'a>(colour: Color) -> Swatch<'a> {
376 swatch(move |_| colour)
377}
378
379impl Swatch<'_> {
380 pub fn size(mut self, size: f32) -> Self {
382 self.size = size;
383 self
384 }
385
386 pub fn diameter(&self) -> f32 {
388 self.size
389 }
390
391 pub fn colour(&self, theme: &Theme) -> Color {
393 (self.colour)(theme)
394 }
395}
396
397impl<'a, Message: 'a> From<Swatch<'a>> for Element<'a, Message> {
398 fn from(swatch: Swatch<'a>) -> Self {
399 let Swatch { colour, size } = swatch;
400 container(iced::widget::space())
401 .width(size)
402 .height(size)
403 .style(move |theme| container::Style {
404 background: Some(Background::Color(colour(theme))),
405 border: Border {
406 radius: radius::FULL.into(),
407 ..Border::default()
408 },
409 ..container::Style::default()
410 })
411 .into()
412 }
413}
414
415pub fn mix(a: Color, b: Color, t: f32) -> Color {
417 let t = t.clamp(0.0, 1.0);
418 Color {
419 r: a.r + (b.r - a.r) * t,
420 g: a.g + (b.g - a.g) * t,
421 b: a.b + (b.b - a.b) * t,
422 a: a.a + (b.a - a.a) * t,
423 }
424}
425
426pub fn on(background: Color) -> Color {
429 let (dark, light) = (color!(0x09090b), color!(0xfafafa));
430 if contrast(dark, background) >= contrast(light, background) {
431 dark
432 } else {
433 light
434 }
435}
436
437pub fn luminance(colour: Color) -> f32 {
440 let linear = |channel: f32| {
441 if channel <= 0.040_45 {
442 channel / 12.92
443 } else {
444 ((channel + 0.055) / 1.055).powf(2.4)
445 }
446 };
447 0.2126 * linear(colour.r) + 0.7152 * linear(colour.g) + 0.0722 * linear(colour.b)
448}
449
450pub fn contrast(a: Color, b: Color) -> f32 {
452 let (a, b) = (luminance(a), luminance(b));
453 (a.max(b) + 0.05) / (a.min(b) + 0.05)
454}
455
456pub const TEXT_CONTRAST: f32 = 4.5;
458
459pub fn readable(colour: Color, background: Color) -> Color {
463 let towards = on(background);
464 (0..=20)
465 .map(|step| mix(colour, towards, step as f32 / 20.0))
466 .find(|candidate| contrast(*candidate, background) >= TEXT_CONTRAST)
467 .unwrap_or(towards)
468}
469
470pub fn fade(color: Color, alpha: f32) -> Color {
472 Color {
473 a: color.a * alpha.clamp(0.0, 1.0),
474 ..color
475 }
476}
477
478#[cfg(test)]
479mod tests {
480 use super::*;
481
482 #[test]
483 fn semibold_keeps_the_base_family() {
484 let font = semibold();
485 assert_eq!(font.weight, Weight::Semibold);
486 assert_eq!(font.family, super::font().family);
487 }
488
489 #[test]
490 fn contrast_follows_the_wcag_formula() {
491 assert!((contrast(Color::BLACK, Color::WHITE) - 21.0).abs() < 0.01);
492 assert!((contrast(Color::WHITE, Color::WHITE) - 1.0).abs() < 1e-6);
493 assert_eq!(
494 contrast(Color::BLACK, Color::WHITE),
495 contrast(Color::WHITE, Color::BLACK)
496 );
497 }
498
499 #[test]
500 fn text_on_a_colour_takes_whichever_reads_better() {
501 let green = color!(0x16a34a);
503 assert_eq!(on(green), color!(0x09090b));
504 assert!(contrast(on(green), green) >= TEXT_CONTRAST);
505 assert_eq!(on(Color::BLACK), color!(0xfafafa));
506 assert_eq!(on(Color::WHITE), color!(0x09090b));
507 }
508
509 #[test]
510 fn destructive_text_reads_on_the_page_in_both_themes() {
511 for theme in [light(), dark()] {
512 let tokens = Tokens::of(&theme);
513 assert!(contrast(tokens.destructive_text, tokens.background) >= TEXT_CONTRAST);
514 assert_eq!(
516 tokens.destructive,
517 theme.extended_palette().danger.base.color
518 );
519 }
520 let tokens = Tokens::of(&dark());
521 assert_ne!(
522 tokens.destructive_text, tokens.destructive,
523 "lightened on dark"
524 );
525 }
526
527 #[test]
528 fn a_colour_that_already_reads_is_left_alone() {
529 let ink = color!(0x1d4ed8);
530 assert_eq!(readable(ink, Color::WHITE), ink);
531 }
532
533 #[test]
534 fn mix_endpoints_return_inputs() {
535 let a = Color::from_rgb(0.0, 0.2, 0.4);
536 let b = Color::from_rgb(1.0, 0.8, 0.6);
537 assert_eq!(mix(a, b, 0.0), a);
538 assert_eq!(mix(a, b, 1.0), b);
539 }
540
541 #[test]
542 fn mix_clamps_out_of_range_factor() {
543 let a = Color::BLACK;
544 let b = Color::WHITE;
545 assert_eq!(mix(a, b, -1.0), a);
546 assert_eq!(mix(a, b, 2.0), b);
547 }
548
549 #[test]
550 fn fade_scales_alpha_only() {
551 let faded = fade(Color::from_rgba(0.1, 0.2, 0.3, 0.8), 0.5);
552 assert_eq!((faded.r, faded.g, faded.b), (0.1, 0.2, 0.3));
553 assert!((faded.a - 0.4).abs() < f32::EPSILON);
554 }
555
556 #[test]
557 fn on_picks_dark_text_for_light_backgrounds() {
558 assert_eq!(on(Color::WHITE), color!(0x09090b));
559 assert_eq!(on(Color::BLACK), color!(0xfafafa));
560 assert_eq!(on(color!(0xdc2626)), color!(0xfafafa));
561 }
562
563 #[test]
564 fn popover_is_the_background_in_light_and_lifted_in_dark() {
565 let light = Tokens::of(&light());
566 assert_eq!(light.popover, light.background);
567
568 let dark = Tokens::of(&dark());
569 let card = mix(dark.background, dark.foreground, 0.04);
570 let brightness = |colour: Color| colour.r + colour.g + colour.b;
571 assert!(brightness(dark.popover) > brightness(card));
572 assert!(brightness(dark.popover) < brightness(dark.foreground));
573 }
574
575 #[test]
576 fn light_and_dark_report_their_mode() {
577 assert!(!Tokens::of(&light()).is_dark);
578 assert!(Tokens::of(&dark()).is_dark);
579 }
580
581 #[test]
582 fn primary_foreground_contrasts_with_primary() {
583 for theme in [light(), dark()] {
584 let tokens = Tokens::of(&theme);
585 assert_ne!(tokens.primary, tokens.primary_foreground);
586 assert_ne!(tokens.background, tokens.foreground);
587 }
588 }
589
590 #[test]
591 fn defaults_match_the_original_palettes() {
592 let light = Tokens::of(&light());
593 assert_eq!(light.background, color!(0xffffff));
594 assert_eq!(light.foreground, color!(0x09090b));
595 assert_eq!(light.primary, color!(0x18181b));
596 assert_eq!(light.destructive, color!(0xdc2626));
597 assert_eq!(light.secondary, light.muted);
598 assert_eq!(light.accent, light.muted);
599 assert_eq!(light.secondary_foreground, light.foreground);
600 assert_eq!(light.accent_foreground, light.foreground);
601
602 let dark = Tokens::of(&dark());
603 assert_eq!(dark.background, color!(0x09090b));
604 assert_eq!(dark.primary, color!(0xfafafa));
605 assert_eq!(dark.success, color!(0x22c55e));
606 assert_eq!(dark.secondary, dark.muted);
607 assert_eq!(dark.secondary_foreground, dark.foreground);
608 assert_eq!(dark.accent_foreground, dark.foreground);
609 }
610
611 #[test]
612 fn defaults_keep_the_generated_border() {
613 for config in [Config::light(), Config::dark()] {
614 let generated = Extended::generate(config.palette());
615 let tokens = Tokens::of(&config.build());
616 assert_eq!(tokens.border, generated.background.strong.color);
617 assert_eq!(tokens.muted, generated.background.weak.color);
618 }
619 }
620
621 #[test]
622 fn config_colours_reach_tokens() {
623 let theme = Config::light()
624 .name("Brand")
625 .primary(color!(0x4f46e5))
626 .secondary(color!(0xe0e7ff))
627 .accent(color!(0xfef3c7))
628 .destructive(color!(0xbe123c))
629 .success(color!(0x059669))
630 .warning(color!(0xca8a04))
631 .background(color!(0xfafaf9))
632 .foreground(color!(0x1c1917))
633 .border(color!(0xd6d3d1))
634 .build();
635 let tokens = Tokens::of(&theme);
636
637 assert_eq!(theme.to_string(), "Brand");
638 assert_eq!(tokens.primary, color!(0x4f46e5));
639 assert_eq!(tokens.primary_foreground, on(color!(0x4f46e5)));
640 assert_eq!(tokens.secondary, color!(0xe0e7ff));
641 assert_eq!(tokens.secondary_foreground, on(color!(0xe0e7ff)));
642 assert_eq!(tokens.accent, color!(0xfef3c7));
643 assert_eq!(tokens.destructive, color!(0xbe123c));
644 assert_eq!(tokens.success, color!(0x059669));
645 assert_eq!(tokens.warning, color!(0xca8a04));
646 assert_eq!(tokens.background, color!(0xfafaf9));
647 assert_eq!(tokens.foreground, color!(0x1c1917));
648 assert_eq!(tokens.border, color!(0xd6d3d1));
649 }
650
651 #[test]
652 fn unset_surfaces_follow_a_new_background() {
653 let background = color!(0xf5f5f4);
654 let tokens = Tokens::of(&Config::light().background(background).build());
655 let shade = Extended::generate(Palette {
656 background,
657 ..Config::light().palette()
658 })
659 .background
660 .weak
661 .color;
662 assert_eq!(tokens.secondary, shade);
663 assert_eq!(tokens.accent, shade);
664 }
665
666 #[test]
667 fn dark_mode_follows_the_background() {
668 assert!(!Tokens::of(&Config::light().build()).is_dark);
669 assert!(Tokens::of(&Config::dark().build()).is_dark);
670 let night = Config::light()
671 .background(color!(0x0f172a))
672 .foreground(color!(0xf8fafc))
673 .build();
674 assert!(Tokens::of(&night).is_dark);
675 let paper = Config::dark()
676 .background(color!(0xfffbeb))
677 .foreground(color!(0x292524))
678 .build();
679 assert!(!Tokens::of(&paper).is_dark);
680 }
681
682 #[test]
683 fn tokens_resolve_for_builtin_iced_themes() {
684 for theme in Theme::ALL {
685 let tokens = Tokens::of(theme);
686 assert_ne!(tokens.background, tokens.foreground, "{theme}");
687 }
688 }
689
690 #[test]
691 fn a_swatch_is_twelve_pixels_unless_sized() {
692 let swatch = swatch(|theme| Tokens::of(theme).primary);
693 assert_eq!(swatch.diameter(), SWATCH_SIZE);
694 assert_eq!(swatch.size(20.0).diameter(), 20.0);
695 }
696
697 #[test]
698 fn a_swatch_resolves_its_colour_from_each_theme() {
699 let swatch = swatch(|theme| Tokens::of(theme).primary);
700 assert_eq!(swatch.colour(&light()), Tokens::of(&light()).primary);
701 assert_eq!(swatch.colour(&dark()), Tokens::of(&dark()).primary);
702 assert_ne!(swatch.colour(&light()), swatch.colour(&dark()));
703 }
704
705 #[test]
706 fn a_fixed_swatch_ignores_the_theme() {
707 let teal = color!(0x14b8a6);
708 let swatch = swatch_color(teal);
709 assert_eq!(swatch.colour(&light()), teal);
710 assert_eq!(swatch.colour(&dark()), teal);
711 }
712}