font.rs

2.4 kB · rust · 73 lines

1use mrlycore::json;2use wasm_bindgen::prelude::*;34/// Lays the text out as one 0/1 grid: its row count, its column count and its rows as strings of '0' and '1', as JSON.5#[wasm_bindgen]6pub fn font_raster(text: &str) -> String {7    let grid = mrlyfont::raster(text);8    let cols = grid.first().map_or(0, |row| row.len());9    let rows: Vec<String> = grid10        .iter()11        .map(|row| {12            row.iter()13                .map(|bit| if *bit == 1 { '1' } else { '0' })14                .collect()15        })16        .collect();17    json!({ "rows": grid.len(), "cols": cols, "grid": rows }).to_string()18}1920/// Writes the text cell by cell in stroke order on a board padded by pad: the board size, the rate and the lit cell indices of every frame, as JSON.21#[wasm_bindgen]22pub fn font_animate(text: &str, pad: usize) -> String {23    anim_json(&mrlyfont::animate(text, pad))24}2526/// Loops the text's write-and-fold cycle, holding hold frames between the movements, in the same shape as font_animate.27#[wasm_bindgen]28pub fn font_cycle(text: &str, pad: usize, hold: usize) -> String {29    let write = mrlyfont::animate(text, pad);30    let merged = mrlyfont::merge(text, pad);31    anim_json(&mrlyfont::cycle(&write, &merged, hold))32}3334/// Reads one character's glyph: the character, its Unicode name, its width, its height and its bitmap rows, as JSON, or null outside the font.35#[wasm_bindgen]36pub fn font_glyph(c: &str) -> String {37    let Some(glyph) = c.chars().next().and_then(mrlyfont::glyph) else {38        return json!(null).to_string();39    };40    json!({41        "char": glyph.char.to_string(),42        "name": mrlyfont::name_of(glyph.char),43        "w": glyph.width(),44        "h": glyph.height(),45        "rows": glyph.rows,46    })47    .to_string()48}4950/// Returns the least strokes that can write the character, the minimum cover of its cells by 4-adjacent paths, or 0 outside the font.51#[wasm_bindgen]52pub fn font_floor(c: &str) -> usize {53    c.chars()54        .next()55        .and_then(mrlyfont::glyph)56        .map_or(0, |glyph| mrlyfont::floor(&mrlyfont::trim(&glyph.rows)))57}5859/// Returns every character the font supports, in font order, as one string.60#[wasm_bindgen]61pub fn font_chars() -> String {62    mrlyfont::supported().into_iter().collect()63}6465fn anim_json(anim: &mrlyfont::Anim) -> String {66    json!({67        "rows": anim.rows,68        "cols": anim.cols,69        "fps": anim.fps,70        "frames": anim.frames,71    })72    .to_string()73}