design_tokens.rs 371 lignes · 14006 octets
//! Lecture des tokens de `design.md` et de `style/charte.yaml`, et génération du bloc
//! `@theme` Tailwind v4 (`tokens.css`).
//!
//! Ce module est compilé deux fois : par `build.rs` (via `#[path]`) pour générer le CSS,
//! et par la bibliothèque pour ses tests. Il ne dépend donc que de serde, serde_norway
//! et thiserror, présents dans les deux jeux de dépendances.

use std::collections::BTreeMap;

use serde::Deserialize;
use serde_norway::Value;

#[derive(Debug, thiserror::Error)]
pub enum TokenError {
    #[error("design.md doit commencer par un front matter YAML délimité par `---`")]
    MissingFrontMatter,
    #[error("YAML invalide : {0}")]
    Yaml(#[from] serde_norway::Error),
    #[error("référence inconnue `{{{0}}}`")]
    UnknownReference(String),
    #[error("token typographique `{field}` invalide pour `{token}`")]
    InvalidTypography { token: String, field: &'static str },
}

/// Tokens du front matter de `design.md` utilisés par le CSS.
#[derive(Debug)]
pub struct DesignSystem {
    pub colors: BTreeMap<String, String>,
    pub typography: BTreeMap<String, TypeToken>,
    pub rounded: BTreeMap<String, String>,
    pub spacing: BTreeMap<String, String>,
}

#[derive(Debug, Clone, PartialEq)]
pub struct TypeToken {
    pub font_size: String,
    pub font_weight: String,
    pub line_height: String,
    pub letter_spacing: String,
}

/// Extensions de la charte (`commun/style/charte.yaml`).
#[derive(Debug, Deserialize)]
pub struct Charte {
    pub colors: BTreeMap<String, String>,
    pub text: BTreeMap<String, String>,
    pub fonts: BTreeMap<String, String>,
    pub containers: BTreeMap<String, String>,
    pub shadows: BTreeMap<String, String>,
    pub breakpoints: BTreeMap<String, String>,
}

impl DesignSystem {
    pub fn parse(design_md: &str) -> Result<Self, TokenError> {
        let front_matter = design_md
            .strip_prefix("---\n")
            .and_then(|rest| rest.split_once("\n---\n"))
            .map(|(yaml, _)| yaml)
            .ok_or(TokenError::MissingFrontMatter)?;
        let root: BTreeMap<String, Value> = serde_norway::from_str(front_matter)?;
        let group = |name: &str| -> Result<BTreeMap<String, Value>, TokenError> {
            match root.get(name) {
                Some(value) => Ok(serde_norway::from_value(value.clone())?),
                None => Ok(BTreeMap::new()),
            }
        };
        let scalars = |name: &str| -> Result<BTreeMap<String, String>, TokenError> {
            Ok(group(name)?.into_iter().filter_map(|(k, v)| scalar(&v).map(|v| (k, v))).collect())
        };

        let mut typography = BTreeMap::new();
        for (token, value) in group("typography")? {
            let fields: BTreeMap<String, Value> = serde_norway::from_value(value)?;
            let field = |field: &'static str| {
                fields
                    .get(field)
                    .and_then(scalar)
                    .ok_or_else(|| TokenError::InvalidTypography { token: token.clone(), field })
            };
            typography.insert(
                token.clone(),
                TypeToken {
                    font_size: field("fontSize")?,
                    font_weight: field("fontWeight")?,
                    line_height: field("lineHeight")?,
                    letter_spacing: field("letterSpacing")?,
                },
            );
        }

        Ok(Self {
            colors: scalars("colors")?,
            typography,
            rounded: scalars("rounded")?,
            spacing: scalars("spacing")?,
        })
    }

    /// Références `{groupe.cle}` du texte qui ne désignent aucun token connu.
    pub fn unknown_references(&self, text: &str) -> Vec<String> {
        references(text).filter(|reference| !self.knows(reference)).map(str::to_owned).collect()
    }

    fn knows(&self, reference: &str) -> bool {
        let Some((group, key)) = reference.split_once('.') else {
            return false;
        };
        match group {
            "colors" => self.colors.contains_key(key),
            "typography" => self.typography.contains_key(key),
            "rounded" => self.rounded.contains_key(key),
            "spacing" => self.spacing.contains_key(key),
            _ => false,
        }
    }

    fn color(&self, value: &str) -> Result<String, TokenError> {
        match value.strip_prefix('{').and_then(|v| v.strip_suffix('}')) {
            Some(reference) => reference
                .strip_prefix("colors.")
                .and_then(|key| self.colors.get(key))
                .cloned()
                .ok_or_else(|| TokenError::UnknownReference(reference.to_owned())),
            None => Ok(value.to_owned()),
        }
    }
}

/// Valeur scalaire YAML rendue en texte (les nombres comme `600` ou `1.08` restent tels quels).
fn scalar(value: &Value) -> Option<String> {
    match value {
        Value::String(s) => Some(s.clone()),
        Value::Number(n) => Some(n.to_string()),
        _ => None,
    }
}

/// Itère sur les références `{groupe.cle}` d'un texte (groupe et clé en `[a-z0-9-]`).
fn references(text: &str) -> impl Iterator<Item = &str> {
    text.split('{').skip(1).filter_map(|chunk| {
        let candidate = chunk.split('}').next().filter(|_| chunk.contains('}'))?;
        let (group, key) = candidate.split_once('.')?;
        let valid = |s: &str| {
            !s.is_empty() && s.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-')
        };
        (valid(group) && valid(key)).then_some(candidate)
    })
}

impl Charte {
    pub fn parse(yaml: &str) -> Result<Self, TokenError> {
        Ok(serde_norway::from_str(yaml)?)
    }
}

/// Génère le contenu de `tokens.css` (bloc `@theme` Tailwind v4).
pub fn render_css(design: &DesignSystem, charte: &Charte) -> Result<String, TokenError> {
    let mut css = String::from(
        "/* Généré par build.rs depuis design.md et style/charte.yaml : ne pas éditer. */\n@theme {\n",
    );
    let mut line = |name: String, value: &str| css.push_str(&format!("  --{name}: {value};\n"));

    for namespace in ["color", "text", "radius", "shadow", "font", "breakpoint"] {
        line(format!("{namespace}-*"), "initial");
    }

    for (name, value) in &design.colors {
        line(format!("color-{name}"), value);
    }
    for (name, value) in &charte.colors {
        line(format!("color-{name}"), &design.color(value)?);
    }

    for (class, token_name) in &charte.text {
        let token = design
            .typography
            .get(token_name)
            .ok_or_else(|| TokenError::UnknownReference(format!("typography.{token_name}")))?;
        line(format!("text-{class}"), &token.font_size);
        line(format!("text-{class}--line-height"), &token.line_height);
        line(format!("text-{class}--letter-spacing"), &token.letter_spacing);
        line(format!("text-{class}--font-weight"), &token.font_weight);
    }

    for (name, value) in &charte.fonts {
        line(format!("font-{name}"), value);
    }
    for (name, value) in &design.rounded {
        line(format!("radius-{name}"), value);
    }
    line("spacing".to_owned(), "4px");
    for (name, value) in &design.spacing {
        line(format!("spacing-{name}"), value);
    }
    for (name, value) in &charte.containers {
        line(format!("container-{name}"), value);
    }
    for (name, value) in &charte.shadows {
        line(format!("shadow-{name}"), value);
    }
    for (name, value) in &charte.breakpoints {
        line(format!("breakpoint-{name}"), value);
    }

    css.push_str("}\n");
    Ok(css)
}

#[cfg(test)]
mod tests {
    use super::*;

