drawland-script 0.1.1

draw.land profiles in JavaScript: the script builds the graph the engine runs
Documentation
//! The pattern part of `drawland.d.ts`, written from penfill's catalogue.
//!
//! Every pattern name, every option, its type and its documentation come from
//! penfill's own description of its generators and materials, so the editor's
//! autocomplete and type checks are exactly what the engine accepts. The
//! block between the `catalog:begin` and `catalog:end` markers is generated:
//! `cargo run -p drawland-script --example write_dts` rewrites it, and a test
//! fails when it is stale.

use penfill::catalog::{self, schema::Default as D, Generator, Kind, Opt};

pub const BEGIN: &str = "// ── catalog:begin (generated by `cargo run -p drawland-script --example write_dts`; do not edit) ──";
pub const END: &str = "// ── catalog:end ──";

/// The generated block, markers included.
pub fn block() -> String {
    let mut s = String::new();
    s += BEGIN;
    s += "\n\n";

    s += "/** A pattern: a material (a named recipe, chosen by what it is for) or a generator (the algorithm, every option open). */\n";
    s += "type Pattern = Material | Generator | \"none\"\n\n";

    s += "/** The materials, group by group. Each is a recipe over one or more generators; `spacing` scales the whole recipe. */\n";
    s += "type Material =\n";
    for g in catalog::Group::ALL {
        let ms: Vec<_> = catalog::MATERIALS.iter().filter(|m| m.group == g).collect();
        if ms.is_empty() {
            continue;
        }
        s += &format!("  // {}: {}\n", g.title(), g.about());
        s += &format!("  | {}\n", ms.iter().map(|m| format!("{:?}", m.name)).collect::<Vec<_>>().join(" | "));
    }
    s += "\n";

    s += "/** The generators: the algorithms under every material. */\n";
    s += &format!(
        "type Generator = {}\n\n",
        catalog::generators().iter().map(|g| format!("{:?}", g.name)).collect::<Vec<_>>().join(" | ")
    );

    s += "/** A symbol `scatter` can place by name. */\n";
    s += &format!("type Mark = {}\n\n", catalog::marks::NAMES.iter().map(|n| format!("{n:?}")).collect::<Vec<_>>().join(" | "));

    s += "/** Polylines in mm around the origin, for your own motif: one `[[x, y], …]` or several. */\n";
    s += "type Polylines = [number, number][] | [number, number][][]\n\n";

    for g in catalog::generators() {
        s += &interface(g);
    }

    s += "/** Each pattern with the options it takes. */\n";
    s += "type PatternOptions =\n";
    for m in catalog::MATERIALS.iter().filter(|m| !m.is_alias()) {
        let mut gens: Vec<&str> = m.layers.iter().map(|l| l.generator).collect();
        gens.dedup();
        let opts = gens.iter().map(|g| options_name(g)).collect::<Vec<_>>().join(" & ");
        s += &format!("  | ({{ pattern: {:?} }} & {opts})\n", m.name);
    }
    for g in catalog::generators() {
        s += &format!("  | ({{ pattern: {:?} }} & {})\n", g.name, options_name(g.name));
    }
    s += "\n";
    s += END;
    s += "\n";
    s
}

fn interface(g: &Generator) -> String {
    let mut s = format!("/** `{}`: {} */\ninterface {} {{\n", g.name, g.about, options_name(g.name));
    for o in g.options {
        s += &format!("  /** {} */\n  {}?: {}\n", doc(o), o.key, ts_type(o));
    }
    s += "}\n\n";
    s
}

fn doc(o: &Opt) -> String {
    let default = match o.default {
        D::None => String::new(),
        D::Num(n) => format!(" Default {}.", trim(n)),
        D::Rel(k) => format!(" Default {} × spacing.", trim(k)),
        D::Flag(b) => format!(" Default {b}."),
        D::Text(t) => format!(" Default `{t:?}`."),
        D::Rels(a, b) => format!(" Default [{}, {}] × spacing.", trim(a), trim(b)),
    };
    format!("{}{default}", o.doc).replace("*/", "* /")
}

fn trim(v: f64) -> String {
    let s = format!("{:.4}", v);
    s.trim_end_matches('0').trim_end_matches('.').to_string()
}

fn ts_type(o: &Opt) -> String {
    let words = |ws: &[&str]| ws.iter().map(|w| format!("{w:?}")).collect::<Vec<_>>().join(" | ");
    match o.kind {
        Kind::Length => "Length".into(),
        Kind::Number { .. } => "number".into(),
        Kind::Count { min, max } if max - min <= 6 => (min..=max).map(|n| n.to_string()).collect::<Vec<_>>().join(" | "),
        Kind::Count { .. } => "number".into(),
        Kind::Flag => "boolean".into(),
        Kind::Choice(ws) => words(ws),
        Kind::Lengths => "Length | [Length, Length]".into(),
        Kind::Motif(ws) if ws == catalog::marks::NAMES => "Mark | Lines | Polylines".into(),
        Kind::Motif(ws) => format!("{} | Lines | Polylines", words(ws)),
        Kind::Text => "string".into(),
        Kind::NumberOr(ws) => format!("number | {}", words(ws)),
    }
}

fn options_name(generator: &str) -> String {
    let mut out = String::new();
    for part in generator.split(['-', '_']) {
        let mut cs = part.chars();
        if let Some(c) = cs.next() {
            out.extend(c.to_uppercase());
            out.push_str(cs.as_str());
        }
    }
    out + "Options"
}

/// `dts` with its generated block replaced by the current one.
pub fn rewrite(dts: &str) -> String {
    let (Some(a), Some(b)) = (dts.find(BEGIN), dts.find(END)) else {
        panic!("drawland.d.ts has no catalog:begin / catalog:end markers");
    };
    let end = b + END.len() + dts[b + END.len()..].find('\n').map_or(0, |n| n + 1);
    format!("{}{}{}", &dts[..a], block(), &dts[end..])
}