//! Small marks beside a row's words: a `State` (what a pull, an issue or a //! check is in), a `Badge` (a count or a tag), a `Label` (a pull's or an //! issue's) and an `Icon` (a menu row's), as the web renderer's StateNode, //! BadgeNode, LabelNode and Icon read them. use super::*; use crate::catalog::{GLYPHS, ROLES, TINTS}; /// `State`: `p: { role, word, style }`: `role` one of the catalog's /// `ROLES`, the one `roles` names for `of/value`, else for `value`, else /// neutral; `word` the view's for the value, else the value capitalised; /// `style` mark, text or pill. pub(super) fn state(p: &Value, scope: &Value) -> R> { let found = required("value", &p["value"], scope, present)?; let value = match found { Value::String(_) | Value::Number(_) | Value::Bool(_) => write(found), _ => return bad("value: not text"), }; let of = text_of(&p["of"], scope)?; // The first key `roles` has decides, even when what it names is no role. let role = p["roles"] .as_object() .and_then(|roles| { of.map(|of| format!("{of}/{value}")) .into_iter() .chain([value.clone()]) .find_map(|k| roles.get(&k)) }) .and_then(Value::as_str) .filter(|r| ROLES.contains(r)) .unwrap_or("neutral"); let word = match p["words"][value.as_str()].as_str() { Some(w) if w != value => w.to_string(), _ => capitalised(&value), }; let style = p["style"] .as_str() .filter(|s| matches!(*s, "mark" | "pill")) .unwrap_or("text"); let mut o = Map::new(); o.insert("role".into(), role.into()); o.insert("word".into(), word.into()); o.insert("style".into(), style.into()); Ok(Some(make("State", o, vec![]))) } fn capitalised(s: &str) -> String { let mut chars = s.chars(); chars .next() .map_or_else(String::new, |c| c.to_uppercase().chain(chars).collect()) } /// A required prop that is text: a string or a number, written out. fn required_text(name: &str, prop: &Value, scope: &Value) -> R { let found = required(name, prop, scope, present)?; if !(found.is_string() || found.is_number()) { return bad(format!("{name}: not text")); } Ok(write(found)) } /// `Badge`: `p: { value }`, its words. pub(super) fn badge(p: &Value, scope: &Value) -> R> { let mut o = Map::new(); o.insert( "value".into(), required_text("value", &p["value"], scope)?.into(), ); Ok(Some(make("Badge", o, vec![]))) } /// `Label`: `p: { name, color?, description? }`, `color` only a `#rrggbb`. pub(super) fn label(p: &Value, scope: &Value) -> R> { let mut o = Map::new(); o.insert( "name".into(), required_text("name", &p["name"], scope)?.into(), ); if let Some(color) = text_of(&p["color"], scope)?.filter(|c| is_hex(c)) { o.insert("color".into(), color.into()); } if let Some(description) = text_of(&p["description"], scope)? { o.insert("description".into(), description.into()); } Ok(Some(make("Label", o, vec![]))) } /// `#rrggbb`, in either case. fn is_hex(c: &str) -> bool { c.len() == 7 && c.starts_with('#') && c[1..].bytes().all(|b| b.is_ascii_hexdigit()) } /// `Icon`: `p: { name, tint, style? }`, each a word of the catalog's, as /// `names` and `tints` give the words for the values bound (a reason's /// glyph); one that resolves to none of them draws nothing. `style` only /// as glyph, the glyph alone. pub(super) fn icon(p: &Value, scope: &Value) -> R> { let word = |key: &str, own: &str, words: &[&str]| -> R { let found = value(&p[key], scope, Value::is_string)?.and_then(Value::as_str); match found.map(|w| p[own][w].as_str().unwrap_or(w)) { Some(w) if words.contains(&w) => Ok(w.to_string()), _ => Err(Fail::Missing), } }; let mut o = Map::new(); o.insert("name".into(), word("name", "names", GLYPHS)?.into()); o.insert("tint".into(), word("tint", "tints", TINTS)?.into()); if p["style"] == "glyph" { o.insert("style".into(), "glyph".into()); } Ok(Some(make("Icon", o, vec![]))) } #[cfg(test)] mod tests { use super::*; fn state_of(props: Value, scope: Value) -> Value { let drawn = state(&props, &scope).ok().flatten().unwrap(); check::checked(&drawn); drawn["p"].clone() } #[test] fn a_state_takes_the_role_of_its_kind_first_and_one_named_wrongly_is_neutral() { let roles = json!({ "pull/open": "open-pull", "open": "open-issue", "merged": "merged", "closed": "launched" }); let p = json!({ "value": { "$": "state" }, "of": { "$": "kind" }, "roles": roles }); assert_eq!( state_of(p.clone(), json!({ "state": "open", "kind": "pull" }))["role"], "open-pull" ); assert_eq!( state_of(p.clone(), json!({ "state": "open", "kind": "issue" }))["role"], "open-issue" ); assert_eq!( state_of(p.clone(), json!({ "state": "merged" }))["role"], "merged" ); assert_eq!( state_of(p.clone(), json!({ "state": "closed" }))["role"], "neutral" ); assert_eq!(state_of(p, json!({ "state": "draft" }))["role"], "neutral"); } #[test] fn a_state_is_worded_by_the_view_else_capitalised() { let p = json!({ "value": { "$": "v" }, "words": { "approve": "Approved", "same": "same" }, "style": "loud" }); let approved = state_of(p.clone(), json!({ "v": "approve" })); assert_eq!(approved["word"], "Approved"); assert_eq!(approved["style"], "text"); assert_eq!(state_of(p.clone(), json!({ "v": "same" }))["word"], "Same"); assert_eq!(state_of(p, json!({ "v": "élan" }))["word"], "Élan"); } #[test] fn a_label_colour_is_a_hex_rgb_alone() { let p = json!({ "name": { "$": "name" }, "color": { "$": "color" } }); let colour = |c: Value| { let drawn = label(&p, &json!({ "name": "bug", "color": c })) .ok() .flatten() .unwrap(); check::checked(&drawn); drawn["p"].get("color").cloned() }; assert_eq!(colour(json!("#A1b2C3")), Some(json!("#A1b2C3"))); assert_eq!(colour(json!("red")), None); assert_eq!(colour(json!("#abc")), None); assert_eq!(colour(json!("#abcdefa")), None); assert_eq!(colour(json!("url(#abcdef)")), None); } #[test] fn an_icon_draws_its_words_and_nothing_for_others() { let p = json!({ "name": { "$": "icon" }, "tint": { "$": "tint" } }); let drawn = icon(&p, &json!({ "icon": "issue", "tint": "green" })) .ok() .flatten() .unwrap(); check::checked(&drawn); assert_eq!( drawn, json!({ "c": "Icon", "p": { "name": "issue", "tint": "green" } }) ); for scope in [ json!({ "icon": "rocket", "tint": "green" }), json!({ "icon": "issue", "tint": "teal" }), json!({ "tint": "green" }), ] { assert!(matches!(icon(&p, &scope), Err(Fail::Missing)), "{scope}"); } } /// A notification's reason: its glyph and tint as names and tints say /// for its value, drawn alone; a value they leave out taken as it is. #[test] fn an_icon_takes_its_words_for_a_value() { let p = json!({ "style": "glyph", "name": { "$": "reason" }, "tint": { "$": "reason" }, "names": { "gallery-favorite": "heart", "follow": "follow" }, "tints": { "gallery-favorite": "red", "follow": "blue" } }); let drawn = |reason: &str| icon(&p, &json!({ "reason": reason })).ok().flatten(); let heart = drawn("gallery-favorite").unwrap(); check::checked(&heart); assert_eq!( heart, json!({ "c": "Icon", "p": { "name": "heart", "tint": "red", "style": "glyph" } }) ); assert_eq!(drawn("follow").unwrap()["p"]["tint"], "blue"); assert!(drawn("reply").is_none()); let own = json!({ "name": { "$": "reason" }, "tint": "green", "names": { "x": "heart" } }); assert_eq!( icon(&own, &json!({ "reason": "search" })) .ok() .flatten() .unwrap()["p"], json!({ "name": "search", "tint": "green" }) ); } #[test] fn a_value_that_is_not_text_is_an_error_where_it_stands() { let root = json!({}); let ctx = Ctx { origins: &[], thumbnails: vec![], trusted: true, root: &root, report: None, inline: None, lexicon: None, handles: None, paged: Vec::new(), more: More::default(), me: None, people: None, }; let scope = json!({ "v": { "an": "object" } }); for (component, prop) in [("State", "value"), ("Badge", "value"), ("Label", "name")] { let layout = json!({ "component": component, "props": { prop: { "$": "v" } } }); let error = resolve(&layout, &scope, &ctx).unwrap(); check::checked(&error); assert_eq!( error["p"], json!({ "component": component, "message": format!("{prop}: not text") }) ); } } #[test] fn a_badge_writes_its_value_and_a_label_its_description() { let drawn = badge(&json!({ "value": { "$": "n" } }), &json!({ "n": 4 })) .ok() .flatten() .unwrap(); check::checked(&drawn); assert_eq!(drawn, json!({ "c": "Badge", "p": { "value": "4" } })); let p = json!({ "name": "bug", "description": { "$": "about" } }); let drawn = label(&p, &json!({ "about": "Something is wrong" })) .ok() .flatten() .unwrap(); check::checked(&drawn); assert_eq!( drawn["p"], json!({ "name": "bug", "description": "Something is wrong" }) ); } }