1use std::collections::BTreeMap;
6
7use gpui_kit::Global;
8use serde_json::{Map, Value, json};
9
10pub const STATE_KEY: &str = "board.jig";
12const FORMAT_SCALE: f64 = 10_000.0;
13pub const HEADING_FONT_DEFAULT: f32 = 15.;
14pub const TAB_FONT_DEFAULT: f32 = 15.;
16pub const BODY_FONT_DEFAULT: f32 = 13.;
17pub const MONO_FONT_DEFAULT: f32 = 13.;
18pub const REFERENCE_REM: f32 = 14.;
22
23#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
25pub struct DensityPreview(pub bool);
26
27impl Global for DensityPreview {}
28
29#[derive(Debug, Clone, Copy, PartialEq)]
31pub struct Control {
32 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 pub default: f32,
41 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
70const 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
90pub 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 control(
115 "--tab-font",
116 "Tabs",
117 (10., 24., 0.5),
118 "px",
119 TAB_FONT_DEFAULT,
120 ),
121];
122
123pub 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
138pub fn format(control: &Control, value: f32) -> String {
141 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
150pub 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
164pub const SWITCH_OFF: f32 = 0.;
166pub const SWITCH_ON: f32 = 1.;
167
168impl Control {
169 pub fn is_switch(&self) -> bool {
172 self.unit.is_empty() && self.choices.is_empty()
173 }
174
175 pub fn is_choice(&self) -> bool {
177 !self.choices.is_empty()
178 }
179}
180
181#[derive(Debug, Clone, Default, PartialEq)]
183pub struct Density {
184 overrides: BTreeMap<&'static str, f32>,
185}
186
187impl Global for Density {}
188
189impl Density {
190 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 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 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 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 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}