Skip to main content

nsh_core/element/
tokens.rs

1//! Design tokens: colors with a light and a dark value, numbers and font
2//! families, by name (`muted-foreground`, `radius`, `font-sans`). The core
3//! gives no name a meaning but `font-sans`, the app's default font (as
4//! Tailwind's `--font-sans` is a page's), and has none of its own: a UI set
5//! brings them (`nsh-base`'s theme, through
6//! [`super::Registry::tokens_from`]), an app sets its own, an embedding app
7//! its own over those ([`crate::Core::set_host_tokens`]).
8//!
9//! A name is a CSS custom property's without its `--`: Tailwind classes name
10//! every token as they name a theme variable (`bg-muted`, `bg-up/30`,
11//! `rounded-(--radius)`, `font-(family-name:--font-mono)`;
12//! `tailwind/theme.rs`), TS reads them with `nsh`'s `token()`, and Rust
13//! components with [`super::ambient::tokens`].
14
15use std::sync::Arc;
16
17use rustc_hash::FxHashMap;
18
19use super::style::AdaptiveColor;
20
21/// The app's default font family's token: Tailwind's `--font-sans`.
22pub const FONT_SANS: &str = "font-sans";
23
24/// The monospaced font family's token: Tailwind's `--font-mono`.
25pub const FONT_MONO: &str = "font-mono";
26
27/// Design tokens by name: colors with a value per appearance, numbers and
28/// font families. The default has none.
29#[derive(Debug, Clone, PartialEq, Default)]
30pub struct Tokens {
31    colors: FxHashMap<Box<str>, AdaptiveColor>,
32    numbers: FxHashMap<Box<str>, f32>,
33    fonts: FxHashMap<Box<str>, Arc<str>>,
34}
35
36/// A token's value.
37#[derive(Debug, Clone, PartialEq)]
38pub enum Token {
39    /// A color, per appearance.
40    Color(AdaptiveColor),
41    /// A number: a length in points, or a unitless quantity.
42    Number(f32),
43    /// A font family.
44    Font(Arc<str>),
45}
46
47/// Makes the tokens of a theme file's content (`Some`), or the defaults
48/// (`None`): how a UI set reads the app's theme ([`super::Registry::tokens_from`]).
49pub type TokenSource = fn(Option<&str>) -> Result<Tokens, String>;
50
51/// The tokens a surface is drawn with once the app's theme file reaches its
52/// root ([`crate::Core::theme_tokens`]). The entry hands the theme to the
53/// renderer in the turn of its first render, before the theme's op reaches
54/// the core: JS reads the tokens from here meanwhile, so its first render
55/// already has them (`token()` of `nsh`).
56#[derive(Debug, Clone, Default)]
57#[non_exhaustive]
58pub struct ThemeTokens {
59    /// How the UI sets read a theme file (`None`: none does).
60    source: Option<TokenSource>,
61    /// The embedding app's tokens, which win over the app's.
62    host: Option<Arc<Tokens>>,
63}
64
65impl ThemeTokens {
66    pub(crate) fn new(source: Option<TokenSource>, host: Option<Arc<Tokens>>) -> Self {
67        Self { source, host }
68    }
69
70    /// The tokens drawn with when the app's theme file is `json`: its own
71    /// under the embedding app's, as the core makes them. `None`: no UI set
72    /// reads themes, or `json` is not one (the core reports it when the
73    /// theme reaches it).
74    pub fn of(&self, json: &str) -> Option<Tokens> {
75        let app = (self.source?)(Some(json)).ok()?;
76        Some(match &self.host {
77            Some(host) => host.over(&app),
78            None => app,
79        })
80    }
81}
82
83impl Tokens {
84    /// The color named `name`.
85    pub fn color(&self, name: &str) -> Option<AdaptiveColor> {
86        self.colors.get(name).copied()
87    }
88
89    /// Sets the color named `name`.
90    pub fn set_color(&mut self, name: &str, color: AdaptiveColor) {
91        self.colors.insert(name.into(), color);
92    }
93
94    /// The number named `name`.
95    pub fn number(&self, name: &str) -> Option<f32> {
96        self.numbers.get(name).copied()
97    }
98
99    /// Sets the number named `name`.
100    pub fn set_number(&mut self, name: &str, value: f32) {
101        self.numbers.insert(name.into(), value);
102    }
103
104    /// The font family named `name` ([`FONT_SANS`], [`FONT_MONO`], ...).
105    pub fn font(&self, name: &str) -> Option<&Arc<str>> {
106        self.fonts.get(name)
107    }
108
109    /// Sets the font family named `name`.
110    pub fn set_font(&mut self, name: &str, family: impl Into<Arc<str>>) {
111        self.fonts.insert(name.into(), family.into());
112    }
113
114    /// The token named `name`, of any kind (a color first, as classes take
115    /// it).
116    pub fn get(&self, name: &str) -> Option<Token> {
117        if let Some(c) = self.colors.get(name) {
118            return Some(Token::Color(*c));
119        }
120        if let Some(n) = self.numbers.get(name) {
121            return Some(Token::Number(*n));
122        }
123        self.fonts.get(name).cloned().map(Token::Font)
124    }
125
126    /// Whether it has no token.
127    pub fn is_empty(&self) -> bool {
128        self.colors.is_empty() && self.numbers.is_empty() && self.fonts.is_empty()
129    }
130
131    /// Each color by name.
132    pub fn colors(&self) -> impl Iterator<Item = (&str, AdaptiveColor)> {
133        self.colors.iter().map(|(k, c)| (&**k, *c))
134    }
135
136    /// Each number by name.
137    pub fn numbers(&self) -> impl Iterator<Item = (&str, f32)> {
138        self.numbers.iter().map(|(k, n)| (&**k, *n))
139    }
140
141    /// Each font family by name.
142    pub fn fonts(&self) -> impl Iterator<Item = (&str, &Arc<str>)> {
143        self.fonts.iter().map(|(k, f)| (&**k, f))
144    }
145
146    /// `self` with the tokens of `base` it does not have.
147    pub fn over(&self, base: &Tokens) -> Tokens {
148        let mut out = base.clone();
149        out.colors
150            .extend(self.colors.iter().map(|(k, c)| (k.clone(), *c)));
151        out.numbers
152            .extend(self.numbers.iter().map(|(k, n)| (k.clone(), *n)));
153        out.fonts
154            .extend(self.fonts.iter().map(|(k, f)| (k.clone(), f.clone())));
155        out
156    }
157}
158
159/// Tokens as apps have them (`nsh-base`'s default theme's and a few of an
160/// app's own), for the core's tests.
161#[cfg(test)]
162pub(crate) fn sample() -> Tokens {
163    let mut tokens = Tokens::default();
164    for (key, light, dark) in [
165        ("background", 0xffffff, 0x0a0a0a),
166        ("foreground", 0x0a0a0a, 0xfafafa),
167        ("border", 0xe5e5e5, 0x262626),
168        ("ring", 0xa3a3a3, 0x525252),
169        ("muted", 0xf5f5f5, 0x262626),
170        ("muted-foreground", 0x737373, 0xa3a3a3),
171        ("accent", 0xf5f5f5, 0x262626),
172        ("primary", 0x171717, 0xfafafa),
173        ("primary-active", 0x0a0a0a, 0xe5e5e5),
174        ("primary-foreground", 0xfafafa, 0x171717),
175        ("popover", 0xffffff, 0x0a0a0a),
176        ("popover-foreground", 0x0a0a0a, 0xfafafa),
177    ] {
178        tokens.set_color(key, AdaptiveColor::rgb(light, dark));
179    }
180    for (key, n) in [("radius", 12.0), ("radius-lg", 16.0), ("font-size", 16.0)] {
181        tokens.set_number(key, n);
182    }
183    tokens
184}
185
186#[cfg(test)]
187mod tests {
188    use super::*;
189    use crate::color::rgb;
190
191    #[test]
192    fn tokens_over_others_win_and_keep_the_rest() {
193        let mut base = Tokens::default();
194        base.set_color("primary", rgb(0x111111).into());
195        base.set_color("ring", rgb(0x222222).into());
196        base.set_number("radius", 12.0);
197        base.set_font(FONT_SANS, "Inter");
198        let mut top = Tokens::default();
199        top.set_color("primary", rgb(0x333333).into());
200        top.set_number("radius-card", 10.0);
201        top.set_font(FONT_MONO, "Iosevka");
202        let tokens = top.over(&base);
203        assert_eq!(tokens.color("primary"), Some(rgb(0x333333).into()));
204        assert_eq!(tokens.color("ring"), Some(rgb(0x222222).into()));
205        assert_eq!(tokens.number("radius"), Some(12.0));
206        assert_eq!(tokens.number("radius-card"), Some(10.0));
207        assert_eq!(tokens.font(FONT_SANS).map(|f| &**f), Some("Inter"));
208        assert_eq!(tokens.font(FONT_MONO).map(|f| &**f), Some("Iosevka"));
209        assert!(Tokens::default().is_empty());
210    }
211}