    const DESIGN_MD: &str = include_str!("../../design.md");
    const CHARTE: &str = include_str!("../style/charte.yaml");

    fn real() -> (DesignSystem, Charte) {
        (
            DesignSystem::parse(DESIGN_MD).expect("design.md valide"),
            Charte::parse(CHARTE).expect("charte.yaml valide"),
        )
    }

    #[test]
    fn design_md_se_lit() {
        let (design, _) = real();
        assert_eq!(design.colors["primary"], "#0070d5");
        assert_eq!(design.typography["heading"].font_size, "32px");
        assert_eq!(design.typography["heading"].font_weight, "600");
        assert_eq!(design.typography["overline"].letter_spacing, "0");
        assert_eq!(design.rounded["sm"], "8px");
        assert_eq!(design.spacing["section"], "64px");
    }

    #[test]
    fn design_md_ne_reference_aucun_token_inconnu() {
        let (design, _) = real();
        assert_eq!(design.unknown_references(DESIGN_MD), Vec::<String>::new());
    }

    #[test]
    fn une_reference_inconnue_est_detectee() {
        let md = "---\ncolors:\n  ink: \"#262626\"\n---\nTexte `{colors.ink}` et `{colors.nope}` et `{spacing.md}`.\n";
        let design = DesignSystem::parse(md).unwrap();
        assert_eq!(design.unknown_references(md), vec!["colors.nope", "spacing.md"]);
    }

    #[test]
    fn sans_front_matter_c_est_une_erreur() {
        let err = DesignSystem::parse("## Colors\n---\ncolors: {}\n---\n").unwrap_err();
        assert!(matches!(err, TokenError::MissingFrontMatter));
    }

    #[test]
    fn le_css_contient_toutes_les_couleurs_de_design_md() {
        let (design, charte) = real();
        let css = render_css(&design, &charte).unwrap();
        for (nom, valeur) in &design.colors {
            assert!(css.contains(&format!("--color-{nom}: {valeur};")), "{nom} absent");
        }
    }

