Cotton code
273 lines · 13.1 KB · RustRaw
//! What a health record's card carries for its face (Cotton Health, 13 Nov//! 2026), read once with the card as a trip's wallet is, so a face never//! performs a second read and prints only the core's words.//!//! - A day's measure (`health_day`, the brass pedometer): `reading` — its//!   measure, its value said in its unit, the usual (the mean of the//!   [`summary::USUAL_DAYS`] days before that hold it), where the hand and//!   the usual's tick stand on the dial (shares of the dial's top, a round//!   figure above both), the day's lowest and highest where the measure has//!   them; on the night's asleep row its stages as shares of the night; on//!   a day the period is logged, its flow.//! - A workout (`health_workout`, the stopwatch): `workout` — its kind, its//!   minutes said and where the stopwatch's hand stands in its hour, when it//!   started, its distance, energy and heart rates.//! - A measurement (`health_measurement`, the brass tag): `tag` — its kind,//!   its reading (blood pressure upper over lower) in its unit, before or//!   after a meal, when it was taken.use std::collections::BTreeMap;use serde_json::{json, Map, Value};use cotton_core::definitions::TableDefinition;use cotton_core::health::catalog::{self, Fold};use cotton_core::health::rows::{DAY_TABLE, MEASUREMENT_TABLE, WORKOUT_TABLE};use cotton_core::health::summary;use cotton_core::records::page::{face_day_words, Words};use cotton_core::rules::shell_lines::LineSet;/// The sleep stages a night's band is drawn in, in the order they stand.const STAGES: [(&str, &str); 4] = [("sleep_deep", "deep"), ("sleep_core", "core"), ("sleep_rem", "rem"), ("sleep_awake", "awake")];/// The health tables whose cards carry words of their own.pub fn carries(table: &str) -> bool {    table == DAY_TABLE || table == WORKOUT_TABLE || table == MEASUREMENT_TABLE}/// A number with its thousands grouped and `places` decimals ("8,412", "6.2").pub fn grouped(value: f64, places: usize) -> String {    let text = format!("{:.*}", places, value.abs());    let (whole, fraction) = text.split_once('.').map(|(whole, fraction)| (whole.to_string(), Some(fraction.to_string()))).unwrap_or((text.clone(), None));    let mut out = String::new();    for (at, digit) in whole.chars().enumerate() {        if at > 0 && (whole.len() - at) % 3 == 0 {            out.push(',');        }        out.push(digit);    }    if value < 0.0 && value.abs() >= 0.5 / 10f64.powi(places as i32) {        out.insert(0, '-');    }    match fraction {        Some(fraction) => format!("{out}.{fraction}"),        None => out,    }}/// Minutes said as a night or a session is: "7 h 12 min", "42 min".pub fn minutes_said(minutes: f64, cards: &LineSet) -> String {    let whole = minutes.round().max(0.0) as i64;    let (hours, rest) = (whole / 60, whole % 60);    if hours == 0 {        return cards.say("health.minutes", &[("m", &rest.to_string())]).unwrap_or_default();    }    cards.say("health.hours_minutes", &[("h", &hours.to_string()), ("m", &rest.to_string())]).unwrap_or_default()}/// A measure's value said, and the unit word printed beside it (empty when/// the said words carry it, as a night's hours do).pub fn value_said(metric: &str, value: f64, cards: &LineSet) -> (String, String) {    let unit = |word: &str| cards.say(&format!("health.unit.{word}"), &[]).unwrap_or_default();    match metric {        "steps" => (grouped(value, 0), unit("steps")),        "distance" => (grouped(value / 1000.0, if value >= 100_000.0 { 0 } else { 1 }), unit("km")),        "active_energy" => (grouped(value, 0), unit("kcal")),        "flights" => (grouped(value, 0), unit("flights")),        "stand_hours" => (grouped(value, 0), unit("hours")),        "resting_heart_rate" | "blood_pressure_systolic" | "blood_pressure_diastolic" => {            (grouped(value, 0), unit(if metric == "resting_heart_rate" { "bpm" } else { "mmhg" }))        }        "heart_rate_variability" => (grouped(value, 0), unit("ms")),        "vo2_max" => (grouped(value, 1), unit("vo2")),        "weight" => (grouped(value, 1), unit("kg")),        "body_fat" => (grouped(value, 1), unit("percent")),        "glucose" => (grouped(value, 0), unit("mgdl")),        _ => match catalog::metric_of(metric).map(|metric| metric.fold) {            Some(Fold::Sleep | Fold::Minutes) => (minutes_said(value, cards), String::new()),            _ => (grouped(value, 1), String::new()),        },    }}/// The dial's top: a round figure (1, 2, 2.5 or 5 of a power of ten) a/// little above the most it must show.pub fn dial_top(most: f64) -> f64 {    let wanted = (most * 1.12).max(1.0);    let power = 10f64.powf(wanted.log10().floor());    [1.0, 2.0, 2.5, 5.0, 10.0].iter().map(|step| step * power).find(|top| *top >= wanted).unwrap_or(10.0 * power)}fn number(row: &Map<String, Value>, key: &str) -> Option<f64> {    row.get(key).and_then(Value::as_f64)}fn text<'a>(row: &'a Map<String, Value>, key: &str) -> Option<&'a str> {    row.get(key).and_then(Value::as_str).map(str::trim).filter(|text| !text.is_empty())}fn label(definition: &TableDefinition, column: &str, value: &str) -> String {    definition.column(column).map(|column| column.choice_label(value)).unwrap_or_else(|| value.to_string())}/// One day's measure as its pedometer draws it. `days` holds the/// `health_day` rows of the day and of the [`summary::USUAL_DAYS`] before it.pub fn reading(definition: &TableDefinition, row: &Map<String, Value>, days: &[Map<String, Value>], cards: &LineSet) -> Map<String, Value> {    let mut out = Map::new();    let (Some(metric), Some(day)) = (text(row, "metric"), text(row, "day")) else { return out };    out.insert("measure".into(), json!(metric));    out.insert("label".into(), json!(label(definition, "metric", metric)));    let from = summary::day_before(day, summary::USUAL_DAYS).unwrap_or_default();    let of = |other: &&Map<String, Value>| text(other, "metric") == Some(metric);    if metric == "menstrual_flow" {        if let Some(state) = text(row, "state") {            out.insert("said".into(), json!(label(definition, "state", state)));        }        return out;    }    let Some(value) = number(row, "value") else { return out };    let (said, unit) = value_said(metric, value, cards);    out.insert("said".into(), json!(said));    out.insert("unit".into(), json!(unit));    let before: Vec<f64> = days.iter().filter(of).filter(|other| text(other, "day").is_some_and(|on| on < day && on >= from.as_str())).filter_map(|other| number(other, "value")).collect();    let usual = (!before.is_empty()).then(|| before.iter().sum::<f64>() / before.len() as f64);    let (low, high) = (number(row, "min"), number(row, "max"));    let top = dial_top([Some(value), usual, high].into_iter().flatten().fold(0.0, f64::max));    out.insert("dial".into(), json!((value / top).clamp(0.0, 1.0)));    out.insert("top".into(), json!(value_said(metric, top, cards).0));    if let Some(usual) = usual {        out.insert("usual".into(), json!(cards.say("health.usual", &[("said", &value_said(metric, usual, cards).0)]).unwrap_or_default()));        out.insert("usual_dial".into(), json!((usual / top).clamp(0.0, 1.0)));    }    if let (Some(low), Some(high)) = (low, high) {        if (high - low).abs() > f64::EPSILON {            out.insert("range".into(), json!(cards.say("health.range", &[("low", &value_said(metric, low, cards).0), ("high", &value_said(metric, high, cards).0)]).unwrap_or_default()));        }    }    let today: Vec<&Map<String, Value>> = days.iter().filter(|other| text(other, "day") == Some(day)).collect();    if metric == "sleep_asleep" {        let minutes = |key: &str| today.iter().find(|other| text(other, "metric") == Some(key)).and_then(|other| number(other, "value"));        let held: Vec<(&str, f64)> = STAGES.iter().filter_map(|(key, stage)| Some((*stage, minutes(key)?))).filter(|(_, minutes)| *minutes > 0.0).collect();        let whole: f64 = held.iter().map(|(_, minutes)| minutes).sum();        let mut night = Map::new();        if let Some(in_bed) = minutes("sleep_in_bed") {            night.insert("in_bed".into(), json!(minutes_said(in_bed, cards)));        }        if whole > 0.0 {            night.insert("stages".into(), Value::Array(held.iter().map(|(stage, minutes)| json!({                "stage": stage,                "label": label(definition, "metric", &format!("sleep_{stage}")),                "said": minutes_said(*minutes, cards),                "share": minutes / whole,            })).collect()));        }        if !night.is_empty() {            out.insert("night".into(), Value::Object(night));        }    }    let flow = today.iter().find(|other| text(other, "metric") == Some("menstrual_flow")).and_then(|other| text(other, "state")).filter(|state| *state != "none");    if let Some(flow) = flow {        out.insert("flow".into(), json!(label(definition, "state", flow)));    }    out}/// One workout as its stopwatch draws it.pub fn workout(definition: &TableDefinition, row: &Map<String, Value>, zone: &str, now: chrono::DateTime<chrono::Utc>, words: &Words, cards: &LineSet) -> Map<String, Value> {    let mut out = Map::new();    if let Some(kind) = text(row, "kind") {        out.insert("kind".into(), json!(label(definition, "kind", kind)));    }    if let Some(minutes) = number(row, "minutes") {        out.insert("minutes".into(), json!(minutes_said(minutes, cards)));        out.insert("sweep".into(), json!((minutes.rem_euclid(60.0)) / 60.0));    }    if let Some(started) = text(row, "started_at").and_then(|at| face_day_words(at, zone, Some(now), &words.dates)) {        out.insert("started".into(), json!(started));    }    if let Some(metres) = number(row, "distance_m").filter(|metres| *metres > 0.0) {        let (said, unit) = value_said("distance", metres, cards);        out.insert("distance".into(), json!(format!("{said} {unit}")));    }    if let Some(energy) = number(row, "energy_kcal").filter(|energy| *energy > 0.0) {        let (said, unit) = value_said("active_energy", energy, cards);        out.insert("energy".into(), json!(format!("{said} {unit}")));    }    let heart = |key: &str| number(row, key).map(|rate| grouped(rate, 0));    match (heart("heart_rate_avg"), heart("heart_rate_max")) {        (Some(average), Some(highest)) => {            out.insert("heart".into(), json!(cards.say("health.heart", &[("avg", &average), ("max", &highest)]).unwrap_or_default()));        }        (Some(rate), None) | (None, Some(rate)) => {            out.insert("heart".into(), json!(format!("{rate} {}", cards.say("health.unit.bpm", &[]).unwrap_or_default())));        }        (None, None) => {}    }    if let Some(device) = text(row, "device") {        out.insert("device".into(), json!(device));    }    out}/// One measurement as its brass tag draws it.pub fn tag(definition: &TableDefinition, row: &Map<String, Value>, zone: &str, now: chrono::DateTime<chrono::Utc>, words: &Words, cards: &LineSet) -> Map<String, Value> {    let mut out = Map::new();    let Some(kind) = text(row, "kind") else { return out };    out.insert("measure".into(), json!(kind));    out.insert("kind".into(), json!(label(definition, "kind", kind)));    let unit = |word: &str| cards.say(&format!("health.unit.{word}"), &[]).unwrap_or_default();    if let Some(value) = number(row, "value") {        let (said, unit) = match kind {            "blood_pressure" => (match number(row, "second") {                Some(lower) => format!("{}/{}", grouped(value, 0), grouped(lower, 0)),                None => grouped(value, 0),            }, unit("mmhg")),            "weight" => (grouped(value, 1), unit("kg")),            "glucose" => (grouped(value, 0), unit("mgdl")),            "temperature" => (grouped(value, 1), unit("celsius")),            _ => (grouped(value, 1), text(row, "unit").unwrap_or_default().to_string()),        };        out.insert("said".into(), json!(said));        out.insert("unit".into(), json!(unit));    }    if let Some(context) = text(row, "context") {        out.insert("context".into(), json!(label(definition, "context", context)));    }    if let Some(taken) = text(row, "measured_at").and_then(|at| face_day_words(at, zone, Some(now), &words.dates)) {        out.insert("taken".into(), json!(taken));    }    out}/// The `health_day` rows of each day asked, read once each however many/// cards stand on it.pub struct DayRows {    held: BTreeMap<String, Vec<Map<String, Value>>>,}impl DayRows {    pub fn new() -> DayRows {        DayRows { held: BTreeMap::new() }    }    /// The rows of `day` and the usual's days before it, each day read once by `read`.    pub fn around(&mut self, day: &str, mut read: impl FnMut(&str) -> Vec<Map<String, Value>>) -> Vec<Map<String, Value>> {        let mut out = Vec::new();        for back in 0..=summary::USUAL_DAYS {            let Some(on) = summary::day_before(day, back) else { continue };            let rows = self.held.entry(on.clone()).or_insert_with(|| read(&on));            out.extend(rows.iter().cloned());        }        out    }}impl Default for DayRows {    fn default() -> Self {        DayRows::new()    }}#[cfg(test)]#[path = "health_card_tests.rs"]mod tests;