mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-17 05:14:24 +00:00
172 lines
6.4 KiB
Rust
172 lines
6.4 KiB
Rust
//! Token dumps: every token of every built-in, as text under `tests/dumps/tokens/`, so a change
|
|
//! to derivation or a theme file shows up as a reviewable diff.
|
|
//!
|
|
//! One file per built-in, mode it has, contrast and size, at the default text size. Run
|
|
//! `UPDATE_DUMPS=1 cargo test -p craft-theme dump` to rewrite them.
|
|
//!
|
|
//! The struct destructuring below is exhaustive on purpose: a new token doesn't compile until it
|
|
//! is dumped.
|
|
|
|
use std::collections::BTreeSet;
|
|
use std::fmt::Write as _;
|
|
use std::path::{Path, PathBuf};
|
|
|
|
use craft_theme::dump::tokens_text;
|
|
use craft_theme::{
|
|
AppSizes, Appearance, Contrast, ContrastCheck, Mode, Size, TextSize, ThemeDef, Tokens, Variants, builtins, resolve, resolve_sized,
|
|
};
|
|
|
|
const HEADER: &str = "# Generated by crates/theme/tests/dumps.rs; rewrite with UPDATE_DUMPS=1 cargo test -p craft-theme dump";
|
|
|
|
/// Every built-in theme variant, resolved, with its dump file name.
|
|
fn resolved_variants() -> Vec<(String, Tokens, Vec<ContrastCheck>)> {
|
|
let mut out = Vec::new();
|
|
for theme in builtins() {
|
|
for mode in modes(theme) {
|
|
for contrast in [Contrast::Standard, Contrast::High] {
|
|
for size in [Size::Compact, Size::Comfortable] {
|
|
let appearance = Appearance { mode, contrast, size, text_size: TextSize::Small, reduced_motion: false };
|
|
let resolved = resolve(theme, appearance, None);
|
|
let name = format!("{}-{}-{}-{}.txt", short_name(theme), mode_name(mode), contrast_name(contrast), size_name(size));
|
|
out.push((name, resolved.tokens, resolved.warnings));
|
|
}
|
|
}
|
|
}
|
|
}
|
|
out
|
|
}
|
|
|
|
#[test]
|
|
fn token_dumps() {
|
|
let dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/dumps/tokens");
|
|
let mut files: Vec<(String, String)> =
|
|
resolved_variants().iter().map(|(name, tokens, warnings)| (name.clone(), dump(tokens, warnings))).collect();
|
|
files.push(app_sizes_dump());
|
|
check_dir(&dir, &files);
|
|
}
|
|
|
|
/// The sample app's size overrides: a base override for both sets and one for Comfortable.
|
|
const SAMPLE_SIZES: &str = r#"{ "all": { "size.control.md": 28 }, "comfortable": { "space.pad.regular": 14 } }"#;
|
|
|
|
/// Comfortable with [`SAMPLE_SIZES`]: the app's base overrides on one theme.
|
|
fn app_sizes_dump() -> (String, String) {
|
|
let sizes = AppSizes::parse(SAMPLE_SIZES.as_bytes()).unwrap();
|
|
let theme = builtins().iter().find(|t| t.id.as_str() == "craft.pro").unwrap();
|
|
let appearance =
|
|
Appearance { mode: Mode::Dark, contrast: Contrast::Standard, size: Size::Comfortable, text_size: TextSize::Small, reduced_motion: false };
|
|
let resolved = resolve_sized(theme, appearance, None, &sizes);
|
|
("pro-dark-standard-comfortable-app-sizes.txt".to_owned(), dump(&resolved.tokens, &resolved.warnings))
|
|
}
|
|
|
|
fn modes(theme: &ThemeDef) -> Vec<Mode> {
|
|
match theme.variants {
|
|
Variants::Both => vec![Mode::Light, Mode::Dark],
|
|
Variants::LightOnly => vec![Mode::Light],
|
|
Variants::DarkOnly => vec![Mode::Dark],
|
|
}
|
|
}
|
|
|
|
fn short_name(theme: &ThemeDef) -> &str {
|
|
let id = theme.id.as_str();
|
|
id.strip_prefix("craft.").unwrap_or(id)
|
|
}
|
|
|
|
fn mode_name(mode: Mode) -> &'static str {
|
|
match mode {
|
|
Mode::Light => "light",
|
|
Mode::Dark => "dark",
|
|
}
|
|
}
|
|
|
|
fn contrast_name(contrast: Contrast) -> &'static str {
|
|
match contrast {
|
|
Contrast::Standard => "standard",
|
|
Contrast::High => "high",
|
|
}
|
|
}
|
|
|
|
fn size_name(size: Size) -> &'static str {
|
|
match size {
|
|
Size::Compact => "compact",
|
|
Size::Comfortable => "comfortable",
|
|
}
|
|
}
|
|
|
|
fn dump(tokens: &Tokens, warnings: &[ContrastCheck]) -> String {
|
|
let mut out = String::from(HEADER);
|
|
out.push('\n');
|
|
out.push_str(&tokens_text(tokens));
|
|
for w in warnings {
|
|
let ContrastCheck { fg, bg, ratio, minimum } = w;
|
|
let _ = writeln!(out, "warning = {} on {}: {ratio:.2} < {minimum:.2}", fg.path(), bg.path());
|
|
}
|
|
out
|
|
}
|
|
|
|
/// Compares `files` with the dump directory, or rewrites it with `UPDATE_DUMPS=1`. Files in the
|
|
/// directory that no longer belong to a dump are reported (and removed on update).
|
|
fn check_dir(dir: &Path, files: &[(String, String)]) {
|
|
let update = std::env::var_os("UPDATE_DUMPS").is_some_and(|v| v != "0");
|
|
let names: BTreeSet<&str> = files.iter().map(|(n, _)| n.as_str()).collect();
|
|
let stale: Vec<PathBuf> = std::fs::read_dir(dir)
|
|
.map(|entries| {
|
|
entries
|
|
.filter_map(Result::ok)
|
|
.map(|e| e.path())
|
|
.filter(|p| p.file_name().and_then(|n| n.to_str()).is_some_and(|n| !names.contains(n)))
|
|
.collect()
|
|
})
|
|
.unwrap_or_default();
|
|
|
|
if update {
|
|
std::fs::create_dir_all(dir).unwrap();
|
|
for (name, text) in files {
|
|
let path = dir.join(name);
|
|
if std::fs::read_to_string(&path).ok().as_deref() != Some(text) {
|
|
std::fs::write(&path, text).unwrap();
|
|
}
|
|
}
|
|
for path in stale {
|
|
std::fs::remove_file(path).unwrap();
|
|
}
|
|
return;
|
|
}
|
|
|
|
let mut report = String::new();
|
|
let mut failed = 0;
|
|
for (name, text) in files {
|
|
let path = dir.join(name);
|
|
match std::fs::read_to_string(&path) {
|
|
Ok(old) if old == *text => {}
|
|
Ok(old) => {
|
|
failed += 1;
|
|
if failed <= 3 {
|
|
let _ = writeln!(report, "{name}:\n{}", diff(&old, text));
|
|
}
|
|
}
|
|
Err(_) => {
|
|
failed += 1;
|
|
let _ = writeln!(report, "{name}: missing");
|
|
}
|
|
}
|
|
}
|
|
for path in &stale {
|
|
failed += 1;
|
|
let _ = writeln!(report, "{}: no longer generated", path.display());
|
|
}
|
|
assert!(failed == 0, "{failed} token dump(s) differ; rerun with UPDATE_DUMPS=1 to rewrite them and review the diff\n{report}");
|
|
}
|
|
|
|
/// The lines only in `old` (`-`) and only in `new` (`+`), at most 20.
|
|
fn diff(old: &str, new: &str) -> String {
|
|
let (a, b): (BTreeSet<&str>, BTreeSet<&str>) = (old.lines().collect(), new.lines().collect());
|
|
let removed = old.lines().filter(|l| !b.contains(l)).map(|l| format!("- {l}"));
|
|
let added = new.lines().filter(|l| !a.contains(l)).map(|l| format!("+ {l}"));
|
|
let all: Vec<String> = removed.chain(added).collect();
|
|
let mut out: Vec<String> = all.iter().take(20).cloned().collect();
|
|
if all.len() > 20 {
|
|
out.push(format!("… {} more", all.len() - 20));
|
|
}
|
|
out.join("\n")
|
|
}
|