    #[test]
    fn le_css_resout_les_alias_et_ajoute_les_couleurs_de_la_charte() {
        let (design, charte) = real();
        let css = render_css(&design, &charte).unwrap();
        assert!(css.contains("--color-input: #8c8c8c;"));
        assert!(css.contains("--color-warning: #be4e04;"));
        assert!(css.contains("--color-error-ink: #cf1322;"));
    }

    #[test]
    fn le_css_reinitialise_les_valeurs_par_defaut_de_tailwind() {
        let (design, charte) = real();
        let css = render_css(&design, &charte).unwrap();
        for espace in ["color", "text", "radius", "shadow", "font", "breakpoint"] {
            assert!(css.contains(&format!("--{espace}-*: initial;")), "{espace}");
        }
    }

    #[test]
    fn le_css_porte_l_echelle_typographique_complete() {
        let (design, charte) = real();
        let css = render_css(&design, &charte).unwrap();
        assert!(css.contains("--text-2xl: 32px;"));
        assert!(css.contains("--text-2xl--line-height: 1.125;"));
        assert!(css.contains("--text-2xl--letter-spacing: -0.96px;"));
        assert!(css.contains("--text-2xl--font-weight: 600;"));
    }

    #[test]
    fn le_css_porte_arrondis_espacements_ombre_et_breakpoints() {
        let (design, charte) = real();
        let css = render_css(&design, &charte).unwrap();
        assert!(css.contains("--radius-sm: 8px;"));
        assert!(css.contains("--spacing: 4px;"));
        assert!(css.contains("--spacing-md: 16px;"));
        assert!(css.contains("--shadow-float: 0 8px 16px rgb(0 0 0 / 0.10);"));
        assert!(css.contains("--breakpoint-sm: 457px;"));
        assert!(css.contains("--font-mono: "));
        assert!(css.contains("--container-card: 28rem;"));
    }

    #[test]
    fn une_charte_qui_reference_un_token_inconnu_est_refusee() {
        let (design, _) = real();
        let charte = Charte::parse(
            "colors:\n  x: \"{colors.inexistante}\"\ntext: {}\nfonts: {}\ncontainers: {}\nshadows: {}\nbreakpoints: {}\n",
        )
        .unwrap();
        let err = render_css(&design, &charte).unwrap_err();
        assert!(matches!(err, TokenError::UnknownReference(r) if r == "colors.inexistante"));
    }

    #[test]
    fn une_charte_qui_utilise_un_style_de_texte_inconnu_est_refusee() {
        let (design, _) = real();
        let charte = Charte::parse(
            "colors: {}\ntext:\n  lg: inexistant\nfonts: {}\ncontainers: {}\nshadows: {}\nbreakpoints: {}\n",
        )
        .unwrap();
        let err = render_css(&design, &charte).unwrap_err();
        assert!(matches!(err, TokenError::UnknownReference(r) if r == "typography.inexistant"));
    }

    /// Ratio de contraste WCAG 2.1 entre deux couleurs `#rrggbb`.
    fn contraste(a: &str, b: &str) -> f64 {
        let luminance = |hex: &str| {
            let c = |i: usize| {
                let v = f64::from(u8::from_str_radix(&hex[i..i + 2], 16).unwrap()) / 255.0;
                if v <= 0.03928 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) }
            };
            0.2126 * c(1) + 0.7152 * c(3) + 0.0722 * c(5)
        };
        let (la, lb) = (luminance(a), luminance(b));
        (la.max(lb) + 0.05) / (la.min(lb) + 0.05)
    }

    #[test]
    fn les_couples_texte_fond_de_la_charte_respectent_wcag_aa() {
        let (design, charte) = real();
        let couleur = |nom: &str| {
            charte
                .colors
                .get(nom)
                .map(|v| design.color(v).unwrap())
                .unwrap_or_else(|| design.colors[nom].clone())
        };
        let couples = [
            ("foreground", "background", 4.5),
            ("muted-foreground", "background", 4.5),
            ("muted-foreground", "muted", 4.5),
            ("primary", "background", 4.5),
            ("primary-foreground", "primary", 4.5),
            ("primary-foreground", "destructive", 4.5),
            ("error-ink", "background", 4.5),
            ("error-ink", "error-bg", 4.5),
            ("success", "success-bg", 4.5),
            ("warning", "warning-bg", 4.5),
            ("info", "info-bg", 4.5),
            ("log-fg", "log-bg", 4.5),
            ("log-ok", "log-bg", 4.5),
            ("log-changed", "log-bg", 4.5),
            ("log-failed", "log-bg", 4.5),
            ("input", "background", 3.0),
        ];
        for (texte, fond, minimum) in couples {
            let ratio = contraste(&couleur(texte), &couleur(fond));
            assert!(ratio >= minimum, "{texte} sur {fond} : {ratio:.2} < {minimum}");
        }
    }
}