Skip to main content

subspace_dashboard/
density.rs

1//! The density jig's tokens (REQ-10): the controls with their limits, and the [`Density`] global that holds the
2//! values the user changed. Rows, panels and the toolbar read the values through
3//! [`crate::Tokens::current`].
4
5use std::collections::BTreeMap;
6
7use gpui_kit::Global;
8use serde_json::{Map, Value, json};
9
10/// The state file key for the overrides.
11pub const STATE_KEY: &str = "board.jig";
12const FORMAT_SCALE: f64 = 10_000.0;
13pub const HEADING_FONT_DEFAULT: f32 = 15.;
14/// Board tab labels start at the heading size, but have their own setting.
15pub const TAB_FONT_DEFAULT: f32 = 15.;
16pub const BODY_FONT_DEFAULT: f32 = 13.;
17pub const MONO_FONT_DEFAULT: f32 = 13.;
18/// The interface base (`rem`) at the default body text size. Control tokens
19/// are pixels at this base, so they scale with the body text like every other
20/// rem-based size.
21pub const REFERENCE_REM: f32 = 14.;
22
23/// True while density changes are a live preview and must not be persisted.
24#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
25pub struct DensityPreview(pub bool);
26
27impl Global for DensityPreview {}
28
29/// One slider of the jig.
30#[derive(Debug, Clone, Copy, PartialEq)]
31pub struct Control {
32    /// The CSS custom property name, such as `--row-h`.
33    pub token: &'static str,
34    pub label: &'static str,
35    pub min: f32,
36    pub max: f32,
37    pub step: f32,
38    pub unit: &'static str,
39    /// The stylesheet value (`src/styles.css`).
40    pub default: f32,
41    /// A choice token's stored values and their labels; the value is the
42    /// index. Empty for a number or a switch.
43    pub choices: &'static [(&'static str, &'static str)],
44}
45
46pub struct ControlGroup {
47    pub name: &'static str,
48    pub controls: &'static [Control],
49}
50
51const fn control(
52    token: &'static str,
53    label: &'static str,
54    (min, max, step): (f32, f32, f32),
55    unit: &'static str,
56    default: f32,
57) -> Control {
58    Control {
59        token,
60        label,
61        min,
62        max,
63        step,
64        unit,
65        default,
66        choices: &[],
67    }
68}
69
70/// A token with named values, such as `flat` or `glass`, stored by name and
71/// held as the index of the value; `default` is an index too.
72const fn choice(
73    token: &'static str,
74    label: &'static str,
75    choices: &'static [(&'static str, &'static str)],
76    (max, default): (f32, f32),
77) -> Control {
78    Control {
79        token,
80        label,
81        min: 0.,
82        max,
83        step: 1.,
84        unit: "",
85        default,
86        choices,
87    }
88}
89
90/// The independent Settings font sizes, also available in the theme designer.
91pub const FONT_SIZES: &[Control] = &[
92    control(
93        "--heading-font",
94        "Headings",
95        (10., 24., 0.5),
96        "px",
97        HEADING_FONT_DEFAULT,
98    ),
99    control(
100        "--row-font",
101        "Body text",
102        (10., 18., 0.5),
103        "px",
104        BODY_FONT_DEFAULT,
105    ),
106    control(
107        "--mono-font",
108        "Code and logs",
109        (10., 20., 0.5),
110        "px",
111        MONO_FONT_DEFAULT,
112    ),
113    // Last, so the first three keep lining up with the three font families.
114    control(
115        "--tab-font",
116        "Tabs",
117        (10., 24., 0.5),
118        "px",
119        TAB_FONT_DEFAULT,
120    ),
121];
122
123/// The index in [`FONT_SIZES`] of the tab size, which has no font family of
124/// its own: tabs use the headings font.
125pub const TAB_FONT_SIZE: usize = 3;
126
127mod groups;
128pub use groups::{CONTROL_GROUPS, GROUPS};
129
130pub fn controls() -> impl Iterator<Item = &'static Control> {
131    GROUPS.iter().flat_map(|group| group.controls)
132}
133
134pub fn control_of(token: &str) -> Option<&'static Control> {
135    controls().find(|control| control.token == token)
136}
137
138/// A value as the jig writes it: at most 4 decimals, then the unit, such as
139/// `13.5px` or `0.6fr`, or a choice token's value name, such as `flat`.
140pub fn format(control: &Control, value: f32) -> String {
141    // A float cast saturates, so a negative value is the first choice.
142    let index = value.round() as usize;
143    if let Some((name, _)) = control.choices.get(index) {
144        return (*name).to_owned();
145    }
146    let rounded = (f64::from(value) * FORMAT_SCALE).round() / FORMAT_SCALE;
147    format!("{rounded}{}", control.unit)
148}
149
150/// Parses a stored value: a number with the control's unit, or one of a
151/// choice token's value names, nothing else.
152pub fn parse(control: &Control, text: &str) -> Option<f32> {
153    if !control.choices.is_empty() {
154        let index = control.choices.iter().position(|(name, _)| *name == text)?;
155        return Some(index as f32);
156    }
157    let number = text.strip_suffix(control.unit)?;
158    let digits = number.strip_prefix('-').unwrap_or(number);
159    let (whole, fraction) = digits.split_once('.').unwrap_or((digits, "0"));
160    let plain = |part: &str| !part.is_empty() && part.bytes().all(|b| b.is_ascii_digit());
161    (plain(whole) && plain(fraction)).then(|| number.parse().ok())?
162}
163
164/// A switch token's stored values.
165pub const SWITCH_OFF: f32 = 0.;
166pub const SWITCH_ON: f32 = 1.;
167
168impl Control {
169    /// A unitless token without named values is an off/on switch stored as
170    /// 0 or 1.
171    pub fn is_switch(&self) -> bool {
172        self.unit.is_empty() && self.choices.is_empty()
173    }
174
175    /// A token with named values, such as `--toolbar-button-rest`.
176    pub fn is_choice(&self) -> bool {
177        !self.choices.is_empty()
178    }
179}
180
181/// The jig values that differ from the stylesheet.
182#[derive(Debug, Clone, Default, PartialEq)]
183pub struct Density {
184    overrides: BTreeMap<&'static str, f32>,
185}
186
187impl Global for Density {}
188
189impl Density {
190    /// The value of `token`: the override, else the default; 0 for an
191    /// unknown token.
192    pub fn get(&self, token: &str) -> f32 {
193        match control_of(token) {
194            Some(control) => self
195                .overrides
196                .get(control.token)
197                .copied()
198                .unwrap_or(control.default),
199            None => 0.0,
200        }
201    }
202
203    pub fn is_changed(&self, token: &str) -> bool {
204        self.overrides.contains_key(token)
205    }
206
207    pub fn is_empty(&self) -> bool {
208        self.overrides.is_empty()
209    }
210
211    /// Sets `token`, clamped to its limits. The default value removes the
212    /// override.
213    pub fn set(&mut self, token: &str, value: f32) {
214        let Some(control) = control_of(token) else {
215            return;
216        };
217        let value = value.clamp(control.min, control.max);
218        if (value - control.default).abs() < f32::EPSILON {
219            self.overrides.remove(control.token);
220        } else {
221            self.overrides.insert(control.token, value);
222        }
223    }
224
225    pub fn remove(&mut self, token: &str) {
226        self.overrides.remove(token);
227    }
228
229    pub fn reset(&mut self) {
230        self.overrides.clear();
231    }
232
233    /// The overrides as stored: `{"--row-h": "30px"}`.
234    pub fn to_json(&self) -> String {
235        let map: Map<String, Value> = self
236            .overrides
237            .iter()
238            .filter_map(|(token, value)| {
239                let control = control_of(token)?;
240                Some((token.to_string(), Value::from(format(control, *value))))
241            })
242            .collect();
243        Value::Object(map).to_string()
244    }
245
246    /// Reads stored overrides. Only known tokens with a number in the
247    /// control's unit are kept, so a stored value cannot inject anything else.
248    pub fn from_json(text: &str) -> Self {
249        let mut density = Self::default();
250        if let Ok(Value::Object(map)) = serde_json::from_str::<Value>(text) {
251            for (token, value) in map {
252                let control = control_of(&token);
253                let value = value.as_str().zip(control).and_then(|(v, c)| parse(c, v));
254                if let Some(value) = value {
255                    density.set(&token, value);
256                }
257            }
258        }
259        density
260    }
261
262    /// The jig's "Copy" text: the changed tokens and every token's value.
263    pub fn snapshot(&self) -> String {
264        let changed: Map<String, Value> = self
265            .overrides
266            .keys()
267            .filter_map(|token| {
268                let control = control_of(token)?;
269                Some((token.to_string(), format(control, self.get(token)).into()))
270            })
271            .collect();
272        let tokens: Map<String, Value> = controls()
273            .map(|c| (c.token.to_string(), format(c, self.get(c.token)).into()))
274            .collect();
275        serde_json::to_string_pretty(&json!({
276            "subspace-board-tokens": 1,
277            "changed": changed,
278            "tokens": tokens,
279        }))
280        .unwrap_or_default()
281    }
282}
283
284#[cfg(test)]
285mod tests {
286    use super::{Density, control_of, controls, format, parse};
287
288    #[test]
289    fn values_clamp_and_the_default_removes_the_override() {
290        let mut density = Density::default();
291        density.set("--row-h", 100.0);
292        assert_eq!(density.get("--row-h"), 48.0);
293        assert!(density.is_changed("--row-h"));
294        density.set("--row-h", 28.0);
295        assert!(density.is_empty());
296        assert!(!density.is_changed("--row-h"));
297        density.set("--unknown", 3.0);
298        assert!(density.is_empty());
299        assert!(!density.is_changed("--unknown"));
300        assert_eq!(controls().count(), 44);
301    }
302
303    #[test]
304    fn choice_tokens_store_their_value_names() {
305        let rest = control_of("--toolbar-button-rest").unwrap();
306        assert!(rest.is_choice() && !rest.is_switch());
307        assert!(control_of("--liquid-glass").unwrap().is_switch());
308        assert_eq!(format(rest, 0.), "flat");
309        assert_eq!(format(rest, 1.), "glass");
310        assert_eq!(parse(rest, "glass"), Some(1.));
311        assert_eq!(parse(rest, "1"), None);
312        assert_eq!(parse(rest, "outline"), None);
313        let density = Density::from_json(r#"{"--toolbar-button-hover":"glass"}"#);
314        assert_eq!(density.get("--toolbar-button-hover"), 1.);
315        assert_eq!(density.get("--toolbar-button-rest"), 0.);
316        assert_eq!(density.to_json(), r#"{"--toolbar-button-hover":"glass"}"#);
317    }
318
319    #[test]
320    fn overrides_survive_json_and_bad_values_are_dropped() {
321        let mut density = Density::default();
322        density.set("--row-font", 13.5);
323        density.set("--done-w", 0.75);
324        let text = density.to_json();
325        assert_eq!(text, r#"{"--done-w":"0.75fr","--row-font":"13.5px"}"#);
326        assert_eq!(Density::from_json(&text), density);
327
328        let hostile =
329            r#"{"--row-h":"30px; color: red","--pad-x":"8em","--x":"1px","--indent":"30px"}"#;
330        let loaded = Density::from_json(hostile);
331        assert_eq!(loaded.get("--row-h"), 28.0);
332        assert_eq!(loaded.get("--pad-x"), 12.0);
333        assert_eq!(loaded.get("--indent"), 30.0);
334        assert_eq!(Density::from_json("not json"), Density::default());
335    }
336
337    #[test]
338    fn the_snapshot_lists_changed_and_all_tokens() {
339        let mut density = Density::default();
340        density.set("--panel-w", 720.0);
341        let snapshot: serde_json::Value = serde_json::from_str(&density.snapshot()).unwrap();
342        assert_eq!(snapshot["changed"]["--panel-w"], "720px");
343        assert_eq!(snapshot["tokens"]["--motion"], "140ms");
344        assert_eq!(snapshot["subspace-board-tokens"], 1);
345    }
346}