Cotton code
375 lines · 15.1 KB · RustRaw
//! Cotton Notes' look and type as data, read from the kit//! (`kits/notes/writing.json`): the four themes, each with a light and a dark//! appearance, the typefaces, the bounds of size, spacing and line width, the//! formatting panel's buttons in order and the bar above the keyboard. Their//! words are the `notes` line set's (`theme.names.<id>`, `type.fonts.<id>`,//! `format.<action>`, `bar.<key>`).use std::sync::OnceLock;use serde::{Deserialize, Serialize};#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]pub struct Colours {    pub ground: String,    pub text: String,    pub heading: String,    pub secondary: String,    /// The ink: the cursor, ticks, buttons, pins, tags and the selected row (the person's ink choice, laid over the    /// theme by [inked]; the theme's own value is today's red).    pub accent: String,    /// Deleting for good and other acts that cannot be undone: the theme's red, whatever the ink (22 Nov 2026).    #[serde(default)]    pub danger: String,    pub rule: String,    pub highlight: String,    pub code_ground: String,    pub selection: String,    /// Links (and note links): the text's own colour, drawn underlined, so a link is never taken for the ink    /// (22 Nov 2026; a muted blue before).    #[serde(default)]    pub link: String,}#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]pub struct Theme {    pub id: String,    pub light: Colours,    pub dark: Colours,}#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]pub struct Defaults {    pub light_theme: String,    pub dark_theme: String,    pub font: String,    pub font_size: f64,    pub line_height: f64,    pub line_width: f64,    /// The space after a paragraph, in lines.    #[serde(default = "default_spacing")]    pub paragraph_spacing: f64,    /// Marks hidden away from the cursor (else drawn dim).    #[serde(default = "yes")]    pub hide_marks: bool,    /// The ink a person who never chose one writes in: blue (owner, 22 Nov 2026), after an upgrade too.    #[serde(default = "blue")]    pub ink: String,}fn blue() -> String {    "blue".into()}/// An ink's two values in one appearance: the accent and its pale selection tint.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]pub struct InkColours {    pub accent: String,    pub selection: String,}/// An ink in light and dark appearance.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]pub struct InkPair {    pub light: InkColours,    pub dark: InkColours,}/// The colour Words writes and marks in, a choice of its own beside the paper (the theme): its values for every/// paper, with its own for a paper whose ground needs them (Print's pure white and black).#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]pub struct Ink {    pub id: String,    pub light: InkColours,    pub dark: InkColours,    #[serde(default)]    pub themes: std::collections::BTreeMap<String, InkPair>,}impl Ink {    /// This ink on [theme] in [dark] appearance.    pub fn on(&self, theme: &str, dark: bool) -> &InkColours {        match self.themes.get(theme) {            Some(pair) => if dark { &pair.dark } else { &pair.light },            None => if dark { &self.dark } else { &self.light },        }    }}fn default_spacing() -> f64 {    0.4}fn yes() -> bool {    true}/// The typefaces Notes is set in: the words and headings, and code.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]pub struct Faces {    pub text: String,    pub code: String,}#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]pub struct Range {    pub min: f64,    pub max: f64,    pub step: f64,}#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]pub struct Widths {    pub choices: Vec<f64>,    pub full: f64,}#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]pub struct Scale {    pub title: f64,    pub heading: Vec<f64>,    pub list_title: f64,    pub list_preview: f64,    pub list_date: f64,}#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]pub struct Writing {    pub format_version: u32,    pub themes: Vec<Theme>,    /// The inks, the default first.    #[serde(default)]    pub inks: Vec<Ink>,    pub defaults: Defaults,    pub fonts: Vec<String>,    pub font_size: Range,    pub line_height: Range,    pub line_width: Widths,    #[serde(default = "spacing_range")]    pub paragraph_spacing: Range,    #[serde(default)]    pub faces: Faces,    /// Theme ids kept by an older build, and the theme each is now.    #[serde(default)]    pub renamed: std::collections::BTreeMap<String, String>,    /// Sizes as multiples of the chosen text size: the title, headings 1–6,    /// and the list's title, preview and date.    #[serde(default)]    pub scale: Option<Scale>,    /// The formatting panel's buttons in order: each a `writing::format`    /// action as JSON (`{"action": "heading", "level": 2}`).    pub formatting: Vec<serde_json::Value>,    pub bar: Vec<String>,    /// The formatting keyboard (the owner's layout, 20 Nov 2026): the bar's    /// left and right keys, a grid of 4 rows by 6 cells (`{key, grey?,    /// action?, hold?}`; no action is a key the phone does itself, `hold`    /// what a long press offers), and the slim foot (copy left, paste right).    #[serde(default)]    pub keyboard: serde_json::Value,    /// Hardware keyboard shortcuts: each a button's action or one of the    /// app's commands, with its keys.    #[serde(default)]    pub shortcuts: Vec<Shortcut>,}fn spacing_range() -> Range {    Range { min: 0.0, max: 1.0, step: 0.1 }}/// The commands a shortcut can give besides a formatting action; each has/// its words at `shortcut.<command>`.pub const COMMANDS: [&str; 6] = ["new", "search", "tag", "info", "settings", "done"];/// The modifiers a shortcut names: `primary` is the platform's own command/// key (⌘ on an Apple keyboard, Ctrl elsewhere), `alt` Option or Alt.pub const MODIFIERS: [&str; 3] = ["primary", "shift", "alt"];/// The named keys a shortcut may end on besides one letter, digit or/// punctuation mark.pub const NAMED_KEYS: [&str; 5] = ["return", "escape", "tab", "up", "down"];/// One keyboard shortcut: `keys` its modifiers then its key, lowercase;/// either `action` (a `writing::format` action, as the panel's buttons are)/// or `command`.#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]pub struct Shortcut {    pub keys: Vec<String>,    #[serde(default, skip_serializing_if = "Option::is_none")]    pub action: Option<serde_json::Value>,    #[serde(default, skip_serializing_if = "Option::is_none")]    pub command: Option<String>,}/// A formatting action's words key in the `notes` line set.pub fn action_line(action: &serde_json::Value) -> String {    let name = action["action"].as_str().unwrap_or_default();    match action.get("level") {        Some(level) => format!("format.heading.{level}"),        None => format!("format.{name}"),    }}/// The kit's writing data.pub fn writing() -> &'static Writing {    static WRITING: OnceLock<Writing> = OnceLock::new();    WRITING.get_or_init(|| serde_json::from_str(include_str!("../../kits/notes/writing.json")).expect("the kit's notes writing data reads"))}pub fn theme(id: &str) -> Option<&'static Theme> {    writing().themes.iter().find(|theme| theme.id == id)}pub fn ink(id: &str) -> Option<&'static Ink> {    writing().inks.iter().find(|ink| ink.id == id)}/// The ink a kept choice names, or the default when it names none this build knows.pub fn ink_or_default(id: Option<&str>) -> &'static Ink {    id.and_then(ink).or_else(|| ink(&writing().defaults.ink)).expect("the kit names its default ink")}/// [theme]'s colours in [dark] appearance, written in [ink]: the accent and selection are the ink's, the rest the paper's.pub fn inked(theme: &Theme, ink: &Ink, dark: bool) -> Colours {    let mut colours = if dark { theme.dark.clone() } else { theme.light.clone() };    let own = ink.on(&theme.id, dark);    colours.accent = own.accent.clone();    colours.selection = own.selection.clone();    colours}#[cfg(test)]mod tests {    use super::*;    use crate::rules::shell_lines::LineSet;    use cotton_rules::writing::format::Action;    fn hex(colour: &str) -> bool {        colour.len() == 7 && colour.starts_with('#') && colour[1..].chars().all(|c| c.is_ascii_hexdigit())    }    #[test]    fn four_themes_each_light_and_dark_with_every_colour_and_a_name() {        let lines = LineSet::shipped("notes").expect("the notes line set");        let data = writing();        assert_eq!(data.themes.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(), ["linen", "slate", "print", "dusk"]);        for theme in &data.themes {            for colours in [&theme.light, &theme.dark] {                let all = serde_json::to_value(colours).unwrap();                assert_eq!(all.as_object().unwrap().len(), 11);                for (key, value) in all.as_object().unwrap() {                    assert!(hex(value.as_str().unwrap()), "{} {key}", theme.id);                }            }            assert!(lines.say(&format!("theme.names.{}", theme.id), &[]).is_some(), "{}", theme.id);        }        // DECISIONS "Look": Linen the default light (warm off-white), Slate the dark, Dusk's dark pure black; old ids read as new.        assert_eq!(theme("linen").unwrap().light.ground, "#F8F6F1");        assert_eq!(theme("dusk").unwrap().dark.ground, "#000000");        assert_eq!(theme(&data.defaults.light_theme).unwrap().id, "linen");        assert_eq!(theme(&data.defaults.dark_theme).unwrap().id, "slate");        for (old, new) in [("chalk", "linen"), ("graphite", "slate"), ("contrast", "print"), ("cotton", "linen")] {            assert_eq!(data.renamed.get(old).map(String::as_str), Some(new));        }    }    // RULE (owner, 22 Nov 2026): Words writes in blue; red stays as a choice, exactly today's per-paper red; every paper    // in every ink, light and dark, has every colour; a link is the text's colour; deleting stays red in any ink.    #[test]    fn every_paper_in_every_ink_has_every_colour_and_blue_is_the_default() {        let lines = LineSet::shipped("notes").expect("the notes line set");        let data = writing();        assert_eq!(data.inks.iter().map(|i| i.id.as_str()).collect::<Vec<_>>(), ["blue", "red", "green", "black"]);        assert_eq!(data.defaults.ink, "blue");        assert_eq!(ink_or_default(None).id, "blue");        assert_eq!(ink_or_default(Some("no such ink")).id, "blue");        assert!(lines.say("ink.title", &[]).is_some());        for ink in &data.inks {            assert!(lines.say(&format!("ink.names.{}", ink.id), &[]).is_some(), "{}", ink.id);            for paper in ink.themes.keys() {                assert!(theme(paper).is_some(), "{} names {paper}, no paper", ink.id);            }            for paper in &data.themes {                for dark in [false, true] {                    let colours = inked(paper, ink, dark);                    for (key, value) in serde_json::to_value(&colours).unwrap().as_object().unwrap() {                        assert!(hex(value.as_str().unwrap()), "{} on {} {key}", ink.id, paper.id);                    }                    let own = if dark { &paper.dark } else { &paper.light };                    assert_eq!(colours.danger, own.danger);                    assert_eq!(colours.link, own.text, "a link is the text's colour ({})", paper.id);                    if ink.id == "red" {                        assert_eq!((&colours.accent, &colours.selection), (&own.accent, &own.selection), "red is today's red on {}", paper.id);                    }                }            }        }        let blue = ink("blue").unwrap();        assert_eq!(inked(theme("linen").unwrap(), blue, false).accent, "#2B4A8F");        assert_eq!(inked(theme("linen").unwrap(), blue, true).accent, "#93ABEB");        assert_eq!(theme("linen").unwrap().light.danger, "#CF4A3C");    }    #[test]    fn every_font_button_and_width_has_its_words_and_every_button_is_an_action() {        let lines = LineSet::shipped("notes").expect("the notes line set");        let data = writing();        assert!(data.fonts.contains(&data.defaults.font));        for font in &data.fonts {            assert!(lines.say(&format!("type.fonts.{font}"), &[]).is_some(), "{font}");        }        for width in &data.line_width.choices {            assert!(lines.say(&format!("type.line_widths.{width}"), &[]).is_some(), "{width}");        }        for button in &data.formatting {            let action: Action = serde_json::from_value(button.clone()).unwrap_or_else(|why| panic!("{button}: {why}"));            let name = button["action"].as_str().unwrap();            let key = match &action {                Action::Heading { level } => format!("format.heading.{level}"),                _ => format!("format.{name}"),            };            assert!(lines.say(&key, &[]).is_some(), "{key}");        }        for key in &data.bar {            assert!(lines.say(&format!("bar.{key}"), &[]).is_some(), "{key}");        }        let names: Vec<&str> = data.formatting.iter().filter_map(|b| b["action"].as_str()).collect();        assert!(names.contains(&"quote") && names.contains(&"code_block"), "the panel has Quote and Code block");        let scale = data.scale.as_ref().expect("the type scale");        assert_eq!(scale.heading.len(), 6);        assert!(scale.title >= scale.heading[0] && scale.heading.windows(2).all(|w| w[0] >= w[1]));        for key in ["format.return", "format.tick", "theme.sample"] {            assert!(lines.say(key, &[]).is_some(), "{key}");        }    }    #[test]    fn every_shortcut_is_one_action_or_command_with_words_and_no_two_share_keys() {        let lines = LineSet::shipped("notes").expect("the notes line set");        let data = writing();        assert!(!data.shortcuts.is_empty());        let mut seen = std::collections::BTreeSet::new();        for shortcut in &data.shortcuts {            let (key, modifiers) = shortcut.keys.split_last().expect("a shortcut has a key");            for modifier in modifiers {                assert!(MODIFIERS.contains(&modifier.as_str()), "{modifier}");            }            assert!(key.chars().count() == 1 || NAMED_KEYS.contains(&key.as_str()), "{key}");            assert_eq!(key.to_lowercase(), *key);            let mut sorted = modifiers.to_vec();            sorted.sort();            assert!(seen.insert((sorted, key.clone())), "two shortcuts on {:?}", shortcut.keys);            match (&shortcut.action, &shortcut.command) {                (Some(action), None) => {                    let _: Action = serde_json::from_value(action.clone()).unwrap_or_else(|why| panic!("{action}: {why}"));                    assert!(lines.say(&action_line(action), &[]).is_some(), "{}", action_line(action));                }                (None, Some(command)) => {                    assert!(COMMANDS.contains(&command.as_str()), "{command}");                    assert!(lines.say(&format!("shortcut.{command}"), &[]).is_some(), "{command}");                }                _ => panic!("{:?} is one action or one command", shortcut.keys),            }        }        assert!(lines.say("shortcut.title", &[]).is_some());    }}