aienux
Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately.
Brought by drakestapleton
aienux / crates / allen-design-tokens / src / lib.rs
| 1 | //! Allen's design tokens: one file in, three files out. |
| 2 | //! |
| 3 | //! `docs/design/DESIGN.md` (Google's DESIGN.md format) holds every colour, size, clock and curve of Allen's |
| 4 | //! look. Its YAML front matter carries the tokens the DESIGN.md tools know (colors, typography, rounded, |
| 5 | //! spacing, components); fenced blocks marked `allen-tokens` in its body carry the rest (motion, heartbeat, |
| 6 | //! boot, sound, contrast floors, reduced motion, keys). This crate reads both, resolves `{group.name}` |
| 7 | //! references, checks the contrast floors, and writes: |
| 8 | //! |
| 9 | //! - `allen_tokens.h` for the C kernel (integers only: colours packed as `CK_RGB`, durations in ms, |
| 10 | //! ratios in Q8 / Q15 / Q16 fixed point, Bezier curves in Q16), |
| 11 | //! - `allen_tokens.rs` for the Rust runners (core types only, so `no_std` code can `include!` it), |
| 12 | //! - `allen-tokens.css` for web surfaces (custom properties, with a reduced-motion block). |
| 13 | //! |
| 14 | //! Only the YAML subset DESIGN.md uses is read: nested maps by two-space indent, `key: value` scalars, |
| 15 | //! optional double quotes. Anything else is an error, never a silent skip. |
| 16 | |
| 17 | use std::fmt::Write as _; |
| 18 | |
| 19 | /// One token: its dotted path (`colors.night`, `motion.letter`) and its value as written. |
| 20 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 21 | pub struct Token { |
| 22 | pub path: String, |
| 23 | pub raw: String, |
| 24 | } |
| 25 | |
| 26 | /// A value, typed by its look. |
| 27 | #[derive(Debug, Clone, PartialEq)] |
| 28 | pub enum Value { |
| 29 | Color(u8, u8, u8), |
| 30 | /// A number and its unit (`px`, `ms`, `Hz`, `em`), as written. |
| 31 | Dim(f64, String), |
| 32 | /// A plain number, written quoted (`"0.030"`). |
| 33 | Ratio(f64), |
| 34 | /// `cubic-bezier(x1, y1, x2, y2)`. |
| 35 | Bezier([f64; 4]), |
| 36 | Text(String), |
| 37 | } |
| 38 | |
| 39 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 40 | pub struct Error(pub String); |
| 41 | |
| 42 | impl std::fmt::Display for Error { |
| 43 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 44 | f.write_str(&self.0) |
| 45 | } |
| 46 | } |
| 47 | |
| 48 | impl std::error::Error for Error {} |
| 49 | |
| 50 | fn err<T>(msg: impl Into<String>) -> Result<T, Error> { |
| 51 | Err(Error(msg.into())) |
| 52 | } |
| 53 | |
| 54 | /// All tokens of one DESIGN.md, in the order written, references resolved. |
| 55 | #[derive(Debug, Clone, Default)] |
| 56 | pub struct Tokens { |
| 57 | pub tokens: Vec<Token>, |
| 58 | } |
| 59 | |
| 60 | impl Tokens { |
| 61 | pub fn get(&self, path: &str) -> Option<&str> { |
| 62 | self.tokens |
| 63 | .iter() |
| 64 | .find(|t| t.path == path) |
| 65 | .map(|t| t.raw.as_str()) |
| 66 | } |
| 67 | |
| 68 | /// The tokens of one top-level group (`colors`), with the group prefix removed. |
| 69 | pub fn group<'a>(&'a self, group: &'a str) -> impl Iterator<Item = (&'a str, &'a str)> + 'a { |
| 70 | self.tokens.iter().filter_map(move |t| { |
| 71 | t.path |
| 72 | .strip_prefix(group) |
| 73 | .and_then(|rest| rest.strip_prefix('.')) |
| 74 | .map(|rest| (rest, t.raw.as_str())) |
| 75 | }) |
| 76 | } |
| 77 | |
| 78 | pub fn groups(&self) -> Vec<&str> { |
| 79 | let mut out: Vec<&str> = Vec::new(); |
| 80 | for t in &self.tokens { |
| 81 | let g = t.path.split('.').next().unwrap_or(""); |
| 82 | if !out.contains(&g) { |
| 83 | out.push(g); |
| 84 | } |
| 85 | } |
| 86 | out |
| 87 | } |
| 88 | } |
| 89 | |
| 90 | /// Reads the YAML subset: returns (path, value) pairs for every scalar, in order. |
| 91 | fn parse_yaml(text: &str, first_line: usize) -> Result<Vec<Token>, Error> { |
| 92 | let mut out = Vec::new(); |
| 93 | let mut stack: Vec<(usize, String)> = Vec::new(); |
| 94 | for (i, line) in text.lines().enumerate() { |
| 95 | let n = first_line + i; |
| 96 | let body = line.trim_end(); |
| 97 | if body.trim().is_empty() || body.trim_start().starts_with('#') { |
| 98 | continue; |
| 99 | } |
| 100 | let indent = body.len() - body.trim_start().len(); |
| 101 | if !indent.is_multiple_of(2) { |
| 102 | return err(format!("line {n}: indent must be a multiple of two spaces")); |
| 103 | } |
| 104 | let Some((key, value)) = body.trim_start().split_once(':') else { |
| 105 | return err(format!("line {n}: expected `key: value`")); |
| 106 | }; |
| 107 | let key = key.trim(); |
| 108 | if key.is_empty() || key.contains(' ') { |
| 109 | return err(format!("line {n}: bad key `{key}`")); |
| 110 | } |
| 111 | while stack.last().is_some_and(|(d, _)| *d >= indent) { |
| 112 | stack.pop(); |
| 113 | } |
| 114 | if stack.len() * 2 != indent { |
| 115 | return err(format!("line {n}: indent jumps a level")); |
| 116 | } |
| 117 | let path = stack |
| 118 | .iter() |
| 119 | .map(|(_, k)| k.as_str()) |
| 120 | .chain(std::iter::once(key)) |
| 121 | .collect::<Vec<_>>() |
| 122 | .join("."); |
| 123 | let value = value.trim(); |
| 124 | if value.is_empty() { |
| 125 | stack.push((indent, key.to_string())); |
| 126 | continue; |
| 127 | } |
| 128 | let raw = match value.strip_prefix('"') { |
| 129 | Some(rest) => match rest.strip_suffix('"') { |
| 130 | Some(inner) => inner.to_string(), |
| 131 | None => return err(format!("line {n}: unclosed quote")), |
| 132 | }, |
| 133 | None => value.to_string(), |
| 134 | }; |
| 135 | out.push(Token { path, raw }); |
| 136 | } |
| 137 | Ok(out) |
| 138 | } |
| 139 | |
| 140 | /// Reads a DESIGN.md: the front matter and every ```allen-tokens block. |
| 141 | pub fn parse(design_md: &str) -> Result<Tokens, Error> { |
| 142 | let Some(rest) = design_md.strip_prefix("---\n") else { |
| 143 | return err("DESIGN.md must start with a `---` front matter line"); |
| 144 | }; |
| 145 | let Some(end) = rest.find("\n---\n") else { |
| 146 | return err("front matter has no closing `---`"); |
| 147 | }; |
| 148 | let mut tokens = parse_yaml(&rest[..end], 2)?; |
| 149 | let body_start = 4 + end + 5; |
| 150 | let body = &design_md[body_start..]; |
| 151 | let body_first_line = design_md[..body_start].lines().count() + 1; |
| 152 | let mut lines = body.lines().enumerate(); |
| 153 | while let Some((i, line)) = lines.next() { |
| 154 | if line.trim_end() != "```allen-tokens" { |
| 155 | continue; |
| 156 | } |
| 157 | let mut block = String::new(); |
| 158 | let mut closed = false; |
| 159 | for (_, l) in lines.by_ref() { |
| 160 | if l.trim_end() == "```" { |
| 161 | closed = true; |
| 162 | break; |
| 163 | } |
| 164 | block.push_str(l); |
| 165 | block.push('\n'); |
| 166 | } |
| 167 | if !closed { |
| 168 | return err(format!( |
| 169 | "allen-tokens block at line {} is not closed", |
| 170 | body_first_line + i |
| 171 | )); |
| 172 | } |
| 173 | tokens.extend(parse_yaml(&block, body_first_line + i + 1)?); |
| 174 | } |
| 175 | for (i, t) in tokens.iter().enumerate() { |
| 176 | if tokens[..i].iter().any(|u| u.path == t.path) { |
| 177 | return err(format!("token `{}` is defined twice", t.path)); |
| 178 | } |
| 179 | } |
| 180 | let mut out = Tokens { tokens }; |
| 181 | resolve(&mut out)?; |
| 182 | Ok(out) |
| 183 | } |
| 184 | |
| 185 | fn resolve(t: &mut Tokens) -> Result<(), Error> { |
| 186 | for i in 0..t.tokens.len() { |
| 187 | let mut raw = t.tokens[i].raw.clone(); |
| 188 | let mut hops = 0; |
| 189 | while let Some(target) = raw.strip_prefix('{').and_then(|r| r.strip_suffix('}')) { |
| 190 | hops += 1; |
| 191 | if hops > 8 { |
| 192 | return err(format!("`{}`: reference loop", t.tokens[i].path)); |
| 193 | } |
| 194 | let found = match t.get(target) { |
| 195 | Some(v) => v.to_string(), |
| 196 | None if t.group(target).next().is_some() => { |
| 197 | // a whole group (a typography role): keep the reference, emitters expand it |
| 198 | break; |
| 199 | } |
| 200 | None => { |
| 201 | return err(format!( |
| 202 | "`{}` points at `{target}`, which does not exist", |
| 203 | t.tokens[i].path |
| 204 | )) |
| 205 | } |
| 206 | }; |
| 207 | raw = found; |
| 208 | } |
| 209 | t.tokens[i].raw = raw; |
| 210 | } |
| 211 | Ok(()) |
| 212 | } |
| 213 | |
| 214 | fn hex2(s: &str) -> Option<u8> { |
| 215 | u8::from_str_radix(s, 16).ok() |
| 216 | } |
| 217 | |
| 218 | /// Types a raw value by its look. |
| 219 | pub fn value(raw: &str) -> Value { |
| 220 | if let Some(h) = raw.strip_prefix('#') { |
| 221 | if h.len() == 6 { |
| 222 | if let (Some(r), Some(g), Some(b)) = (hex2(&h[0..2]), hex2(&h[2..4]), hex2(&h[4..6])) { |
| 223 | return Value::Color(r, g, b); |
| 224 | } |
| 225 | } |
| 226 | } |
| 227 | if let Some(args) = raw |
| 228 | .strip_prefix("cubic-bezier(") |
| 229 | .and_then(|r| r.strip_suffix(')')) |
| 230 | { |
| 231 | let v: Vec<f64> = args |
| 232 | .split(',') |
| 233 | .filter_map(|a| a.trim().parse().ok()) |
| 234 | .collect(); |
| 235 | if v.len() == 4 { |
| 236 | return Value::Bezier([v[0], v[1], v[2], v[3]]); |
| 237 | } |
| 238 | } |
| 239 | if let Ok(n) = raw.parse::<f64>() { |
| 240 | return Value::Ratio(n); |
| 241 | } |
| 242 | let split = raw |
| 243 | .find(|c: char| !(c.is_ascii_digit() || c == '.' || c == '-')) |
| 244 | .unwrap_or(raw.len()); |
| 245 | if split > 0 { |
| 246 | if let Ok(n) = raw[..split].parse::<f64>() { |
| 247 | let unit = &raw[split..]; |
| 248 | if unit.chars().all(|c| c.is_ascii_alphabetic()) { |
| 249 | return Value::Dim(n, unit.to_string()); |
| 250 | } |
| 251 | } |
| 252 | } |
| 253 | Value::Text(raw.to_string()) |
| 254 | } |
| 255 | |
| 256 | /// WCAG 2.2 relative luminance of an sRGB colour. |
| 257 | pub fn luminance(r: u8, g: u8, b: u8) -> f64 { |
| 258 | let lin = |c: u8| { |
| 259 | let c = f64::from(c) / 255.0; |
| 260 | if c <= 0.04045 { |
| 261 | c / 12.92 |
| 262 | } else { |
| 263 | ((c + 0.055) / 1.055).powf(2.4) |
| 264 | } |
| 265 | }; |
| 266 | 0.2126 * lin(r) + 0.7152 * lin(g) + 0.0722 * lin(b) |
| 267 | } |
| 268 | |
| 269 | /// WCAG contrast ratio between two colours (1.0 to 21.0). |
| 270 | pub fn contrast(a: (u8, u8, u8), b: (u8, u8, u8)) -> f64 { |
| 271 | let (la, lb) = (luminance(a.0, a.1, a.2), luminance(b.0, b.1, b.2)); |
| 272 | let (hi, lo) = if la > lb { (la, lb) } else { (lb, la) }; |
| 273 | (hi + 0.05) / (lo + 0.05) |
| 274 | } |
| 275 | |
| 276 | /// One measured pair from the `contrast` group. |
| 277 | #[derive(Debug, Clone)] |
| 278 | pub struct ContrastResult { |
| 279 | pub fg: String, |
| 280 | pub bg: String, |
| 281 | /// Opacity the foreground is drawn at (1.0 opaque). |
| 282 | pub alpha: f64, |
| 283 | pub ratio: f64, |
| 284 | pub floor: f64, |
| 285 | /// Gated pairs fail the build below their floor; report-only pairs (the kernel today) do not. |
| 286 | pub gated: bool, |
| 287 | } |
| 288 | |
| 289 | impl ContrastResult { |
| 290 | pub fn passes(&self) -> bool { |
| 291 | self.ratio >= self.floor |
| 292 | } |
| 293 | } |
| 294 | |
| 295 | /// The foreground as it lands on the background when drawn at `alpha` (sRGB blend, as the kernel does). |
| 296 | pub fn blend(fg: (u8, u8, u8), bg: (u8, u8, u8), alpha: f64) -> (u8, u8, u8) { |
| 297 | let mix = |f: u8, b: u8| (f64::from(b) + (f64::from(f) - f64::from(b)) * alpha).round() as u8; |
| 298 | (mix(fg.0, bg.0), mix(fg.1, bg.1), mix(fg.2, bg.2)) |
| 299 | } |
| 300 | |
| 301 | fn alpha_of(t: &Tokens, group: &str, name: &str) -> Result<Option<f64>, Error> { |
| 302 | match t.get(&format!("{group}.{name}")).map(value) { |
| 303 | None => Ok(None), |
| 304 | Some(Value::Ratio(a)) if (0.0..=1.0).contains(&a) => Ok(Some(a)), |
| 305 | Some(_) => err(format!("{group}.{name}: must be a number from 0 to 1")), |
| 306 | } |
| 307 | } |
| 308 | |
| 309 | fn color_of(t: &Tokens, name: &str) -> Result<(u8, u8, u8), Error> { |
| 310 | match t.get(&format!("colors.{name}")).map(value) { |
| 311 | Some(Value::Color(r, g, b)) => Ok((r, g, b)), |
| 312 | _ => err(format!( |
| 313 | "contrast pair names `{name}`, which is not a colour" |
| 314 | )), |
| 315 | } |
| 316 | } |
| 317 | |
| 318 | /// Measures every `contrast.<fg>-on-<bg>` pair against its floor. |
| 319 | pub fn check_contrast(t: &Tokens) -> Result<Vec<ContrastResult>, Error> { |
| 320 | let mut out = Vec::new(); |
| 321 | for (pair, floor) in t.group("contrast") { |
| 322 | let Some((fg, bg)) = pair.split_once("-on-") else { |
| 323 | return err(format!("contrast.{pair}: name must be <fg>-on-<bg>")); |
| 324 | }; |
| 325 | let Value::Ratio(floor) = value(floor) else { |
| 326 | return err(format!("contrast.{pair}: floor must be a number")); |
| 327 | }; |
| 328 | let (f, b) = (color_of(t, fg)?, color_of(t, bg)?); |
| 329 | let alpha = alpha_of(t, "drawn-alpha", fg)?.unwrap_or(1.0); |
| 330 | out.push(ContrastResult { |
| 331 | fg: fg.to_string(), |
| 332 | bg: bg.to_string(), |
| 333 | alpha, |
| 334 | ratio: contrast(blend(f, b, alpha), b), |
| 335 | floor, |
| 336 | gated: true, |
| 337 | }); |
| 338 | if let Some(today) = alpha_of(t, "kernel-today-alpha", fg)? { |
| 339 | out.push(ContrastResult { |
| 340 | fg: fg.to_string(), |
| 341 | bg: bg.to_string(), |
| 342 | alpha: today, |
| 343 | ratio: contrast(blend(f, b, today), b), |
| 344 | floor, |
| 345 | gated: false, |
| 346 | }); |
| 347 | } |
| 348 | } |
| 349 | Ok(out) |
| 350 | } |
| 351 | |
| 352 | /// The contrast report written next to the exports. |
| 353 | pub fn contrast_report(results: &[ContrastResult]) -> String { |
| 354 | let mut s = String::from( |
| 355 | "# Generated from docs/design/DESIGN.md by allen-design-tokens. Do not edit.\n\ |
| 356 | # WCAG 2.2 contrast of each declared pair (foreground on background), measured as drawn:\n\ |
| 357 | # the foreground blended over the background at its drawing opacity first.\n\ |
| 358 | # REPORT lines are the kernel as it draws today; they do not gate the build.\n", |
| 359 | ); |
| 360 | for r in results { |
| 361 | let _ = writeln!( |
| 362 | s, |
| 363 | "{:<10} on {:<6} at {:>5.3} {:>6.2}:1 floor {:>4.1} {}", |
| 364 | r.fg, |
| 365 | r.bg, |
| 366 | r.alpha, |
| 367 | r.ratio, |
| 368 | r.floor, |
| 369 | match (r.gated, r.passes()) { |
| 370 | (true, true) => "PASS", |
| 371 | (true, false) => "FAIL", |
| 372 | (false, true) => "REPORT pass", |
| 373 | (false, false) => "REPORT below floor", |
| 374 | } |
| 375 | ); |
| 376 | } |
| 377 | s |
| 378 | } |
| 379 | |
| 380 | fn ident(path: &str) -> String { |
| 381 | path.chars() |
| 382 | .map(|c| { |
| 383 | if c.is_ascii_alphanumeric() { |
| 384 | c.to_ascii_uppercase() |
| 385 | } else { |
| 386 | '_' |
| 387 | } |
| 388 | }) |
| 389 | .collect() |
| 390 | } |
| 391 | |
| 392 | fn q(v: f64, one: f64) -> i64 { |
| 393 | (v * one).round() as i64 |
| 394 | } |
| 395 | |
| 396 | const HEADER: &str = "Generated from docs/design/DESIGN.md by allen-design-tokens. Do not edit; change DESIGN.md and run\n `cargo run -p allen-design-tokens -- generate`."; |
| 397 | |
| 398 | /// The C header: integers only, for the kernel. |
| 399 | pub fn emit_c(t: &Tokens) -> String { |
| 400 | let mut s = format!( |
| 401 | "/* allen_tokens.h -- Allen's look as numbers.\n * {}\n * Colours are packed as CK_RGB (r << 16 | g << 8 | b). Durations in ms. Ratios in Q8 (/256), Q15 (/32767)\n * and Q16 (/65536). Bezier control points in Q16. */\n#ifndef AIENOS_ALLEN_TOKENS_H\n#define AIENOS_ALLEN_TOKENS_H\n", |
| 402 | HEADER.replace('\n', "\n *") |
| 403 | ); |
| 404 | for g in t.groups() { |
| 405 | let _ = write!(s, "\n/* {g} */\n"); |
| 406 | for (name, raw) in t.group(g) { |
| 407 | let id = format!("ALLEN_{}_{}", ident(g), ident(name)); |
| 408 | match value(raw) { |
| 409 | Value::Color(r, gg, b) => { |
| 410 | let _ = writeln!(s, "#define {id} 0x{r:02X}{gg:02X}{b:02X}u"); |
| 411 | } |
| 412 | Value::Dim(n, unit) => { |
| 413 | let unit_id = ident(&unit); |
| 414 | if n.fract() == 0.0 && n >= 0.0 { |
| 415 | let _ = writeln!(s, "#define {id}_{unit_id} {}u", n as i64); |
| 416 | } else { |
| 417 | let _ = writeln!(s, "#define {id}_{unit_id}_X1000 {}", q(n, 1000.0)); |
| 418 | } |
| 419 | } |
| 420 | Value::Ratio(n) if n.fract() == 0.0 && n.abs() >= 2.0 => { |
| 421 | let _ = writeln!(s, "#define {id} {}", n as i64); |
| 422 | } |
| 423 | Value::Ratio(n) => { |
| 424 | let _ = writeln!(s, "#define {id}_Q8 {}", q(n, 256.0)); |
| 425 | let _ = writeln!(s, "#define {id}_Q15 {}", q(n, 32767.0)); |
| 426 | let _ = writeln!(s, "#define {id}_Q16 {}", q(n, 65536.0)); |
| 427 | } |
| 428 | Value::Bezier(p) => { |
| 429 | for (k, v) in ["X1", "Y1", "X2", "Y2"].iter().zip(p) { |
| 430 | let _ = writeln!(s, "#define {id}_{k}_Q16 {}", q(v, 65536.0)); |
| 431 | } |
| 432 | } |
| 433 | Value::Text(text) => { |
| 434 | if let Some(role) = text.strip_prefix('{').and_then(|r| r.strip_suffix('}')) { |
| 435 | let _ = writeln!(s, "/* {id}: {role} */"); |
| 436 | } else { |
| 437 | let _ = writeln!(s, "#define {id} \"{}\"", text.replace('"', "\\\"")); |
| 438 | } |
| 439 | } |
| 440 | } |
| 441 | } |
| 442 | } |
| 443 | s.push_str("\n#endif\n"); |
| 444 | s |
| 445 | } |
| 446 | |
| 447 | /// The Rust module: core types only. |
| 448 | pub fn emit_rust(t: &Tokens) -> String { |
| 449 | let mut s = format!( |
| 450 | "// allen_tokens.rs -- Allen's look as constants.\n// {}\n// Core types only, so no_std code can include!() this file.\n\n\ |
| 451 | /// An sRGB colour.\n#[derive(Debug, Clone, Copy, PartialEq, Eq)]\npub struct Rgb {{\n pub r: u8,\n pub g: u8,\n pub b: u8,\n}}\n\n\ |
| 452 | impl Rgb {{\n /// Packed as the kernel's CK_RGB.\n pub const fn packed(self) -> u32 {{\n (self.r as u32) << 16 | (self.g as u32) << 8 | self.b as u32\n }}\n}}\n\n\ |
| 453 | /// A CSS cubic-bezier easing curve, control points in Q16 (65536 = 1.0).\n#[derive(Debug, Clone, Copy, PartialEq, Eq)]\npub struct Bezier {{\n pub x1: i32,\n pub y1: i32,\n pub x2: i32,\n pub y2: i32,\n}}\n", |
| 454 | HEADER.replace('\n', "\n//") |
| 455 | ); |
| 456 | for g in t.groups() { |
| 457 | let module = g.replace('-', "_"); |
| 458 | let _ = write!(s, "\npub mod {module} {{\n #[allow(unused_imports)]\n use super::{{Bezier, Rgb}};\n"); |
| 459 | for (name, raw) in t.group(g) { |
| 460 | let id = ident(name); |
| 461 | let line = match value(raw) { |
| 462 | Value::Color(r, gg, b) => { |
| 463 | format!("pub const {id}: Rgb = Rgb {{ r: {r}, g: {gg}, b: {b} }};") |
| 464 | } |
| 465 | Value::Dim(n, unit) => { |
| 466 | let unit_id = ident(&unit); |
| 467 | if n.fract() == 0.0 && n >= 0.0 { |
| 468 | format!("pub const {id}_{unit_id}: u32 = {};", n as i64) |
| 469 | } else { |
| 470 | format!("pub const {id}_{unit_id}: f32 = {n:?};") |
| 471 | } |
| 472 | } |
| 473 | Value::Ratio(n) if n.fract() == 0.0 && n.abs() >= 2.0 => { |
| 474 | format!("pub const {id}: u32 = {};", n as i64) |
| 475 | } |
| 476 | Value::Ratio(n) => format!( |
| 477 | "pub const {id}: f32 = {n:?};\n pub const {id}_Q16: i32 = {};", |
| 478 | q(n, 65536.0) |
| 479 | ), |
| 480 | Value::Bezier(p) => format!( |
| 481 | "pub const {id}: Bezier = Bezier {{ x1: {}, y1: {}, x2: {}, y2: {} }};", |
| 482 | q(p[0], 65536.0), |
| 483 | q(p[1], 65536.0), |
| 484 | q(p[2], 65536.0), |
| 485 | q(p[3], 65536.0) |
| 486 | ), |
| 487 | Value::Text(text) => { |
| 488 | if let Some(role) = text.strip_prefix('{').and_then(|r| r.strip_suffix('}')) { |
| 489 | format!("// {id}: {role}") |
| 490 | } else { |
| 491 | format!("pub const {id}: &str = {text:?};") |
| 492 | } |
| 493 | } |
| 494 | }; |
| 495 | let _ = writeln!(s, " {line}"); |
| 496 | } |
| 497 | s.push_str("}\n"); |
| 498 | } |
| 499 | s |
| 500 | } |
| 501 | |
| 502 | /// The CSS custom properties. |
| 503 | pub fn emit_css(t: &Tokens) -> String { |
| 504 | let var = |g: &str, name: &str| format!("--allen-{g}-{name}").replace('.', "-"); |
| 505 | let css_value = |raw: &str| -> String { |
| 506 | if let Some(role) = raw.strip_prefix('{').and_then(|r| r.strip_suffix('}')) { |
| 507 | return format!("var(--allen-{})", role.replace('.', "-")); |
| 508 | } |
| 509 | match value(raw) { |
| 510 | Value::Text(text) if text.contains(' ') && !text.contains('(') => format!("\"{text}\""), |
| 511 | _ => raw.to_string(), |
| 512 | } |
| 513 | }; |
| 514 | let mut s = format!( |
| 515 | "/* allen-tokens.css -- Allen's look as CSS custom properties.\n {HEADER} */\n:root {{\n" |
| 516 | ); |
| 517 | for g in t.groups() { |
| 518 | if g == "reduced-motion" { |
| 519 | continue; |
| 520 | } |
| 521 | let _ = writeln!(s, " /* {g} */"); |
| 522 | for (name, raw) in t.group(g) { |
| 523 | let name_v = if g == "typography" && name.ends_with(".fontFamily") { |
| 524 | let _ = writeln!( |
| 525 | s, |
| 526 | " {}: \"{raw}\", ui-rounded, system-ui, sans-serif;", |
| 527 | var(g, name) |
| 528 | ); |
| 529 | continue; |
| 530 | } else { |
| 531 | css_value(raw) |
| 532 | }; |
| 533 | let _ = writeln!(s, " {}: {name_v};", var(g, name)); |
| 534 | if let Value::Color(r, gg, b) = value(raw) { |
| 535 | let _ = writeln!(s, " {}-rgb: {r} {gg} {b};", var(g, name)); |
| 536 | } |
| 537 | } |
| 538 | } |
| 539 | s.push_str("}\n\n@media (prefers-reduced-motion: reduce) {\n :root {\n"); |
| 540 | for (name, raw) in t.group("reduced-motion") { |
| 541 | let target = ["motion", "heartbeat", "boot"] |
| 542 | .iter() |
| 543 | .find(|g| t.get(&format!("{g}.{name}")).is_some()) |
| 544 | .map(|g| var(g, name)) |
| 545 | .unwrap_or_else(|| var("reduced-motion", name)); |
| 546 | let _ = writeln!(s, " {target}: {};", css_value(raw)); |
| 547 | } |
| 548 | s.push_str(" }\n}\n"); |
| 549 | s |
| 550 | } |
| 551 | |
| 552 | /// Every file the generator writes, by name. |
| 553 | pub fn outputs(t: &Tokens) -> Result<Vec<(&'static str, String)>, Error> { |
| 554 | let results = check_contrast(t)?; |
| 555 | Ok(vec![ |
| 556 | ("allen_tokens.h", emit_c(t)), |
| 557 | ("allen_tokens.rs", emit_rust(t)), |
| 558 | ("allen-tokens.css", emit_css(t)), |
| 559 | ("contrast.txt", contrast_report(&results)), |
| 560 | ]) |
| 561 | } |
| 562 | |
| 563 | #[cfg(test)] |
| 564 | mod tests { |
| 565 | use super::*; |
| 566 | |
| 567 | const MINI: &str = "---\nname: T\ncolors:\n primary: \"#ECF0FC\"\n night: \"#060812\"\ncomponents:\n page:\n backgroundColor: \"{colors.night}\"\n---\n\n## Motion\n\n```allen-tokens\nmotion:\n letter: 35ms\n ease-smooth: \"cubic-bezier(0.3333, 0, 0.6667, 1)\"\ncontrast:\n primary-on-night: \"7.0\"\n```\n"; |
| 568 | |
| 569 | #[test] |
| 570 | fn reads_front_matter_and_blocks() { |
| 571 | let t = parse(MINI).unwrap(); |
| 572 | assert_eq!(t.get("colors.night"), Some("#060812")); |
| 573 | assert_eq!(t.get("components.page.backgroundColor"), Some("#060812")); |
| 574 | assert_eq!(t.get("motion.letter"), Some("35ms")); |
| 575 | } |
| 576 | |
| 577 | #[test] |
| 578 | fn broken_reference_is_an_error() { |
| 579 | let bad = MINI.replace("{colors.night}", "{colors.nope}"); |
| 580 | assert!(parse(&bad).is_err()); |
| 581 | } |
| 582 | |
| 583 | #[test] |
| 584 | fn duplicate_token_is_an_error() { |
| 585 | let bad = MINI.replace(" letter: 35ms\n", " letter: 35ms\n letter: 36ms\n"); |
| 586 | assert!(parse(&bad).is_err()); |
| 587 | } |
| 588 | |
| 589 | #[test] |
| 590 | fn wcag_reference_values() { |
| 591 | // black on white is 21:1 by definition; equal colours are 1:1 |
| 592 | assert!((contrast((0, 0, 0), (255, 255, 255)) - 21.0).abs() < 1e-9); |
| 593 | assert!((contrast((6, 8, 18), (6, 8, 18)) - 1.0).abs() < 1e-9); |
| 594 | } |
| 595 | |
| 596 | #[test] |
| 597 | fn smoothstep_bezier_is_exact() { |
| 598 | // x(s) = s for control x 1/3, 2/3, so y(s) = 3s^2 - 2s^3 = ck_smooth |
| 599 | let y = |s: f64| 3.0 * (1.0 - s) * s * s + s * s * s; |
| 600 | for i in 0..=10 { |
| 601 | let s = f64::from(i) / 10.0; |
| 602 | assert!((y(s) - (3.0 * s * s - 2.0 * s * s * s)).abs() < 1e-12); |
| 603 | } |
| 604 | } |
| 605 | |
| 606 | #[test] |
| 607 | fn c_export_is_integer_only() { |
| 608 | let t = parse(MINI).unwrap(); |
| 609 | let c = emit_c(&t); |
| 610 | assert!(c.contains("#define ALLEN_COLORS_NIGHT 0x060812u")); |
| 611 | assert!(c.contains("#define ALLEN_MOTION_LETTER_MS 35u")); |
| 612 | assert!(c.contains("#define ALLEN_MOTION_EASE_SMOOTH_X1_Q16 21843")); |
| 613 | assert!( |
| 614 | !c.contains('.') |
| 615 | || c.lines() |
| 616 | .all(|l| !l.starts_with("#define") || !l.contains('.')) |
| 617 | ); |
| 618 | } |
| 619 | } |