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::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`), with what of the file it left out (a value it cannot read):
49/// how a UI set reads the app's theme ([`super::Registry::tokens_from`]).
50/// `Err`: the content is no theme file at all.
51pub type TokenSource = fn(Option<&str>) -> Result<(Tokens, Vec<String>), String>;
52
53/// The tokens a surface is drawn with once the app's theme file reaches its
54/// root ([`crate::Core::theme_tokens`]). The entry hands the theme to the
55/// renderer in the turn of its first render, before the theme's op reaches
56/// the core: JS reads the tokens from here meanwhile, so its first render
57/// already has them (`token()` of `nsh`).
58#[derive(Debug, Clone, Default)]
59#[non_exhaustive]
60pub struct ThemeTokens {
61    /// How the UI sets read a theme file (`None`: none does).
62    source: Option<TokenSource>,
63    /// The embedding app's tokens, which win over the app's.
64    host: Option<Arc<Tokens>>,
65}
66
67impl ThemeTokens {
68    pub(crate) fn new(source: Option<TokenSource>, host: Option<Arc<Tokens>>) -> Self {
69        Self { source, host }
70    }
71
72    /// The tokens drawn with when the app's theme file is `json`: its own
73    /// under the embedding app's, as the core makes them. `None`: no UI set
74    /// reads themes, or `json` is not one (the core reports it when the
75    /// theme reaches it).
76    pub fn of(&self, json: &str) -> Option<Tokens> {
77        let (app, _) = (self.source?)(Some(json)).ok()?;
78        Some(self.under_host(app))
79    }
80
81    /// [`ThemeTokens::of`] for a theme file that must be read whole (`nsh`'s
82    /// `setTheme`): `Err` names each value it cannot read, `; `-separated.
83    /// `None`: no UI set reads themes.
84    pub fn checked(&self, json: &str) -> Option<Result<Tokens, String>> {
85        Some(match (self.source?)(Some(json)) {
86            Ok((app, left_out)) if left_out.is_empty() => Ok(self.under_host(app)),
87            Ok((_, left_out)) => Err(left_out.join("; ")),
88            Err(e) => Err(e),
89        })
90    }
91
92    /// `app` under the embedding app's tokens.
93    fn under_host(&self, app: Tokens) -> Tokens {
94        match &self.host {
95            Some(host) => host.over(&app),
96            None => app,
97        }
98    }
99}
100
101impl Tokens {
102    /// The color named `name`.
103    pub fn color(&self, name: &str) -> Option<AdaptiveColor> {
104        self.colors.get(name).copied()
105    }
106
107    /// Sets the color named `name`.
108    pub fn set_color(&mut self, name: &str, color: AdaptiveColor) {
109        self.colors.insert(name.into(), color);
110    }
111
112    /// The number named `name`.
113    pub fn number(&self, name: &str) -> Option<f32> {
114        self.numbers.get(name).copied()
115    }
116
117    /// Sets the number named `name`.
118    pub fn set_number(&mut self, name: &str, value: f32) {
119        self.numbers.insert(name.into(), value);
120    }
121
122    /// The font family named `name` ([`FONT_SANS`], [`FONT_MONO`], ...).
123    pub fn font(&self, name: &str) -> Option<&Arc<str>> {
124        self.fonts.get(name)
125    }
126
127    /// Sets the font family named `name`.
128    pub fn set_font(&mut self, name: &str, family: impl Into<Arc<str>>) {
129        self.fonts.insert(name.into(), family.into());
130    }
131
132    /// The token named `name`, of any kind (a color first, as classes take
133    /// it).
134    pub fn get(&self, name: &str) -> Option<Token> {
135        if let Some(c) = self.colors.get(name) {
136            return Some(Token::Color(*c));
137        }
138        if let Some(n) = self.numbers.get(name) {
139            return Some(Token::Number(*n));
140        }
141        self.fonts.get(name).cloned().map(Token::Font)
142    }
143
144    /// Whether it has no token.
145    pub fn is_empty(&self) -> bool {
146        self.colors.is_empty() && self.numbers.is_empty() && self.fonts.is_empty()
147    }
148
149    /// Each color by name.
150    pub fn colors(&self) -> impl Iterator<Item = (&str, AdaptiveColor)> {
151        self.colors.iter().map(|(k, c)| (&**k, *c))
152    }
153
154    /// Each number by name.
155    pub fn numbers(&self) -> impl Iterator<Item = (&str, f32)> {
156        self.numbers.iter().map(|(k, n)| (&**k, *n))
157    }
158
159    /// Each font family by name.
160    pub fn fonts(&self) -> impl Iterator<Item = (&str, &Arc<str>)> {
161        self.fonts.iter().map(|(k, f)| (&**k, f))
162    }
163
164    /// `self` with the tokens of `base` it does not have.
165    pub fn over(&self, base: &Tokens) -> Tokens {
166        let mut out = base.clone();
167        out.colors
168            .extend(self.colors.iter().map(|(k, c)| (k.clone(), *c)));
169        out.numbers
170            .extend(self.numbers.iter().map(|(k, n)| (k.clone(), *n)));
171        out.fonts
172            .extend(self.fonts.iter().map(|(k, f)| (k.clone(), f.clone())));
173        out
174    }
175}
176
177/// Tokens as apps have them (`nsh-base`'s default theme's and a few of an
178/// app's own), for the core's tests.
179#[cfg(test)]
180pub(crate) fn sample() -> Tokens {
181    let mut tokens = Tokens::default();
182    for (key, light, dark) in [
183        ("background", 0xffffff, 0x0a0a0a),
184        ("foreground", 0x0a0a0a, 0xfafafa),
185        ("border", 0xe5e5e5, 0x262626),
186        ("ring", 0xa3a3a3, 0x525252),
187        ("muted", 0xf5f5f5, 0x262626),
188        ("muted-foreground", 0x737373, 0xa3a3a3),
189        ("accent", 0xf5f5f5, 0x262626),
190        ("primary", 0x171717, 0xfafafa),
191        ("primary-active", 0x0a0a0a, 0xe5e5e5),
192        ("primary-foreground", 0xfafafa, 0x171717),
193        ("popover", 0xffffff, 0x0a0a0a),
194        ("popover-foreground", 0x0a0a0a, 0xfafafa),
195    ] {
196        tokens.set_color(key, AdaptiveColor::rgb(light, dark));
197    }
198    for (key, n) in [("radius", 12.0), ("radius-lg", 16.0), ("font-size", 16.0)] {
199        tokens.set_number(key, n);
200    }
201    tokens
202}
203
204#[cfg(test)]
205mod tests {
206    use super::*;
207    use crate::color::rgb;
208
209    #[test]
210    fn tokens_over_others_win_and_keep_the_rest() {
211        let mut base = Tokens::default();
212        base.set_color("primary", rgb(0x111111).into());
213        base.set_color("ring", rgb(0x222222).into());
214        base.set_number("radius", 12.0);
215        base.set_font(FONT_SANS, "Inter");
216        let mut top = Tokens::default();
217        top.set_color("primary", rgb(0x333333).into());
218        top.set_number("radius-card", 10.0);
219        top.set_font(FONT_MONO, "Iosevka");
220        let tokens = top.over(&base);
221        assert_eq!(tokens.color("primary"), Some(rgb(0x333333).into()));
222        assert_eq!(tokens.color("ring"), Some(rgb(0x222222).into()));
223        assert_eq!(tokens.number("radius"), Some(12.0));
224        assert_eq!(tokens.number("radius-card"), Some(10.0));
225        assert_eq!(tokens.font(FONT_SANS).map(|f| &**f), Some("Inter"));
226        assert_eq!(tokens.font(FONT_MONO).map(|f| &**f), Some("Iosevka"));
227        assert!(Tokens::default().is_empty());
228    }
229}