Cotton code
119 lines · 4.9 KB · RustRaw
//! The marks catalogue (`marks.json`) and its lookup: as a person types a new//! item, the few marks whose words match are offered. A word lookup, offline,//! in several languages; not a suggestion engine (DECISIONS.md, Marks).use std::sync::OnceLock;use serde::{Deserialize, Serialize};use unicode_normalization::UnicodeNormalization;#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]pub struct Mark {    pub id: String,    /// Words per language (`en`, `hi`, `es`, `fr`, `de`).    pub words: std::collections::BTreeMap<String, Vec<String>>,    /// The drawing: one SVG path (absolute M and C) per ballpoint stroke on a    /// 24 by 24 square, drawn round-capped at 1.6 in the pen blue, never    /// filled. Written by scripts/days-marks-draw.py. Empty: not drawn yet.    #[serde(default, skip_serializing_if = "Vec::is_empty")]    pub strokes: Vec<String>,}#[derive(Deserialize)]struct File {    marks: Vec<Mark>,}/// Every mark, in the catalogue's order.pub fn catalogue() -> &'static [Mark] {    static ALL: OnceLock<Vec<Mark>> = OnceLock::new();    ALL.get_or_init(|| serde_json::from_str::<File>(include_str!("marks.json")).expect("days/marks.json reads").marks)}/// Whether `id` is a mark of the catalogue.pub fn known(id: &str) -> bool {    catalogue().iter().any(|mark| mark.id == id)}/// Whether `id` is a mark of the catalogue with a drawing: only those are/// offered, and only those stand on the month sheet.pub fn drawn(id: &str) -> bool {    catalogue().iter().any(|mark| mark.id == id && !mark.strokes.is_empty())}/// The marks a picker offers: every drawn mark, the ones `typed` finds first/// (best first), then the rest in the catalogue's order.pub fn offered(typed: &str, language: &str) -> Vec<&'static Mark> {    let found = find(typed, language, usize::MAX);    let mut out: Vec<&'static Mark> = found.iter().filter_map(|id| catalogue().iter().find(|mark| mark.id == *id)).collect();    out.extend(catalogue().iter().filter(|mark| !mark.strokes.is_empty() && !found.contains(&mark.id.as_str())));    out}/// Lower case with accents taken off, so "Café" and "cafe" meet.fn folded(word: &str) -> String {    word.nfd().filter(|c| !unicode_normalization::char::is_combining_mark(*c)).flat_map(char::to_lowercase).collect()}/// The typed words, lower case. A word of four letters or more is also/// read with its accents off ("Cafe" finds "café"); a shorter one is not, so/// "the" never meets the French "thé".fn tokens(text: &str) -> Vec<String> {    text.split(|c: char| !(c.is_alphanumeric() || c == '-' || c == '\''))        .map(|word| word.trim_matches(|c| c == '\'' || c == '-').to_lowercase())        .map(|word| word.strip_suffix("'s").map(str::to_string).unwrap_or(word))        .filter(|word| !word.is_empty())        .collect()}fn loose(word: &str) -> bool {    word.chars().count() >= 4}/// How well one typed word meets one catalogue word: 3 the same, 2 the same/// but for a plural `s`/`es`, 1 a beginning of at least three letters (the/// person is still typing). 0 is no match.fn meets(typed: &str, word: &str) -> u8 {    if typed == word {        return 3;    }    let plural = |a: &str, b: &str| a.strip_suffix("es").or_else(|| a.strip_suffix('s')) == Some(b);    if plural(typed, word) || plural(word, typed) {        return 2;    }    if typed.chars().count() >= 3 && word.starts_with(typed) {        return 1;    }    0}/// The few (at most `limit`) marks whose words meet the typed words, best/// first: by how well, then the language asked for before the others, then/// the catalogue's order. The LAST typed word may be unfinished; only it is/// read as a beginning.pub fn find(typed: &str, language: &str, limit: usize) -> Vec<&'static str> {    let typed = tokens(typed);    let last = typed.len().saturating_sub(1);    let mut scored: Vec<(u8, u8, usize, &'static str)> = Vec::new();    for (at, mark) in catalogue().iter().enumerate().filter(|(_, mark)| !mark.strokes.is_empty()) {        let mut best: Option<(u8, u8)> = None;        for (lang, words) in &mark.words {            let own = u8::from(lang == language);            for word in words {                let (plain, flat) = (word.to_lowercase(), folded(word));                for (i, one) in typed.iter().enumerate() {                    let score = if loose(one) { meets(&folded(one), &flat).max(meets(one, &plain)) } else { meets(one, &plain) };                    let score = if score == 1 && i != last { 0 } else { score };                    if score > 0 && best.is_none_or(|b| (score, own) > b) {                        best = Some((score, own));                    }                }            }        }        if let Some((score, own)) = best {            scored.push((score, own, at, mark.id.as_str()));        }    }    scored.sort_by(|a, b| b.0.cmp(&a.0).then(b.1.cmp(&a.1)).then(a.2.cmp(&b.2)));    scored.into_iter().take(limit).map(|(.., id)| id).collect()}