//! A project's BRAND KIT — its colours, its fonts, how it sounds, and the logo //! files that go with it (schema v27). //! //! ============================================================================ //! A SHIM. Its PERMANENT HOME is `cotton_core::models::project::brand`, the //! port of `packages/core/src/models/project/brand.ts` — MOVE IT THERE the //! moment core grows a `models` tree, rather than writing a second copy. The //! whole reason the TypeScript keeps it in core is that BOTH writers ask it: //! the app's edit sheet (`projectsService.updateBrand`) and this server's //! `update_project`. A hex the phone accepts and this refuses would be an edit //! that vanishes on sync. //! ============================================================================ //! //! The parse's two halves look inconsistent and are not. It DROPS a key it does //! not know and REFUSES a key it knows that carries the wrong type: //! //! - unknown is the FUTURE. The column syncs, so a phone a version behind the //! server will meet a brand carrying a field this build has never heard of. //! Degrading to the fields it knows keeps the page readable. //! - wrong-typed is a BUG NOW — a `colors` that is a string, a hex the CSS it //! will be pasted into would reject. Swallowing that is the silent fallback //! this repo does not do. use serde_json::{Map, Value}; /// The four slots a brand kit has room for, in the order a page draws them. /// /// Each is a `cotton_project_links.note` on a linked document — so the role is /// data the owner can see and change, not a schema the file has to grow. pub const BRAND_ASSET_ROLES: &[&str] = &["logo", "logo-dark", "wordmark", "icon"]; pub fn is_brand_asset_role(value: &str) -> bool { BRAND_ASSET_ROLES.contains(&value) } /// The three type roles a brand names. More is a design system, not a kit. const BRAND_FONT_ROLES: &[&str] = &["display", "body", "mono"]; /// The caps. They are small ON PURPOSE: a brand kit is what somebody hands a /// designer or pastes into a prompt, not a palette generator's output. const BRAND_COLOR_MAX: usize = 12; const BRAND_FONT_MAX: usize = 6; const BRAND_LINK_MAX: usize = 12; const BRAND_VOICE_MAX: usize = 2000; const BRAND_TAGLINE_MAX: usize = 200; const BRAND_NAME_MAX: usize = 60; const BRAND_FAMILY_MAX: usize = 120; const BRAND_SOURCE_MAX: usize = 500; const BRAND_LABEL_MAX: usize = 80; const BRAND_URL_MAX: usize = 500; /// A normalised kit, held as the JSON it is stored and answered as: the shape /// is the wire, and building a struct only to serialise it back key for key /// would be a second declaration of the same object. pub type ProjectBrand = Map; /// `#fff`, `#ffffff`, `#ffffffaa` — the three forms CSS takes, nothing else. fn is_hex(value: &str) -> bool { let Some(body) = value.strip_prefix('#') else { return false; }; matches!(body.len(), 3 | 6 | 8) && body.chars().all(|c| c.is_ascii_hexdigit()) } fn object_of(value: &Value) -> Option<&Map> { value.as_object() } /// A string field, trimmed. `Ok(None)` means "the key was absent or blank"; an /// `Err` means the key was present and NOT a string, which is always a refusal. fn read_text(source: &Map, key: &str) -> Result, ()> { match source.get(key) { None | Some(Value::Null) => Ok(None), Some(Value::String(raw)) => { let trimmed = raw.trim(); Ok((!trimmed.is_empty()).then(|| trimmed.to_string())) } Some(_) => Err(()), } } fn chars(value: &str) -> usize { value.chars().count() } fn parse_colors(raw: &Value) -> Result, String> { let Some(entries) = raw.as_array() else { return Err("colours must be a list".to_string()); }; if entries.len() > BRAND_COLOR_MAX { return Err(format!( "a brand kit holds at most {BRAND_COLOR_MAX} colours" )); } let mut out = Vec::with_capacity(entries.len()); for entry in entries { let Some(entry) = object_of(entry) else { return Err("every colour is a name and a hex".to_string()); }; let name = match read_text(entry, "name") { Ok(Some(name)) => name, _ => return Err("every colour needs a name".to_string()), }; if chars(&name) > BRAND_NAME_MAX { return Err(format!( "a colour's name is at most {BRAND_NAME_MAX} characters" )); } let hex = match read_text(entry, "hex") { Ok(Some(hex)) if is_hex(&hex) => hex.to_lowercase(), _ => return Err("every colour needs a hex value like #1f2933".to_string()), }; let mut colour = Map::new(); colour.insert("name".to_string(), Value::from(name)); colour.insert("hex".to_string(), Value::from(hex)); out.push(Value::Object(colour)); } Ok(out) } fn parse_fonts(raw: &Value) -> Result, String> { let Some(entries) = raw.as_array() else { return Err("fonts must be a list".to_string()); }; if entries.len() > BRAND_FONT_MAX { return Err(format!("a brand kit holds at most {BRAND_FONT_MAX} fonts")); } let mut out = Vec::with_capacity(entries.len()); for entry in entries { let Some(entry) = object_of(entry) else { return Err("every font is a role and a family".to_string()); }; let role = entry.get("role").and_then(Value::as_str); let Some(role) = role.filter(|role| BRAND_FONT_ROLES.contains(role)) else { return Err(format!( "a font's role is one of {}", BRAND_FONT_ROLES.join(", ") )); }; let family = match read_text(entry, "family") { Ok(Some(family)) => family, _ => return Err("every font needs a family".to_string()), }; if chars(&family) > BRAND_FAMILY_MAX { return Err(format!( "a font's family is at most {BRAND_FAMILY_MAX} characters" )); } let source = match read_text(entry, "source") { Ok(source) => source, Err(()) => return Err("a font's source must be text".to_string()), }; if source .as_deref() .is_some_and(|s| chars(s) > BRAND_SOURCE_MAX) { return Err(format!( "a font's source is at most {BRAND_SOURCE_MAX} characters" )); } let mut font = Map::new(); font.insert("role".to_string(), Value::from(role)); font.insert("family".to_string(), Value::from(family)); // Omitted rather than stored blank: a key nobody filled in is a key the // JSON should not carry. if let Some(source) = source { font.insert("source".to_string(), Value::from(source)); } out.push(Value::Object(font)); } Ok(out) } fn parse_links(raw: &Value) -> Result, String> { let Some(entries) = raw.as_array() else { return Err("links must be a list".to_string()); }; if entries.len() > BRAND_LINK_MAX { return Err(format!("a brand kit holds at most {BRAND_LINK_MAX} links")); } let mut out = Vec::with_capacity(entries.len()); for entry in entries { let Some(entry) = object_of(entry) else { return Err("every link is a label and a url".to_string()); }; let label = match read_text(entry, "label") { Ok(Some(label)) => label, _ => return Err("every link needs a label".to_string()), }; if chars(&label) > BRAND_LABEL_MAX { return Err(format!( "a link's label is at most {BRAND_LABEL_MAX} characters" )); } let url = match read_text(entry, "url") { Ok(Some(url)) => url, _ => return Err("every link needs a url".to_string()), }; if chars(&url) > BRAND_URL_MAX { return Err(format!( "a link's url is at most {BRAND_URL_MAX} characters" )); } // http(s) only, and the scheme is checked rather than inferred: a `url` // the app hands to `Linking.openURL` is a thing the phone will EXECUTE, // and `javascript:` is not a website. let lowered = url.to_lowercase(); let scheme_ok = lowered.starts_with("http://") || lowered.starts_with("https://"); let rest = lowered .strip_prefix("https://") .or_else(|| lowered.strip_prefix("http://")) .unwrap_or(""); if !scheme_ok || rest.is_empty() || url.chars().any(char::is_whitespace) { return Err("a link's url starts with http:// or https://".to_string()); } let mut link = Map::new(); link.insert("label".to_string(), Value::from(label)); link.insert("url".to_string(), Value::from(url)); out.push(Value::Object(link)); } Ok(out) } /// The ONE validator for `cotton_memory_projects.brand`. /// /// Answers a normalised kit or a sentence a person can read — the app puts it /// in a toast, the server returns it as the tool's refusal, and neither writes /// a rule of its own. pub fn parse_project_brand(value: &Value) -> Result { let Some(value) = object_of(value) else { return Err("a brand kit is an object".to_string()); }; let colors = match value.get("colors") { None => Vec::new(), Some(raw) => parse_colors(raw)?, }; let fonts = match value.get("fonts") { None => Vec::new(), Some(raw) => parse_fonts(raw)?, }; let voice = match value.get("voice") { None | Some(Value::Null) => String::new(), Some(Value::String(raw)) => raw.trim().to_string(), Some(_) => return Err("voice must be text".to_string()), }; if chars(&voice) > BRAND_VOICE_MAX { return Err(format!("voice is at most {BRAND_VOICE_MAX} characters")); } let tagline = match value.get("tagline") { None | Some(Value::Null) => String::new(), Some(Value::String(raw)) => raw.trim().to_string(), Some(_) => return Err("tagline must be text".to_string()), }; if chars(&tagline) > BRAND_TAGLINE_MAX { return Err(format!( "a tagline is at most {BRAND_TAGLINE_MAX} characters" )); } let links = match value.get("links") { None => Vec::new(), Some(raw) => parse_links(raw)?, }; let mut brand = Map::new(); brand.insert("colors".to_string(), Value::Array(colors)); brand.insert("fonts".to_string(), Value::Array(fonts)); brand.insert("voice".to_string(), Value::from(voice)); if !tagline.is_empty() { brand.insert("tagline".to_string(), Value::from(tagline)); } if !links.is_empty() { brand.insert("links".to_string(), Value::Array(links)); } Ok(brand) } /// Nothing filled in — what a writer stores as `null` rather than as an object /// full of blanks, so "no brand kit" has ONE representation. pub fn brand_is_empty(brand: &ProjectBrand) -> bool { let empty_list = |key: &str| { brand .get(key) .and_then(Value::as_array) .is_none_or(|list| list.is_empty()) }; empty_list("colors") && empty_list("fonts") && brand .get("voice") .and_then(Value::as_str) .is_none_or(|voice| voice.trim().is_empty()) && brand .get("tagline") .and_then(Value::as_str) .is_none_or(str::is_empty) && empty_list("links") } /// Whether a project's BRAND section holds anything — a kit with something /// in it, or at least one logo file linked in a brand role. /// /// ONE answer for every reader that draws the section, `get_project` (the /// page) first. A kit that fails to parse reads as no kit, /// [`read_project_brand`]'s rule. pub fn brand_kit_holds(brand: Option<&Value>, brand_files: usize) -> bool { brand_files > 0 || read_project_brand(brand).is_some_and(|kit| !brand_is_empty(&kit)) } /// The column's value as a row hands it back, read into a kit. /// /// A value the parse REFUSES answers `None` rather than throwing. This is a /// read on the path of every project list: throwing would black out every /// project page over one bad row, and the row on disk is untouched by answering /// none — the next write through [`parse_project_brand`] replaces it. pub fn read_project_brand(value: Option<&Value>) -> Option { match value { None | Some(Value::Null) => None, Some(value) => parse_project_brand(value).ok(), } }