Cotton code
157 lines · 6.3 KB · RustRaw
//! The logo's own gates, and the JSON every other language reads it through.//!//! The FIDELITY guard — "these numbers are the app icon's own geometry" — is//! not here: it needs to open a PNG, and it lives in//! `scripts/__tests__/constellation-mark.test.ts`, which reads the JSON this//! file emits. What is here is everything that can be stated about the record//! without the art in hand.use super::*;use std::path::PathBuf;/// The committed JSON the TypeScript side reads. Inside `crates/`, so nothing/// under `crates/` reaches outside it (step 5, R12) — the same placement as/// `palette.json`, for the same reason.fn json_path() -> PathBuf {    // Run time, not `env!` — a cached test binary carries a checkout that is gone (#403).    PathBuf::from(        std::env::var("CARGO_MANIFEST_DIR")            .expect("cargo sets CARGO_MANIFEST_DIR for every `cargo test`"),    )    .join("src/design/mark.json")}#[test]fn the_content_box_holds_every_point_and_the_ink_on_it() {    let (min_x, min_y, max_x, max_y) = content_bounds();    assert!(min_x < 0.0, "the apex sits on x = 0 and its join spills left of it");    for point in POINTS {        assert!(point.x >= min_x && point.x <= max_x, "{point:?} is outside that box in x");        assert!(point.y >= min_y && point.y <= max_y, "{point:?} is outside that box in y");    }    assert!(max_y - min_y > max_x - min_x, "the logo is taller than it is wide");}#[test]fn the_svg_reaches_for_nothing_outside_itself() {    // These pages are served by a self-hosted server with no cottondb.com    // behind it, under a policy that refuses an external image. A logo that    // fetches is a logo that is missing.    // The wrapper's `xmlns` is the SVG namespace NAME and is not fetched, so    // the "no http" rule is asked of the drawing, which is what a caller    // inlines into a page of its own.    for drawing in [mark_inner(96.0, MarkInk::default()), tile_svg(64.0)] {        for forbidden in ["<image", "href", "url(", "<use", "http"] {            assert!(                !drawing.replace("http://www.w3.org/2000/svg", "").contains(forbidden),                "the inline mark carries {forbidden:?}: {drawing}",            );        }    }    for svg in [mark_svg(96.0, MarkInk::default()), tile_svg(64.0)] {        assert!(svg.starts_with("<svg"), "{svg}");        assert!(svg.ends_with("</svg>"), "{svg}");    }}#[test]fn the_mark_fits_the_square_it_is_asked_for() {    // Every coordinate the renderer writes lands inside 0…size, which is what    // makes the apex's round join safe at any size.    let size = 120.0_f64;    // The hexes go first: `#D9962E` holds a "9962" that is not a coordinate.    let svg = mark_inner(size, MarkInk::default())        .replace(KNOT_INK, "")        .replace(THREAD_INK, "");    for number in svg.split(|ch: char| !(ch.is_ascii_digit() || ch == '.' || ch == '-')) {        let Ok(value) = number.parse::<f64>() else { continue };        assert!(value >= -0.01 && value <= size + 0.01, "{value} is outside 0…{size}");    }}// ── The JSON the other languages read ────────────────────────────────────────//// The logo is drawn in four languages: Rust (the server's pages), Swift (both// apps, rendered by `cotton-gen` from this record), TypeScript (the site's// brand assets) and — as raster — the master PNG the icons derive from. Rust is// the DECLARATION; this JSON is how the TypeScript reads it, and how the// fidelity guard reads it before opening the master.fn mark_json() -> String {    let mut root = serde_json::Map::new();    root.insert("viewWidth".into(), VIEW_WIDTH.into());    root.insert("viewHeight".into(), VIEW_HEIGHT.into());    root.insert("knotRadius".into(), KNOT_RADIUS.into());    root.insert("threadWidth".into(), THREAD_WIDTH.into());    root.insert("knotInk".into(), KNOT_INK.into());    root.insert("threadInk".into(), THREAD_INK.into());    root.insert("ground".into(), GROUND.into());    root.insert(        "points".into(),        serde_json::Value::Array(            POINTS                .iter()                .map(|point| {                    let mut object = serde_json::Map::new();                    object.insert("x".into(), point.x.into());                    object.insert("y".into(), point.y.into());                    object.insert("kind".into(), point.kind.as_str().into());                    serde_json::Value::Object(object)                })                .collect(),        ),    );    root.insert(        "threads".into(),        serde_json::Value::Array(            THREADS                .iter()                .map(|(from, to)| {                    serde_json::Value::Array(vec![(*from as u64).into(), (*to as u64).into()])                })                .collect(),        ),    );    format!(        "{}\n",        serde_json::to_string_pretty(&serde_json::Value::Object(root)).expect("the record is JSON")    )}#[test]fn the_emitted_json_matches_the_committed_one() {    let path = json_path();    let wanted = mark_json();    let found = std::fs::read_to_string(&path).ok();    if found.as_deref() == Some(wanted.as_str()) {        return;    }    if std::env::var("COTTON_DESIGN_WRITE_JSON").as_deref() == Ok("1") {        // The writing run PASSES, on purpose — see `palette_tests.rs` for why.        std::fs::write(&path, &wanted).expect("write the logo JSON");        println!(            "{} rewritten from `design::mark` — re-run without \             COTTON_DESIGN_WRITE_JSON to confirm, then commit it.",            path.display()        );        return;    }    panic!(        "{} is not what `design::mark` declares. Run \         `COTTON_DESIGN_WRITE_JSON=1 cargo test -p cotton-core design::mark` and commit it; \         the site's copy and the fidelity guard against the master art both read this file \         (`scripts/__tests__/constellation-mark.test.ts`).",        path.display()    );}#[test]#[ignore = "a hand check: writes the logo as SVG so a human can look at it"]fn write_a_preview() {    let out = std::env::var("COTTON_MARK_PREVIEW").unwrap_or_default();    if out.is_empty() {        return;    }    std::fs::write(&out, tile_svg(512.0)).expect("write the preview");}