From 1959fc3d71bf90ece9db6cbf329f92950e9fc452 Mon Sep 17 00:00:00 2001 From: phonedu <135960865+phonedu@users.noreply.github.com> Date: Tue, 10 Nov 2026 11:44:18 +0800 Subject: [PATCH] M13: design review commands (engine and MCP) --- crates/doc/src/design_review.rs | 111 ++ crates/doc/src/lib.rs | 6 + crates/engine/src/automation/inspect.rs | 2 + crates/engine/src/cmd.rs | 1 + crates/engine/src/cmd/create.rs | 26 +- crates/engine/src/cmd/props.rs | 2 +- crates/engine/src/design/audit.rs | 1318 +++++++++++++++++++++ crates/engine/src/design/fix.rs | 319 +++++ crates/engine/src/design/mod.rs | 378 ++++++ crates/engine/src/design/rules.rs | 132 +++ crates/engine/src/design/tests.rs | 863 ++++++++++++++ crates/engine/src/inspect_fields_tests.rs | 1 + crates/engine/src/lib.rs | 1 + crates/engine/src/prefs.rs | 4 + crates/mcp/src/prompts.rs | 20 +- crates/mcp/src/server.rs | 6 +- crates/mcp/tests/it/protocol.rs | 5 +- 17 files changed, 3183 insertions(+), 12 deletions(-) create mode 100644 crates/doc/src/design_review.rs create mode 100644 crates/engine/src/design/audit.rs create mode 100644 crates/engine/src/design/fix.rs create mode 100644 crates/engine/src/design/mod.rs create mode 100644 crates/engine/src/design/rules.rs create mode 100644 crates/engine/src/design/tests.rs diff --git a/crates/doc/src/design_review.rs b/crates/doc/src/design_review.rs new file mode 100644 index 000000000..c2fce64c8 --- /dev/null +++ b/crates/doc/src/design_review.rs @@ -0,0 +1,111 @@ +//! The design system a file's review follows: how strict it is, the spacing grid, the radii it +//! accepts and the brand accents it knows (`design.configure`). +//! +//! Kept in the document, so a file carries its settings for everyone who opens it, and the audit, +//! the fixer and CI all read the same values. + +use figcraft_color::Color; +use serde::{Deserialize, Serialize}; + +/// How strict `design.audit` is. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum DesignPreset { + /// The rules that catch the usual AI-generated tells. + #[default] + Recommended, + /// Recommended plus the judgment calls (too many accent colours, frames without auto layout). + Strict, + /// Only the findings that keep a design usable: contrast, the type floor, gradient text and + /// clipped text. + Accessibility, +} + +impl DesignPreset { + pub const ALL: [Self; 3] = [Self::Recommended, Self::Strict, Self::Accessibility]; + + pub fn id(self) -> &'static str { + match self { + Self::Recommended => "recommended", + Self::Strict => "strict", + Self::Accessibility => "accessibility", + } + } + + pub fn from_id(s: &str) -> Option { + match s.trim().to_ascii_lowercase().as_str() { + "recommended" | "default" => Some(Self::Recommended), + "strict" => Some(Self::Strict), + "accessibility" | "a11y" => Some(Self::Accessibility), + _ => None, + } + } +} + +/// The smallest and largest spacing grid a file may set. +pub const GRID_MIN: f64 = 1.0; +pub const GRID_MAX: f64 = 64.0; + +/// Most radii and brand colours a file keeps. +pub const MAX_RADII: usize = 32; +pub const MAX_BRAND_COLORS: usize = 32; + +/// A file's design review settings. The default is the recommended preset on a 4px grid with the +/// 4px radius scale and no brand palette. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(default, rename_all = "camelCase")] +pub struct DesignReview { + pub preset: DesignPreset, + /// The spacing and radius grid in pixels (`0`: 4). A value outside [`GRID_MIN`]..=[`GRID_MAX`] + /// reads as the default. + pub grid: f64, + /// The corner radii the design uses, in pixels. Empty: any multiple of the grid from the grid + /// up, or a pill. + pub radii: Vec, + /// The brand's accent colours: they don't count as stray accents (`color.accents`). + pub brand: Vec, + /// Rule ids this file turns off. + pub disabled: Vec, +} + +impl DesignReview { + /// Whether the settings are the default ones (nothing to save). + pub fn is_default(&self) -> bool { + *self == Self::default() + } + + /// The grid in pixels, with invalid values read as 4. + pub fn grid(&self) -> f64 { + if self.grid.is_finite() && (GRID_MIN..=GRID_MAX).contains(&self.grid) { self.grid } else { 4.0 } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn presets_round_trip_by_id() { + for p in DesignPreset::ALL { + assert_eq!(DesignPreset::from_id(p.id()), Some(p)); + } + assert_eq!(DesignPreset::from_id("a11y"), Some(DesignPreset::Accessibility)); + assert_eq!(DesignPreset::from_id("loud"), None); + } + + #[test] + fn a_default_file_does_not_serialize_the_settings_and_junk_grid_reads_as_four() { + let doc = crate::Document::new("Untitled"); + let json = serde_json::to_value(&doc).unwrap(); + assert!(json.get("designReview").is_none(), "{json}"); + let mut settings = DesignReview::default(); + assert!(settings.is_default()); + settings.grid = -3.0; + assert_eq!(settings.grid(), 4.0); + settings.grid = f64::NAN; + assert_eq!(settings.grid(), 4.0); + settings.grid = 8.0; + assert_eq!(settings.grid(), 8.0); + assert!(!settings.is_default()); + } +} diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 81760d718..ac6cf5602 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -12,6 +12,7 @@ pub mod board; mod board_route; pub mod colors; pub mod comments; +pub mod design_review; pub mod facilitation; pub mod geometry; pub mod handoff; @@ -30,6 +31,7 @@ pub use board::*; pub use board_route::{END_GAP, MAX_RUNS, RouteEnd, attach_points, attached_sides, path_handles, reshaped, route_along, route_points}; pub use colors::*; pub use comments::*; +pub use design_review::{DesignPreset, DesignReview, GRID_MAX, GRID_MIN, MAX_BRAND_COLORS, MAX_RADII}; pub use facilitation::*; pub use figcraft_color as color; pub use figcraft_geom as geom; @@ -229,6 +231,9 @@ pub struct Document { /// Image adjustment presets saved in this file. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub image_presets: Vec, + /// The design system and rules this file's review follows (`design.configure`). + #[serde(default, skip_serializing_if = "DesignReview::is_default")] + pub design_review: DesignReview, /// Annotation categories (`None`: [`AnnotationCategory::defaults`]). #[serde(default, skip_serializing_if = "Option::is_none")] pub annotation_categories: Option>, @@ -285,6 +290,7 @@ impl Document { published: None, color_profile: ColorProfile::Srgb, image_presets: Vec::new(), + design_review: DesignReview::default(), annotation_categories: None, dev_snapshots: BTreeMap::new(), timer: None, diff --git a/crates/engine/src/automation/inspect.rs b/crates/engine/src/automation/inspect.rs index 324635071..d4615bb84 100644 --- a/crates/engine/src/automation/inspect.rs +++ b/crates/engine/src/automation/inspect.rs @@ -40,6 +40,7 @@ pub const NODE_KEYS: &[&str] = &[ "fontFamily", "fontSize", "fontStyle", + "fontWeight", "fontVariations", "gridCell", "grids", @@ -398,6 +399,7 @@ fn text_props(t: &TextData, o: &mut serde_json::Map, options: &In }); insert_prop(o, options, "fontFamily", || json!(t.style.font_family)); insert_prop(o, options, "fontStyle", || json!(t.style.font_style)); + insert_prop(o, options, "fontWeight", || json!(t.style.weight())); insert_prop(o, options, "fontSize", || json!(t.style.font_size)); if !t.style.variations.is_empty() { insert_prop(o, options, "fontVariations", || json!(t.style.variations)); diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 0e90dc198..8ab89c1d5 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -107,6 +107,7 @@ fn registry() -> &'static Registry { list.extend(crate::dev_resources::specs()); list.extend(crate::dev_measurements::specs()); list.extend(crate::distance::specs()); + list.extend(crate::design::specs()); list.extend(crate::collab::specs()); list.extend(crate::branches::specs()); list.extend(crate::plugins::specs()); diff --git a/crates/engine/src/cmd/create.rs b/crates/engine/src/cmd/create.rs index 435c3422a..920ec1113 100644 --- a/crates/engine/src/cmd/create.rs +++ b/crates/engine/src/cmd/create.rs @@ -1,7 +1,7 @@ //! Creating nodes. use figcraft_color::{ImageFilters, ImageScaleMode, Paint}; -use figcraft_doc::{Document, Node, NodeId, NodeKind, StrokeCap, TextAutoResize, TextData, VectorNetwork}; +use figcraft_doc::{Document, Node, NodeId, NodeKind, Sizing, StrokeCap, TextAutoResize, TextData, VectorNetwork}; use figcraft_geom::Point; use serde_json::{Value, json}; @@ -99,7 +99,7 @@ pub fn specs() -> Vec { spec!( "text.create", "Text", - "{text | characters, x, y, parent?, index?, name? (default: the first line), width? (fixed width wraps), props? (fontSize, fontFamily, …), select? (default true)}", + "{text | characters, x?, y? (ignored inside an auto layout parent), parent?, index?, name? (default: the first line), width? (fixed width wraps), props? (fontSize, fontWeight, fontFamily, …), select? (default true)}", true, |s, p| { create_kind(s, p, "text") } ), @@ -275,7 +275,9 @@ pub fn create(s: &mut Session, p: &Value) -> Result { let doc = s.doc()?; let pn = doc.get(parent)?; if !pn.kind.is_container() { - return Err(bad(cmd, format!("{parent} can't contain layers"))); + let name = pn.name.trim(); + let what = if name.is_empty() { pn.kind.type_name().to_string() } else { format!("{} \"{}\"", pn.kind.type_name(), name) }; + return Err(bad(cmd, format!("{parent} ({what}) can't contain layers"))); } if base == "Section" && !doc.takes_sections(parent) { return Err(bad(cmd, "sections go on the page or in other sections")); @@ -371,6 +373,24 @@ pub fn create(s: &mut Session, p: &Value) -> Result { doc.insert(node, parent, index)?; if let Some(Value::Object(props)) = get(p, "props") { super::props::apply(cmd, doc, nid, props)?; + // An auto layout frame hugs the axes the caller left unset — the incumbent's default, and + // the difference between a card and a 100pt-tall box that silently clips its rows. + // Explicit width/height and explicit sizing keep their fixed/fill behaviour. + if doc.node(nid).is_some_and(|n| n.layout.is_some()) { + let asked = |axis: &str, keys: &[&str]| { + let long = if axis == "h" { "width" } else { "height" }; + let short = if axis == "h" { "w" } else { "h" }; + num(p, long).is_some() || props.contains_key(long) || props.contains_key(short) || keys.iter().any(|k| props.contains_key(*k)) + }; + if let Some(n) = doc.node_mut(nid) { + if !asked("h", &["sizingH", "layoutSizingHorizontal"]) { + n.child_layout.sizing_h = Sizing::Hug; + } + if !asked("v", &["sizingV", "layoutSizingVertical"]) { + n.child_layout.sizing_v = Sizing::Hug; + } + } + } } if boolean(p, "select").unwrap_or(true) { ds.selection = vec![nid]; diff --git a/crates/engine/src/cmd/props.rs b/crates/engine/src/cmd/props.rs index 2e5da37bd..f077a31d9 100644 --- a/crates/engine/src/cmd/props.rs +++ b/crates/engine/src/cmd/props.rs @@ -23,7 +23,7 @@ clip, isMask, layout (null|horizontal|vertical|grid|{...}), gap, crossGap, paddi mainAlign (min|center|max, or the auto gaps spaceBetween|spaceAround|spaceEvenly), crossAlign (min|center|max|baseline: first text baselines, horizontal layouts), contentAlign (wrapped lines: auto = packed where crossAlign says | spaceBetween), wrap (rows of a horizontal layout, columns of a vertical one), strokesIncluded (the frame's inside stroke takes up space), reverseZ (canvas stacking: true = first on top), \ columnGap / rowGap (aliases of gap / crossGap), gridColumns, gridRows, columnTracks / rowTracks ([120 | \"1fr\" | \"auto\" | {sizing, value}]), \ gridColumn / gridRow (0-based cell anchor, null = auto), gridColumnSpan, gridRowSpan, gridAlignH / gridAlignV (a grid child's alignment in its cell: min|center|max, auto/null = the frame's), sizingH / sizingV (fixed|hug|fill), \ -absolute (ignore auto layout; follows constraints), minWidth, maxWidth, minHeight, maxHeight (null removes), constraints {horizontal, vertical}, grids, exports, characters, fontFamily, fontStyle, \ +absolute (ignore auto layout; follows constraints), minWidth, maxWidth, minHeight, maxHeight (null removes), constraints {horizontal, vertical}, grids, exports, characters, fontFamily, fontStyle, fontWeight (a number: 400 Regular, 600 Semi Bold — the nearest face the family has), \ fontSize, lineHeight (auto|px|\"150%\"), letterSpacing (px|\"2%\"), textAlign (left|center|right|justified), textAlignVertical, textAutoResize \ (widthAndHeight|height|none|truncate), textDecoration, textDecorationStyle (solid|dotted|wavy), textDecorationThickness / textDecorationOffset \ (auto|px|\"10%\" of the font size; the offset runs from the baseline down to an underline's top edge), textDecorationSkipInk (underlines break around descenders), \ diff --git a/crates/engine/src/design/audit.rs b/crates/engine/src/design/audit.rs new file mode 100644 index 000000000..0a39840e5 --- /dev/null +++ b/crates/engine/src/design/audit.rs @@ -0,0 +1,1318 @@ +//! Walking the scope and turning what it finds into findings. +//! +//! Nothing here edits the document: `design.audit` reads pages and reports. The walk stops at an +//! instance's children (they mirror the main component, which is audited where it lives), skips +//! hidden layers and caps the number of nodes so a huge file cannot stall the app. + +use std::collections::{BTreeMap, BTreeSet}; + +use figcraft_color::{BlendMode, Color, Paint, PaintKind}; +use figcraft_doc::{ + CollectionId, DesignPreset, Document, Effect, EffectKind, LayoutMode, ModeId, Node, NodeId, NodeKind, Shadow, Sizing, StrokeAlign, + TextAutoResize, TextData, VariableValue, +}; +use serde_json::{Map, Value, json}; + +use crate::cmd::lists::paint_binding_key; + +use super::rules::{Severity, rule}; + +/// Most layers one audit looks at; past it the report says `truncated`. +const MAX_NODES: usize = 50_000; +/// Most text layers one audit lays out for the overflow check (text layout is the expensive part). +const MAX_TEXT_MEASURED: usize = 2_000; +/// Most auto layout frames one audit measures for clipped children (bounds are per-subtree). +const MAX_FRAMES_MEASURED: usize = 500; +/// Most siblings or children one backdrop lookup scans before it stops guessing; a flat frame with +/// tens of thousands of layers must not turn every text check into a full scan. +const MAX_BACKDROP_SCAN: usize = 512; + +/// The design system a run checks against: the file's settings (`design.configure`) with an +/// optional preset override from the call. +#[derive(Clone)] +pub(crate) struct Settings { + pub(crate) preset: DesignPreset, + pub(crate) grid: f64, + /// Allowed corner radii; empty: any multiple of the grid from the grid up, or a pill. + pub(crate) radii: Vec, + /// Brand accents as 8-bit RGBA. + pub(crate) brand: Vec<[u8; 4]>, + pub(crate) disabled: BTreeSet, + /// Variable modes the run resolves colours in (empty: the document's own modes). + pub(crate) modes: BTreeMap, + /// The same modes by collection and mode name, for the message and the report. + pub(crate) mode_labels: BTreeMap, +} + +impl Settings { + pub(crate) fn new(doc: &Document, preset: Option) -> Self { + let config = &doc.design_review; + Self { + preset: preset.unwrap_or(config.preset), + grid: config.grid(), + radii: config.radii.iter().copied().filter(|r| r.is_finite() && (0.0..=999.0).contains(r)).collect(), + brand: config.brand.iter().map(|c| c.to_rgba8()).collect(), + disabled: config.disabled.iter().cloned().collect(), + modes: BTreeMap::new(), + mode_labels: BTreeMap::new(), + } + } + + /// Resolve colours in `modes` (collection and mode ids, already checked against the document). + pub(crate) fn in_modes(mut self, doc: &Document, modes: BTreeMap) -> Self { + for (collection, mode) in &modes { + let Some(c) = doc.variables.collection_by_id(collection) else { continue }; + let Some(m) = c.mode_by_id(mode) else { continue }; + self.mode_labels.insert(c.name.clone(), m.name.clone()); + } + self.modes = modes; + self + } + + /// The mode names for a finding's message, when any are overridden. + fn mode_note(&self) -> String { + self.mode_labels.iter().map(|(c, m)| format!("{c}: {m}")).collect::>().join(", ") + } + + /// Whether a run using these settings reports `id`. + pub(crate) fn enabled(&self, id: &str) -> bool { + !self.disabled.contains(id) && super::rules::enabled(id, self.preset) + } + + fn on_grid(&self, v: f64) -> bool { + v.is_finite() && ((v / self.grid) - (v / self.grid).round()).abs() <= 0.01 + } + + pub(crate) fn snap(&self, v: f64) -> f64 { + if v.is_finite() { ((v / self.grid).round() * self.grid).max(0.0) } else { 0.0 } + } + + pub(crate) fn radius_ok(&self, r: f64, w: f64, h: f64) -> bool { + if !r.is_finite() || r <= 0.01 { + return true; + } + let min = w.min(h); + let pill = min > 0.0 && (r - min / 2.0).abs() <= 1.0; + if pill { + return true; + } + if !self.radii.is_empty() { + return self.radii.iter().any(|a| (r - a).abs() <= 0.5); + } + r >= self.grid && self.on_grid(r) + } + + pub(crate) fn snap_radius(&self, r: f64) -> f64 { + if !r.is_finite() { + return self.grid; + } + if !self.radii.is_empty() { + let mut best = self.grid; + let mut distance = f64::INFINITY; + for a in &self.radii { + let d = (r - a).abs(); + if d < distance { + best = *a; + distance = d; + } + } + return best; + } + ((r / self.grid).round() * self.grid).max(self.grid) + } + + /// Whether `c` is one of the file's brand accents (within a few 8-bit steps per channel). + pub(crate) fn is_brand(&self, c: Color) -> bool { + let rgba = c.to_rgba8(); + self.brand.iter().any(|b| (0..4).all(|i| b[i].abs_diff(rgba[i]) <= 12)) + } + + /// The settings a report or the window shows. + pub(crate) fn json(&self) -> Value { + let mut v = json!({"preset": self.preset.id(), "grid": self.grid}); + if !self.mode_labels.is_empty() + && let Some(o) = v.as_object_mut() + { + o.insert("modes".into(), json!(self.mode_labels)); + } + v + } +} + +/// One finding, owned so `design.fix` can act on it after the walk. +#[derive(Clone)] +pub(crate) struct Finding { + pub(crate) rule: &'static str, + pub(crate) severity: Severity, + pub(crate) node: NodeId, + pub(crate) path: String, + pub(crate) message: String, + pub(crate) fixable: bool, + pub(crate) suggestion: Option, + /// The values behind the message, for a localized line in the window and for agents. + pub(crate) details: Option, + /// Why a finding is not fixable: `"bound"` (owned by a variable or style), `"modes"` (read in + /// the chosen variable modes), `None` (needs a decision). Only for `fixable: false`. + pub(crate) reason: Option<&'static str>, +} + +impl Finding { + fn json(&self) -> Value { + let mut v = json!({ + "rule": self.rule, + "severity": self.severity.id(), + "node": self.node, + "path": self.path, + "message": self.message, + "fixable": self.fixable, + }); + if let (Some(s), Some(o)) = (&self.suggestion, v.as_object_mut()) { + o.insert("suggestion".into(), s.clone()); + } + if let (Some(d), Some(o)) = (&self.details, v.as_object_mut()) { + o.insert("details".into(), d.clone()); + } + if !self.fixable + && let Some(o) = v.as_object_mut() + { + o.insert("reason".into(), json!(self.reason.unwrap_or("decision"))); + } + v + } +} + +/// What one walk found. +pub(crate) struct Report { + pub(crate) findings: Vec, + pub(crate) nodes: usize, + pub(crate) truncated: bool, +} + +/// A colour token's default-mode value, for the hardcoded-value check. +struct TokenColor { + name: String, + rgba: [u8; 4], +} + +/// A number token's default-mode value. +struct TokenNumber { + name: String, + value: f64, +} + +/// The file's variables in their collections' default modes. Layers with explicit modes are left +/// out of the token checks (the default value may not be what they show). +struct Tokens { + colors: Vec, + numbers: Vec, +} + +impl Tokens { + fn new(doc: &Document) -> Self { + if doc.variables.variables.is_empty() { + return Self { colors: Vec::new(), numbers: Vec::new() }; + } + let modes: BTreeMap = + doc.variables.collections.iter().filter_map(|c| c.default_mode().map(|m| (c.id.clone(), m.clone()))).collect(); + let mut colors = Vec::new(); + let mut numbers = Vec::new(); + for var in &doc.variables.variables { + let name = if var.name.is_empty() { var.id.clone() } else { var.name.clone() }; + match doc.variables.resolve(&var.id, &modes) { + Some(VariableValue::Color(c)) if c.a > 0.01 => colors.push(TokenColor { name, rgba: c.to_rgba8() }), + Some(VariableValue::Number(n)) if n.is_finite() && n > 0.01 => numbers.push(TokenNumber { name, value: n }), + _ => {} + } + } + colors.sort_by_key(|c| c.rgba); + colors.dedup_by(|a, b| a.rgba == b.rgba); + numbers.sort_by(|a, b| a.value.total_cmp(&b.value)); + numbers.dedup_by(|a, b| (a.value - b.value).abs() <= 1e-6); + Self { colors, numbers } + } + + fn is_empty(&self) -> bool { + self.colors.is_empty() && self.numbers.is_empty() + } + + fn number(&self, value: f64) -> Option<&TokenNumber> { + self.numbers.iter().find(|t| (t.value - value).abs() <= 1e-6) + } + + fn color(&self, color: Color) -> Option<&TokenColor> { + let rgba = color.to_rgba8(); + self.colors.iter().find(|t| t.rgba == rgba) + } +} + +struct Ctx<'a> { + doc: &'a Document, + findings: Vec, + visited: usize, + text_nodes: usize, + /// Font sizes in half-pixels, so 12.5 stays distinct from 12. + sizes: BTreeSet, + families: BTreeSet, + /// Layers carrying at least one shadow. + shadowed: usize, + /// Text layers laid out for the overflow check. + measured: usize, + /// Auto layout frames measured for clipped children. + measured_frames: usize, + tokens: Tokens, + /// The design system this run checks against. + settings: Settings, + /// Distinct accent colours, with the first layer that paints each (for `color.accents`). + accents: BTreeMap<[u8; 4], String>, + truncated: bool, +} + +/// Walk `roots` and collect every finding. `design.audit` reports them; `design.fix` acts on the +/// ones marked fixable. +pub(crate) fn collect(doc: &Document, roots: &[NodeId], anchor: Option, anchor_path: &str, scope: &str, settings: &Settings) -> Report { + let mut ctx = Ctx { + doc, + findings: Vec::new(), + visited: 0, + text_nodes: 0, + sizes: BTreeSet::new(), + families: BTreeSet::new(), + shadowed: 0, + measured: 0, + measured_frames: 0, + tokens: Tokens::new(doc), + settings: settings.clone(), + accents: BTreeMap::new(), + truncated: false, + }; + for root in roots { + ctx.walk(*root); + } + ctx.scope_rules(anchor, anchor_path, scope); + Report { findings: ctx.findings, nodes: ctx.visited, truncated: ctx.truncated } +} + +/// Audit `roots` (pages, frames or layers), labelled `scope` in the report. Aggregate findings +/// (too many type sizes…) point at `anchor`. +pub(crate) fn run( + doc: &Document, + roots: &[NodeId], + scope: &str, + anchor: Option, + anchor_path: &str, + min: Severity, + filter: Option<&BTreeSet>, + preset: Option, + modes: BTreeMap, +) -> Value { + let settings = Settings::new(doc, preset).in_modes(doc, modes); + let report = collect(doc, roots, anchor, anchor_path, scope, &settings); + let shown: Vec<&Finding> = report + .findings + .iter() + .filter(|f| f.severity >= min && settings.enabled(f.rule)) + .filter(|f| filter.is_none_or(|set| set.contains(f.rule))) + .collect(); + let mut counts = [0usize; 3]; + for f in &shown { + counts[f.severity.index()] += 1; + } + let score = (100.0 - shown.iter().map(|f| f.severity.penalty()).sum::()).clamp(0.0, 100.0).round(); + let mut by_rule: BTreeMap<&str, usize> = BTreeMap::new(); + for f in &shown { + *by_rule.entry(f.rule).or_default() += 1; + } + let findings: Vec = shown.into_iter().map(Finding::json).collect(); + let mut out = settings.json(); + if let Some(o) = out.as_object_mut() { + o.insert("scope".into(), json!(scope)); + o.insert("score".into(), json!(score)); + o.insert("counts".into(), json!({"high": counts[2], "medium": counts[1], "low": counts[0]})); + o.insert("byRule".into(), json!(by_rule)); + o.insert("nodes".into(), json!(report.nodes)); + o.insert("findings".into(), json!(findings)); + o.insert("truncated".into(), json!(report.truncated)); + } + out +} + +impl Ctx<'_> { + fn walk(&mut self, root: NodeId) { + let mut stack = vec![(root, String::new())]; + while let Some((id, parent)) = stack.pop() { + if self.visited >= MAX_NODES { + self.truncated = true; + return; + } + let Some(n) = self.doc.node(id) else { continue }; + if !n.visible || n.locked || n.opacity <= 0.001 { + continue; + } + self.visited += 1; + let name = label(n); + let path = if parent.is_empty() { name } else { format!("{parent} / {name}") }; + if !n.is_page() { + self.check_node(n, &path); + } + // An instance's children mirror its main component; audit the main where it lives. + if matches!(&n.kind, NodeKind::Instance { .. }) { + continue; + } + for child in n.children.iter().rev() { + stack.push((*child, path.clone())); + } + } + } + + fn check_node(&mut self, n: &Node, path: &str) { + self.check_naming(n, path); + self.check_spacing(n, path); + self.check_radius(n, path); + self.check_paints(n, path); + self.check_effects(n, path); + if let NodeKind::Text(t) = &n.kind { + self.check_text(n, t, path); + } + self.check_layout(n, path); + self.check_clipping(n, path); + self.note_accents(n); + self.check_tokens(n, path); + } + + fn check_naming(&mut self, n: &Node, path: &str) { + if is_default_name(&n.name) { + self.push_details( + "naming.auto", + n.id, + path, + format!("Layer still has its default name \"{}\"", n.name.trim()), + None, + Some(json!({"name": n.name.trim()})), + ); + } + } + + /// A frame or component holding several layers without auto layout: in the Strict preset. + fn check_layout(&mut self, n: &Node, path: &str) { + if n.layout.is_some() || n.children.len() < 3 { + return; + } + if matches!(n.kind, NodeKind::Frame | NodeKind::Component { .. } | NodeKind::ComponentSet { .. }) { + let count = n.children.len(); + self.push_details( + "layout.no-auto-layout", + n.id, + path, + format!("{count} children with no auto layout"), + None, + Some(json!({"children": count})), + ); + } + } + + /// A fixed-size auto layout frame that clips children which overflow it: the rows exist but + /// are invisible — the usual headless surprise. Hug frames grow, so they cannot clip. + fn check_clipping(&mut self, n: &Node, path: &str) { + if self.measured_frames >= MAX_FRAMES_MEASURED || !n.clip || n.children.is_empty() || n.layout.is_none() { + return; + } + // An instance mirrors its main; the main is audited where it lives. + if matches!(n.kind, NodeKind::Instance { .. }) { + return; + } + let fixed_h = n.child_layout.sizing_h != Sizing::Hug; + let fixed_v = n.child_layout.sizing_v != Sizing::Hug; + if !(fixed_h || fixed_v) { + return; + } + let Some(frame) = self.doc.world_bounds(n.id) else { return }; + let mut u: Option<(f64, f64, f64, f64)> = None; + for child in &n.children { + let Some(c) = self.doc.node(*child) else { continue }; + if !c.visible { + continue; + } + if let Some(b) = self.doc.world_bounds(*child) { + u = Some(match u { + None => (b.x0, b.y0, b.x1, b.y1), + Some((x0, y0, x1, y1)) => (x0.min(b.x0), y0.min(b.y0), x1.max(b.x1), y1.max(b.y1)), + }); + } + } + self.measured_frames += 1; + let Some((ux0, uy0, ux1, uy1)) = u else { return }; + let over_h = fixed_h && (ux1 > frame.x1 + 1.0 || ux0 < frame.x0 - 1.0); + let over_v = fixed_v && (uy1 > frame.y1 + 1.0 || uy0 < frame.y0 - 1.0); + if !(over_h || over_v) { + return; + } + let mut suggestion = Map::new(); + if over_h { + suggestion.insert("sizingH".into(), json!("hug")); + } + if over_v { + suggestion.insert("sizingV".into(), json!("hug")); + } + self.push_details( + "layout.clipped", + n.id, + path, + format!( + "Fixed-size frame clips children that reach {:.0}×{:.0} inside its {:.0}×{:.0}; they are invisible", + ux1 - ux0, + uy1 - uy0, + frame.x1 - frame.x0, + frame.y1 - frame.y0 + ), + Some(Value::Object(suggestion)), + Some(json!({"width": ux1 - ux0, "height": uy1 - uy0, "frameWidth": frame.x1 - frame.x0, "frameHeight": frame.y1 - frame.y0})), + ); + } + + /// Collect the accent colours the scope paints (brand accents and neutrals excluded), for + /// `color.accents`. + fn note_accents(&mut self, n: &Node) { + let paints = match &n.kind { + NodeKind::Text(t) => t.style.fills.as_deref().unwrap_or(&n.fills), + _ => &n.fills, + }; + for p in paints.iter().chain(n.strokes.iter()) { + if !p.visible || p.opacity < 0.5 { + continue; + } + let PaintKind::Solid { color } = &p.kind else { continue }; + if self.settings.is_brand(*color) { + continue; + } + if let Some(rgba) = accent_rgba(*color) + && self.accents.len() < 64 + { + self.accents.entry(rgba).or_insert_with(|| n.name.trim().to_string()); + } + } + } + + fn check_spacing(&mut self, n: &Node, path: &str) { + let Some(al) = &n.layout else { return }; + let mut off = Vec::new(); + let mut suggestion = Map::new(); + if al.mode != LayoutMode::Grid { + if !self.settings.on_grid(al.gap) { + off.push(format!("gap {}", al.gap)); + suggestion.insert("gap".into(), json!(self.settings.snap(al.gap))); + } + if al.wrap && !self.settings.on_grid(al.cross_gap) { + off.push(format!("cross gap {}", al.cross_gap)); + suggestion.insert("crossGap".into(), json!(self.settings.snap(al.cross_gap))); + } + } + let sides = ["top", "right", "bottom", "left"]; + let mut padding_off = false; + for (i, side) in sides.iter().enumerate() { + if let Some(v) = al.padding.get(i).copied().filter(|v| !self.settings.on_grid(*v)) { + off.push(format!("padding {side} {v}")); + padding_off = true; + } + } + if padding_off { + suggestion.insert("padding".into(), json!(al.padding.map(|v| self.settings.snap(v)))); + } + if !off.is_empty() { + let suggestion = if suggestion.is_empty() { None } else { Some(Value::Object(suggestion)) }; + let mut details = Map::new(); + details.insert("grid".into(), json!(self.settings.grid)); + if !self.settings.on_grid(al.gap) { + details.insert("gap".into(), json!(al.gap)); + } + if al.wrap && !self.settings.on_grid(al.cross_gap) { + details.insert("crossGap".into(), json!(al.cross_gap)); + } + if padding_off { + details.insert("padding".into(), json!(al.padding)); + } + self.push_details( + "spacing.off-grid", + n.id, + path, + format!("Off the {}px grid: {}", self.settings.grid, off.join(", ")), + suggestion, + Some(Value::Object(details)), + ); + if [ + "gap", + "columnGap", + "rowGap", + "crossGap", + "padding", + "paddingHorizontal", + "paddingVertical", + "paddingTop", + "paddingRight", + "paddingBottom", + "paddingLeft", + ] + .iter() + .any(|k| n.bound.contains_key(*k)) + { + self.not_fixable(" (bound to a variable)", "bound"); + } + } + } + + fn check_radius(&mut self, n: &Node, path: &str) { + let mut bad: Vec = n.corners.radii.iter().copied().filter(|r| *r > 0.01 && !self.settings.radius_ok(*r, n.width, n.height)).collect(); + if bad.is_empty() { + return; + } + bad.sort_by(f64::total_cmp); + bad.dedup_by(|a, b| (*a - *b).abs() <= 0.01); + let shown: Vec = bad.iter().map(|r| r.to_string()).collect(); + let suggested = self.settings.snap_radius(bad.first().copied().unwrap_or(0.0)); + let suggestion = json!({"cornerRadius": suggested}); + let scale = if self.settings.radii.is_empty() { + format!("any multiple of {}, or a pill", self.settings.grid) + } else { + let list: Vec = self.settings.radii.iter().map(|r| r.to_string()).collect(); + format!("{}, or a pill", list.join(", ")) + }; + self.push_details( + "radius.off-scale", + n.id, + path, + format!("Corner radius off the scale: {} (use {scale})", shown.join(", ")), + Some(suggestion), + Some(json!({"radii": bad, "suggested": suggested})), + ); + if ["cornerRadius", "topLeftRadius", "topRightRadius", "bottomRightRadius", "bottomLeftRadius"].iter().any(|k| n.bound.contains_key(*k)) { + self.not_fixable(" (bound to a variable)", "bound"); + } + } + + fn check_paints(&mut self, n: &Node, path: &str) { + let is_text = matches!(&n.kind, NodeKind::Text(_)); + let fills: &[Paint] = match &n.kind { + NodeKind::Text(t) => t.style.fills.as_deref().unwrap_or(&n.fills), + _ => &n.fills, + }; + let fills_gradient = fills.iter().any(|p| p.visible && matches!(&p.kind, PaintKind::Gradient(_))); + let strokes_gradient = n.strokes.iter().any(|p| p.visible && matches!(&p.kind, PaintKind::Gradient(_))); + let run_gradient = match &n.kind { + NodeKind::Text(t) => t + .runs + .iter() + .any(|r| r.style.fills.as_ref().is_some_and(|paints| paints.iter().any(|p| p.visible && matches!(&p.kind, PaintKind::Gradient(_))))), + _ => false, + }; + if fills_gradient || strokes_gradient || run_gradient { + let id = if is_text { "color.gradient-text" } else { "color.gradient" }; + self.push(id, n.id, path, "Painted with a gradient (a hue-to-hue wash is the usual AI tell)".into(), None); + } + // A hairline border is for container-like shapes; an icon's stroke is its whole drawing, + // so full opacity is the intent there, not a stray border. + let container_like = matches!(&n.kind, NodeKind::Frame | NodeKind::Rectangle | NodeKind::Ellipse { .. } | NodeKind::Component { .. }); + if container_like && has_stroke(n) && border_is_strong(self.doc, n) { + self.push( + "color.border-opacity", + n.id, + path, + "Border is more opaque than a hairline (6–10% is enough)".into(), + Some(json!({"strokeOpacity": 0.08})), + ); + if n.styles.stroke.is_some() || n.bound.keys().any(|k| k.starts_with("strokes/")) { + self.not_fixable(" (bound to a style or variable)", "bound"); + } + } + } + + fn check_effects(&mut self, n: &Node, path: &str) { + let mut glow = false; + let mut colored = false; + let mut shadows = 0; + for e in n.effects.iter().filter(|e| e.visible) { + if let EffectKind::DropShadow(s) | EffectKind::InnerShadow(s) = &e.kind { + shadows += 1; + glow |= is_glow(e); + colored |= is_colored_shadow(s); + } + } + if shadows > 0 { + self.shadowed += 1; + } + if glow { + self.push( + "color.glow", + n.id, + path, + "Shadow has no offset and a large blur, so it reads as a glow".into(), + Some(json!({"removeEffects": ["dropShadow", "innerShadow"]})), + ); + if n.styles.effect.is_some() || n.bound.keys().any(|k| k.starts_with("effects/")) { + self.not_fixable(" (bound to a style or variable)", "bound"); + } + } + if colored { + self.push( + "color.colored-shadow", + n.id, + path, + "Shadow carries a visible hue; shadows read as depth only when neutral".into(), + Some(json!({"neutralShadow": true})), + ); + if n.styles.effect.is_some() || n.bound.keys().any(|k| k.starts_with("effects/")) { + self.not_fixable(" (bound to a style or variable)", "bound"); + } + } + } + + fn check_text(&mut self, n: &Node, t: &TextData, path: &str) { + let chars = t.characters.trim(); + let s = &t.style; + let size = if s.font_size.is_finite() { s.font_size } else { 0.0 }; + let weight = s.weight(); + // A text style (whole layer or a run) or a variable owns the type; changing it here would + // drift from the style the user chose. + let styled = n.styles.text.is_some() + || s.style_id.is_some() + || t.runs.iter().any(|r| r.style.style_id.is_some()) + || ["fontSize", "fontStyle", "fontWeight", "letterSpacing"].iter().any(|k| n.bound.contains_key(*k)); + if !chars.is_empty() { + self.text_nodes += 1; + count_size(&mut self.sizes, size); + self.families.insert(family_key(&s.font_family)); + } + for run in &t.runs { + if run.end > run.start { + count_size(&mut self.sizes, run.style.font_size); + self.families.insert(family_key(&run.style.font_family)); + } + } + + if size > 0.0 && size < 11.0 && !chars.is_empty() { + self.push_details( + "type.too-small", + n.id, + path, + format!("Body text at {size}px is below the 11px floor"), + None, + Some(json!({"size": size})), + ); + } + if size >= 20.0 && weight > 600 { + self.push_details( + "type.weight", + n.id, + path, + format!("Heading weight {weight} is heavier than a heading needs"), + Some(json!({"fontWeight": 600})), + Some(json!({"weight": weight})), + ); + if styled { + self.not_fixable(" (bound to a style or variable)", "bound"); + } + } + if s.italic() && !chars.is_empty() { + self.push("type.italic", n.id, path, "Interface text is italic".into(), Some(json!({"italic": false}))); + if styled { + self.not_fixable(" (bound to a style or variable)", "bound"); + } + } + let tracking = s.letter_spacing.resolve(size); + if tracking.is_finite() && tracking < -0.01 && size > 0.0 && size < 24.0 { + self.push_details( + "type.negative-tracking", + n.id, + path, + format!("Small text is tracked {tracking}px tighter; use size or weight instead"), + Some(json!({"letterSpacing": 0})), + Some(json!({"tracking": tracking})), + ); + if styled { + self.not_fixable(" (bound to a style or variable)", "bound"); + } + } + + // A run with its own fill makes the text more than one colour; the base fill is not the + // whole story, so the contrast check skips rather than judging the wrong pair. + let mixed_fills = t.runs.iter().any(|r| r.style.fills.is_some()); + self.check_contrast(n, t, path, size, weight, mixed_fills); + + if contains_emoji(&t.characters) || contains_emoji(&n.name) { + self.push("icon.emoji", n.id, path, "Emoji in interface text or a layer name; use a line icon set instead".into(), None); + } + if t.characters.contains('!') || t.characters.contains('!') { + self.push("copy.exclamation", n.id, path, "Copy uses an exclamation mark".into(), Some(json!({"removeExclamations": true}))); + } + if short_label_ends_with_period(chars) { + self.push("copy.trailing-period", n.id, path, "Short label ends with a period".into(), Some(json!({"removeTrailingPeriod": true}))); + } + if has_hype(chars) { + self.push("copy.hype", n.id, path, "Copy uses a hype word (\"AI-powered\", \"supercharge\"…)".into(), None); + } + + // A fixed-width text box whose stored height is shorter than the laid-out text clips or + // overlaps what follows it. Truncating boxes and auto-width boxes are intentional. + if !chars.is_empty() + && n.width > 0.0 + && self.measured < MAX_TEXT_MEASURED + && matches!(t.auto_resize, TextAutoResize::None | TextAutoResize::Height) + { + self.measured += 1; + let needed = figcraft_text::layout_cached(t, Some(n.width), None).height; + if needed.is_finite() && needed > n.height + 1.0 { + self.push_details( + "layout.text-overflow", + n.id, + path, + format!("Text needs {needed:.0}px of height but its box is {:.0}px; it clips or overlaps", n.height), + None, + Some(json!({"needed": needed, "height": n.height})), + ); + } + } + } + + /// WCAG contrast for single-colour text, in the run's variable modes when any were given. + fn check_contrast(&mut self, n: &Node, t: &TextData, path: &str, size: f64, weight: u16, mixed_fills: bool) { + if mixed_fills { + return; + } + let (fg, bg) = if self.settings.modes.is_empty() { + (text_color(n, t), backdrop(self.doc, n)) + } else { + (text_color_in(self.doc, n, t, &self.settings.modes), backdrop_in(self.doc, n, Some(&self.settings.modes))) + }; + let (Some(fg), Some(bg)) = (fg, bg) else { return }; + let ratio = fg.contrast(bg); + if !ratio.is_finite() { + return; + } + let large = size >= 24.0 || (size >= 18.0 && weight >= 700); + let need = if large { 3.0 } else { 4.5 }; + if ratio >= need { + return; + } + let mode_note = if self.settings.mode_labels.is_empty() { String::new() } else { format!(" in {}", self.settings.mode_note()) }; + let mut details = json!({"ratio": ratio, "needed": need, "foreground": fg.to_hex(), "background": bg.to_hex()}); + if !self.settings.mode_labels.is_empty() + && let Some(o) = details.as_object_mut() + { + o.insert("modes".into(), json!(self.settings.mode_labels)); + } + self.push_details( + "color.contrast", + n.id, + path, + format!("Contrast {ratio:.2}:1, needs {need:.2}:1 ({} on {}){mode_note}", fg.to_hex(), bg.to_hex()), + None, + Some(details), + ); + if !self.settings.modes.is_empty() { + self.not_fixable(" (read in the chosen variable modes)", "modes"); + } else if n.styles.fill.is_some() || n.bound.keys().any(|k| k.starts_with("fills/")) { + self.not_fixable(" (bound to a style or variable)", "bound"); + } + } + + fn check_tokens(&mut self, n: &Node, path: &str) { + if self.tokens.is_empty() || !n.var_modes.is_empty() { + return; + } + // Colours: a solid paint that is exactly a colour variable's default value, unbound and + // not styled, is a hardcoded token. + let mut hits: Vec<(&str, String, String)> = Vec::new(); + let is_text = matches!(&n.kind, NodeKind::Text(_)); + let fills: &[Paint] = match &n.kind { + NodeKind::Text(t) => t.style.fills.as_deref().unwrap_or(&n.fills), + _ => &n.fills, + }; + if n.styles.fill.is_none() { + for (i, p) in fills.iter().enumerate() { + if !p.visible || paint_binding_key(n, true, i).is_some() { + continue; + } + let Some(c) = p.solid_color() else { continue }; + if let Some(tok) = self.tokens.color(c) { + hits.push((if is_text { "text" } else { "fill" }, c.to_hex(), tok.name.clone())); + } + } + } + if n.styles.stroke.is_none() { + for (i, p) in n.strokes.iter().enumerate() { + if !p.visible || paint_binding_key(n, false, i).is_some() { + continue; + } + let Some(c) = p.solid_color() else { continue }; + if let Some(tok) = self.tokens.color(c) { + hits.push(("stroke", c.to_hex(), tok.name.clone())); + } + } + } + if !hits.is_empty() { + hits.sort(); + hits.dedup(); + let shown: Vec = hits.iter().map(|(kind, hex, token)| format!("{kind} #{hex} = \"{token}\"")).collect(); + let details: Vec = + hits.iter().map(|(kind, hex, token)| json!({"kind": kind, "color": format!("#{hex}"), "token": token})).collect(); + self.push_details( + "token.hardcoded-color", + n.id, + path, + format!("Matches a variable but is not bound: {}", shown.join(", ")), + None, + Some(json!({"hits": details})), + ); + } + + // Numbers: spacing, radii, a text size and opacity. + let mut hits: Vec<(String, f64, String)> = Vec::new(); + { + let mut check = |value: f64, field: &str| { + if value.is_finite() + && value > 0.01 + && let Some(tok) = self.tokens.number(value) + { + hits.push((field.to_string(), value, tok.name.clone())); + } + }; + if let Some(al) = &n.layout { + if al.mode != LayoutMode::Grid && !n.bound.contains_key("gap") { + check(al.gap, "gap"); + } + if al.wrap && !n.bound.contains_key("crossGap") { + check(al.cross_gap, "crossGap"); + } + let keys = ["paddingTop", "paddingRight", "paddingBottom", "paddingLeft"]; + for (i, key) in keys.iter().enumerate() { + if !n.bound.contains_key(*key) + && let Some(v) = al.padding.get(i).copied() + { + check(v, key); + } + } + } + if !["cornerRadius", "topLeftRadius", "topRightRadius", "bottomRightRadius", "bottomLeftRadius"].iter().any(|k| n.bound.contains_key(*k)) + { + for r in n.corners.radii { + check(r, "cornerRadius"); + } + } + if let NodeKind::Text(t) = &n.kind { + let styled = n.styles.text.is_some() || t.style.style_id.is_some() || t.runs.iter().any(|r| r.style.style_id.is_some()); + if !styled && !n.bound.contains_key("fontSize") { + check(t.style.font_size, "fontSize"); + } + } + if n.opacity < 0.99 && !n.bound.contains_key("opacity") { + check(f64::from(n.opacity), "opacity"); + } + } + if !hits.is_empty() { + hits.sort_by(|a, b| a.0.cmp(&b.0).then_with(|| a.1.total_cmp(&b.1))); + hits.dedup_by(|a, b| a.0 == b.0 && (a.1 - b.1).abs() <= 1e-6); + let shown: Vec = hits.iter().map(|(field, value, token)| format!("{field} {value} = \"{token}\"")).collect(); + let details: Vec = hits.iter().map(|(field, value, token)| json!({"field": field, "value": value, "token": token})).collect(); + self.push_details( + "token.hardcoded-number", + n.id, + path, + format!("Matches a variable but is not bound: {}", shown.join(", ")), + None, + Some(json!({"hits": details})), + ); + } + } + + fn scope_rules(&mut self, anchor: Option, path: &str, scope: &str) { + let Some(node) = anchor else { return }; + if self.text_nodes >= 8 { + if self.sizes.len() > 5 { + let sizes: Vec = self.sizes.iter().map(|v| trim_half(*v)).collect(); + self.push_details( + "type.sizes", + node, + path, + format!("{} font sizes in this {scope}: {}", sizes.len(), sizes.join(", ")), + None, + Some(json!({"sizes": sizes, "count": sizes.len()})), + ); + } + if self.families.len() > 2 { + let families: Vec<&str> = self.families.iter().map(String::as_str).collect(); + self.push_details( + "type.families", + node, + path, + format!("{} font families in this {scope}: {}", families.len(), families.join(", ")), + None, + Some(json!({"families": families, "count": families.len()})), + ); + } + } + if self.visited >= 20 && self.shadowed > 5 && self.shadowed * 5 > self.visited { + self.push_details( + "detail.shadow-count", + node, + path, + format!("{} of {} layers carry a shadow or blur", self.shadowed, self.visited), + None, + Some(json!({"shadowed": self.shadowed, "nodes": self.visited})), + ); + } + if self.accents.len() > 2 { + let colors: Vec = self.accents.keys().take(6).map(|c| format!("#{:02X}{:02X}{:02X}", c[0], c[1], c[2])).collect(); + self.push_details( + "color.accents", + node, + path, + format!("{} accent colours in this {scope}: {} (keep two)", self.accents.len(), colors.join(", ")), + None, + Some(json!({"count": self.accents.len(), "colors": colors})), + ); + } + } + + fn push(&mut self, id: &'static str, node: NodeId, path: &str, message: String, suggestion: Option) { + self.push_details(id, node, path, message, suggestion, None); + } + + /// A finding whose message has values, with those values in `details` too. + fn push_details(&mut self, id: &'static str, node: NodeId, path: &str, message: String, suggestion: Option, details: Option) { + let Some(r) = rule(id) else { return }; + self.findings.push(Finding { + rule: r.id, + severity: r.severity, + node, + path: path.to_string(), + message, + fixable: r.fixable, + suggestion, + details, + reason: None, + }); + } + + /// Mark the finding just pushed as not auto-fixable, with the reason in its message and as a + /// machine code for the window (`"bound"`: owned by a variable or style; `"modes"`: read in + /// the chosen variable modes). + fn not_fixable(&mut self, note: &str, reason: &'static str) { + if let Some(f) = self.findings.last_mut() { + f.fixable = false; + f.message.push_str(note); + f.reason = Some(reason); + } + } +} + +/// The layer's name, or a stand-in when it has none; long names are cut so paths stay readable. +fn label(n: &Node) -> String { + let name = n.name.trim(); + if name.is_empty() { + return format!("{} {}", n.kind.type_name(), n.id.0); + } + let mut chars = name.chars(); + let short: String = chars.by_ref().take(60).collect(); + if chars.next().is_some() { format!("{short}…") } else { short } +} + +/// A colour that reads as an accent: enough chroma to be a hue rather than a neutral, and neither +/// near-black nor near-white. +fn accent_rgba(c: Color) -> Option<[u8; 4]> { + if !c.a.is_finite() || c.a < 0.5 { + return None; + } + let max = c.r.max(c.g).max(c.b); + let min = c.r.min(c.g).min(c.b); + (max - min >= 0.18 && max >= 0.2 && min <= 0.88).then(|| c.to_rgba8()) +} + +fn has_stroke(n: &Node) -> bool { + n.stroke.weight > 0.01 || n.stroke.sides.is_some_and(|s| s.iter().any(|w| *w > 0.01)) +} + +/// Whether a stroke reads as a strong border rather than a hairline: its colour blended over what +/// is behind it, compared with that backdrop. With no known backdrop, the paint's alpha decides. +fn border_is_strong(doc: &Document, n: &Node) -> bool { + let Some(p) = n.strokes.iter().rev().find(|p| p.visible) else { return false }; + if p.blend != BlendMode::Normal { + return false; + } + let Some(c) = p.solid_color() else { return p.opacity > 0.12 }; + // An inside stroke sits on the layer's own fill; centre and outside strokes sit on what is + // behind it. Default strokes are inside, so a border on a dark panel is judged on that panel. + let bg = if n.stroke.align == StrokeAlign::Inside { solid_fill(n).or_else(|| backdrop(doc, n)) } else { backdrop(doc, n) }; + match bg { + Some(bg) => blend(c, bg).contrast(bg) > 1.5, + None => c.a > 0.12, + } +} + +fn blend(fg: Color, bg: Color) -> Color { + let a = fg.a; + Color::new(fg.r * a + bg.r * (1.0 - a), fg.g * a + bg.g * (1.0 - a), fg.b * a + bg.b * (1.0 - a), 1.0) +} + +fn chroma(c: Color) -> f32 { + let [r, g, b, _] = c.to_rgba8(); + let (max, min) = (r.max(g).max(b) as f32, r.min(g).min(b) as f32); + (max - min) / 255.0 +} + +/// A shadow with no offset and a large blur: it lights the layer instead of giving it depth. +pub(crate) fn is_glow(e: &Effect) -> bool { + if !e.visible { + return false; + } + match &e.kind { + EffectKind::DropShadow(s) | EffectKind::InnerShadow(s) => { + s.offset.0.abs() <= 1.0 && s.offset.1.abs() <= 1.0 && s.radius >= 8.0 && s.color.a > 0.05 + } + _ => false, + } +} + +/// A shadow whose colour carries a visible hue. +pub(crate) fn is_colored_shadow(s: &Shadow) -> bool { + chroma(s.color) > 0.12 && s.color.a > 0.05 +} + +/// The topmost visible solid paint, if it is opaque enough to know what shows through it. +fn solid_fill(n: &Node) -> Option { + let p = n.fills.iter().rev().find(|p| p.visible)?; + // A blend mode changes what the colour looks like over what is behind it; do not guess. + if !matches!(n.blend, BlendMode::Normal | BlendMode::PassThrough) || p.blend != BlendMode::Normal || p.opacity < 0.95 { + return None; + } + match &p.kind { + PaintKind::Solid { color } if color.a >= 0.95 => Some(*color), + _ => None, + } +} + +/// The colour a text layer's characters show in, when it is a single opaque solid paint. +pub(crate) fn text_color(n: &Node, t: &TextData) -> Option { + let paints = t.style.fills.as_deref().unwrap_or(&n.fills); + let p = paints.iter().rev().find(|p| p.visible)?; + if p.blend != BlendMode::Normal { + return None; + } + if p.opacity < 0.95 { + return None; + } + match &p.kind { + PaintKind::Solid { color } if color.a >= 0.95 => Some(*color), + _ => None, + } +} + +/// `base`, resolved in the layer's variable modes (with `overrides` on top) when the paint's colour +/// is bound to a colour variable. +fn bound_color(doc: &Document, n: &Node, fills: bool, index: usize, base: Color, overrides: &BTreeMap) -> Color { + let Some(key) = paint_binding_key(n, fills, index) else { return base }; + let Some(id) = n.bound.get(key) else { return base }; + let mut modes = doc.modes_for(n.id); + modes.extend(overrides.iter().map(|(c, m)| (c.clone(), m.clone()))); + match doc.variables.resolve(id, &modes) { + Some(VariableValue::Color(c)) => c, + _ => base, + } +} + +/// [`solid_fill`], with bound colours resolved in `overrides` (the layer's own modes first). +fn solid_fill_in(doc: &Document, n: &Node, overrides: &BTreeMap) -> Option { + let index = n.fills.iter().rposition(|p| p.visible)?; + let p = n.fills.get(index)?; + if !matches!(n.blend, BlendMode::Normal | BlendMode::PassThrough) || p.blend != BlendMode::Normal || p.opacity < 0.95 { + return None; + } + let PaintKind::Solid { color } = &p.kind else { return None }; + if color.a < 0.95 { + return None; + } + let color = bound_color(doc, n, true, index, *color, overrides); + (color.a >= 0.95).then_some(color) +} + +/// [`text_color`], with bound colours resolved in `overrides`. +fn text_color_in(doc: &Document, n: &Node, t: &TextData, overrides: &BTreeMap) -> Option { + let paints = t.style.fills.as_deref().unwrap_or(&n.fills); + let (index, p) = paints.iter().enumerate().rev().find(|(_, p)| p.visible)?; + if p.blend != BlendMode::Normal || p.opacity < 0.95 { + return None; + } + let PaintKind::Solid { color } = &p.kind else { return None }; + if color.a < 0.95 { + return None; + } + let color = bound_color(doc, n, true, index, *color, overrides); + (color.a >= 0.95).then_some(color) +} + +/// What lies directly behind a layer, or why it cannot be sampled. +enum Behind { + Known(Color), + /// A gradient, image, translucency or partial cover: the audit does not guess. + Unknown, +} + +/// The first opaque solid behind a layer. At each ancestor level, look at the siblings painted +/// below it (z-order, `reverse_z` respected) for the topmost one that covers it, then at that +/// ancestor's own fill. The old version only walked ancestors, so white text on a dark rectangle +/// sibling was compared with the page behind both and reported as unreadable. +pub(crate) fn backdrop(doc: &Document, n: &Node) -> Option { + backdrop_in(doc, n, None) +} + +/// [`backdrop`], resolving bound colours in `overrides` when given. +fn backdrop_in(doc: &Document, n: &Node, overrides: Option<&BTreeMap>) -> Option { + let target = doc.world_bounds(n.id)?; + let mut current = n.id; + for _ in 0..256 { + let node = doc.node(current)?; + let parent_id = node.parent?; + let parent = doc.node(parent_id)?; + if parent.opacity < 0.99 { + return None; + } + match sibling_behind(doc, parent, current, target, overrides) { + Some(Behind::Known(c)) => return Some(c), + Some(Behind::Unknown) => return None, + None => {} + } + if let NodeKind::Page { background, .. } = &parent.kind { + return if background.a >= 0.95 { Some(*background) } else { None }; + } + if parent.fills.iter().any(|p| p.visible) { + return match overrides { + Some(modes) => solid_fill_in(doc, parent, modes), + None => solid_fill(parent), + }; + } + current = parent_id; + } + None +} + +/// The topmost sibling painted below `current` that covers `target`, if it has visible paint. +fn sibling_behind( + doc: &Document, + parent: &Node, + current: NodeId, + target: figcraft_geom::Rect, + overrides: Option<&BTreeMap>, +) -> Option { + let index = parent.children.iter().position(|c| *c == current)?; + let reverse = parent.layout.as_ref().is_some_and(|l| l.reverse_z); + // Last child on top: siblings before `index` are below it. First on top: siblings after are. + let total = if reverse { parent.children.len().saturating_sub(index + 1) } else { index }; + let order: Box> = if reverse { Box::new(index + 1..parent.children.len()) } else { Box::new((0..index).rev()) }; + for i in order.take(MAX_BACKDROP_SCAN) { + let Some(sibling) = parent.children.get(i).and_then(|id| doc.node(*id)) else { continue }; + if let Some(behind) = paint_behind(doc, sibling, target, 1, overrides) { + return Some(behind); + } + } + // Past the cap the topmost paint is unknown, not the page behind the container. + (total > MAX_BACKDROP_SCAN).then_some(Behind::Unknown) +} + +/// The topmost paint a layer (and what it contains) puts under `target`: its children first (they +/// paint above its fill), then its own fill. Text and lines paint glyphs or a stroke, not a +/// background; a container without a fill is entered so a background rectangle inside a group is +/// found too. Clipped children outside the frame are left out. +fn paint_behind( + doc: &Document, + node: &Node, + target: figcraft_geom::Rect, + depth: usize, + overrides: Option<&BTreeMap>, +) -> Option { + if depth > 64 || !node.visible { + return None; + } + let bounds = doc.world_bounds(node.id); + let clipped_away = node.clip && bounds.is_some_and(|b| !contains(b, target)); + if !clipped_away { + let reverse = node.layout.as_ref().is_some_and(|l| l.reverse_z); + let order: Box> = + if reverse { Box::new(0..node.children.len()) } else { Box::new((0..node.children.len()).rev()) }; + for i in order.take(MAX_BACKDROP_SCAN) { + let Some(child) = node.children.get(i).and_then(|id| doc.node(*id)) else { continue }; + if let Some(behind) = paint_behind(doc, child, target, depth + 1, overrides) { + return Some(behind); + } + } + if node.children.len() > MAX_BACKDROP_SCAN { + return Some(Behind::Unknown); + } + } + if matches!(&node.kind, NodeKind::Text(_) | NodeKind::Line) || !node.fills.iter().any(|p| p.visible) { + return None; + } + let b = bounds?; + if !overlaps(b, target) { + return None; + } + if !contains(b, target) || node.opacity < 0.99 { + return Some(Behind::Unknown); + } + let color = match overrides { + Some(modes) => solid_fill_in(doc, node, modes), + None => solid_fill(node), + }; + Some(match color { + Some(c) => Behind::Known(c), + None => Behind::Unknown, + }) +} + +fn overlaps(b: figcraft_geom::Rect, target: figcraft_geom::Rect) -> bool { + b.x0 < target.x1 && target.x0 < b.x1 && b.y0 < target.y1 && target.y0 < b.y1 +} + +fn contains(b: figcraft_geom::Rect, target: figcraft_geom::Rect) -> bool { + b.x0 <= target.x0 && b.y0 <= target.y0 && b.x1 >= target.x1 && b.y1 >= target.y1 +} + +fn count_size(sizes: &mut BTreeSet, size: f64) { + if size.is_finite() && size > 0.0 { + sizes.insert((size * 2.0).round() as i64); + } +} + +fn trim_half(v: i64) -> String { + let n = v as f64 / 2.0; + if (n - n.round()).abs() < 0.01 { format!("{}", n.round() as i64) } else { format!("{n}") } +} + +fn family_key(family: &str) -> String { + let f = family.trim().to_ascii_lowercase(); + if f.is_empty() { "inter".into() } else { f } +} + +fn contains_emoji(s: &str) -> bool { + s.chars().any(|c| { + let u = c as u32; + (0x1F000..=0x1FAFF).contains(&u) || (0x2600..=0x27BF).contains(&u) || matches!(u, 0x2B50 | 0x2B55 | 0x203C | 0x2049) + }) +} + +fn short_label_ends_with_period(s: &str) -> bool { + let s = s.trim_end(); + let body = s.trim_end_matches(['.', '。']).trim_end(); + if body == s || body.is_empty() { + return false; + } + !body.contains('\n') && !body.contains(". ") && body.chars().count() <= 24 +} + +fn has_hype(s: &str) -> bool { + let s = s.to_ascii_lowercase(); + ["ai-powered", "supercharge", "revolutioniz", "game-chang", "unleash the"].iter().any(|w| s.contains(w)) +} + +fn is_default_name(name: &str) -> bool { + let Some((word, number)) = name.trim().rsplit_once(' ') else { return false }; + const KINDS: [&str; 13] = + ["Frame", "Rectangle", "Ellipse", "Group", "Text", "Component", "Section", "Vector", "Line", "Polygon", "Star", "Slice", "Boolean"]; + KINDS.contains(&word) && !number.is_empty() && number.chars().all(|c| c.is_ascii_digit()) +} diff --git a/crates/engine/src/design/fix.rs b/crates/engine/src/design/fix.rs new file mode 100644 index 000000000..e6a5e6d7e --- /dev/null +++ b/crates/engine/src/design/fix.rs @@ -0,0 +1,319 @@ +//! `design.fix`: repair the findings `design.audit` marks fixable, as one undo step. +//! +//! Every repair is the safe, unambiguous one the audit already suggested: spacing snapped to the +//! 4px grid, radii to the scale, heavy headings to Semi Bold, italic and negative tracking removed, +//! glows taken out, shadow colours neutralised and strong borders thinned. Content rules (copy, +//! naming) and gradients are left alone: those need a decision, not arithmetic. + +use std::collections::{BTreeMap, BTreeSet}; + +use figcraft_color::{Color, PaintKind}; +use figcraft_doc::{DesignPreset, Document, EffectKind, LayoutMode, LetterSpacing, Node, NodeId, NodeKind, TextData, TextStyle}; +use serde_json::{Value, json}; + +use super::audit::{Report, Settings, backdrop, collect, is_colored_shadow, is_glow, text_color}; + +/// Fix what `roots` made fixable among `filter`'s rules. With `exact`, only findings on the roots +/// themselves are repaired, not findings on their descendants. `dry_run` reports the same counts +/// without changing the document. +pub(crate) fn run( + doc: &mut Document, + roots: &[NodeId], + anchor: Option, + anchor_path: &str, + scope: &str, + preset: Option, + filter: Option<&BTreeSet>, + exact: bool, + dry_run: bool, +) -> Value { + let settings = Settings::new(doc, preset); + let before = collect(doc, roots, anchor, anchor_path, scope, &settings); + let targets: Vec<(NodeId, &'static str)> = before + .findings + .iter() + .filter(|f| f.fixable && settings.enabled(f.rule)) + .filter(|f| filter.is_none_or(|set| set.contains(f.rule))) + .filter(|f| !exact || roots.contains(&f.node)) + .map(|f| (f.node, f.rule)) + .collect(); + let mut by_rule: BTreeMap<&'static str, usize> = BTreeMap::new(); + let mut changed = 0usize; + let mut skipped = 0usize; + if dry_run { + changed = targets.len(); + for (_, rule) in &targets { + *by_rule.entry(*rule).or_default() += 1; + } + } else { + for (id, rule) in &targets { + match apply(doc, *id, rule, &settings) { + Some(true) => { + changed += 1; + *by_rule.entry(*rule).or_default() += 1; + } + _ => skipped += 1, + } + } + } + let after = collect(doc, roots, anchor, anchor_path, scope, &settings); + json!({ + "scope": scope, + "dryRun": dry_run, + "changed": changed, + "skipped": skipped, + "byRule": by_rule, + "before": tally(&before, &settings), + "after": tally(&after, &settings), + }) +} + +fn tally(report: &Report, settings: &Settings) -> Value { + let shown: Vec<&super::audit::Finding> = report.findings.iter().filter(|f| settings.enabled(f.rule)).collect(); + let mut counts = [0usize; 3]; + for f in &shown { + counts[f.severity.index()] += 1; + } + let score = (100.0 - shown.iter().map(|f| f.severity.penalty()).sum::()).clamp(0.0, 100.0).round(); + json!({ + "score": score, + "counts": {"high": counts[2], "medium": counts[1], "low": counts[0]}, + "nodes": report.nodes, + "findings": shown.len(), + }) +} + +/// Apply one finding's repair. `None` when the layer is gone or the repair does not apply to it; +/// `Some(false)` when it applied to nothing (a no-op the caller counts as skipped). +fn apply(doc: &mut Document, id: NodeId, rule: &str, settings: &Settings) -> Option { + if rule == "color.contrast" { + return apply_contrast(doc, id); + } + let n = doc.node_mut(id)?; + match rule { + "spacing.off-grid" => apply_spacing(n, settings), + "radius.off-scale" => { + if ["cornerRadius", "topLeftRadius", "topRightRadius", "bottomRightRadius", "bottomLeftRadius"].iter().any(|k| n.bound.contains_key(*k)) { + return Some(false); + } + apply_radius(n, settings) + } + "type.weight" | "type.italic" | "type.negative-tracking" => { + if text_styled(n) || ["fontSize", "fontStyle", "fontWeight", "letterSpacing"].iter().any(|k| n.bound.contains_key(*k)) { + return Some(false); + } + match rule { + "type.weight" => apply_text(n, cap_weight), + "type.italic" => apply_text(n, unitalic), + _ => apply_text(n, zero_tracking), + } + } + "color.glow" | "color.colored-shadow" => { + if n.styles.effect.is_some() || n.bound.keys().any(|k| k.starts_with("effects/")) { + return Some(false); + } + if rule == "color.glow" { apply_glow(n) } else { apply_neutral_shadows(n) } + } + "color.border-opacity" => { + if n.styles.stroke.is_some() || n.bound.keys().any(|k| k.starts_with("strokes/")) { + return Some(false); + } + apply_border(n) + } + _ => Some(false), + } +} + +/// A text layer whose type comes from a text style (the whole layer or one run). +fn text_styled(n: &Node) -> bool { + match &n.kind { + NodeKind::Text(t) => n.styles.text.is_some() || t.style.style_id.is_some() || t.runs.iter().any(|r| r.style.style_id.is_some()), + _ => false, + } +} + +/// Darken (or lighten, on a dark backdrop) the text colour until it reaches the WCAG ratio. The +/// hue is kept as far as the blend allows; when even black or white cannot reach the ratio, the +/// text is left as it is and counted as skipped. +fn apply_contrast(doc: &mut Document, id: NodeId) -> Option { + let n = doc.node(id)?; + let NodeKind::Text(t) = &n.kind else { return Some(false) }; + if n.styles.fill.is_some() || n.bound.keys().any(|k| k.starts_with("fills/")) { + return Some(false); + } + let fg = text_color(n, t)?; + let bg = backdrop(doc, n)?; + let size = t.style.font_size; + let large = size >= 24.0 || (size >= 18.0 && t.style.weight() >= 700); + let need = if large { 3.0 } else { 4.5 }; + if fg.contrast(bg) >= need { + return Some(false); + } + let fixed = accessible(fg, bg, need); + if fixed.contrast(bg) < need { + return Some(false); + } + let n = doc.node_mut(id)?; + let NodeKind::Text(t) = &mut n.kind else { return Some(false) }; + let paints = match &mut t.style.fills { + Some(fills) => fills, + None => &mut n.fills, + }; + let paint = paints.iter_mut().rev().find(|p| p.visible && matches!(&p.kind, PaintKind::Solid { .. }))?; + paint.opacity = 1.0; + if let PaintKind::Solid { color } = &mut paint.kind { + *color = fixed.with_alpha(fg.a); + Some(true) + } else { + Some(false) + } +} + +/// The closest shade of `fg` towards black (light backdrop) or white (dark backdrop) that meets +/// `need` against `bg`, by bisection. +fn accessible(fg: Color, bg: Color, need: f32) -> Color { + let target = if bg.luminance() > 0.5 { Color::BLACK } else { Color::WHITE }; + let (mut lo, mut hi) = (0.0f32, 1.0f32); + let mut best = target; + for _ in 0..24 { + let t = (lo + hi) / 2.0; + let c = Color::new(fg.r + (target.r - fg.r) * t, fg.g + (target.g - fg.g) * t, fg.b + (target.b - fg.b) * t, 1.0); + if c.contrast(bg) >= need { + best = c; + hi = t; + } else { + lo = t; + } + } + best +} + +fn apply_spacing(n: &mut Node, settings: &Settings) -> Option { + // Any spacing binding owns the whole layout value: fixing one field next to a token would + // leave a mixed layout and is not what the audit promised. + if [ + "gap", + "columnGap", + "rowGap", + "crossGap", + "padding", + "paddingHorizontal", + "paddingVertical", + "paddingTop", + "paddingRight", + "paddingBottom", + "paddingLeft", + ] + .iter() + .any(|k| n.bound.contains_key(*k)) + { + return Some(false); + } + let al = n.layout.as_mut()?; + let mut changed = false; + if al.mode != LayoutMode::Grid { + let gap = settings.snap(al.gap); + if (gap - al.gap).abs() > 1e-6 { + al.gap = gap; + changed = true; + } + if al.wrap { + let cross = settings.snap(al.cross_gap); + if (cross - al.cross_gap).abs() > 1e-6 { + al.cross_gap = cross; + changed = true; + } + } + } + for side in &mut al.padding { + let value = settings.snap(*side); + if (value - *side).abs() > 1e-6 { + *side = value; + changed = true; + } + } + Some(changed) +} + +fn apply_radius(n: &mut Node, settings: &Settings) -> Option { + let (w, h) = (n.width, n.height); + let pill = w.min(h); + let mut changed = false; + for r in &mut n.corners.radii { + if *r > 0.01 && !settings.radius_ok(*r, w, h) { + *r = if pill > 0.0 && (*r - pill / 2.0).abs() <= 1.0 { pill / 2.0 } else { settings.snap_radius(*r) }; + changed = true; + } + } + Some(changed) +} + +/// Run `f` over a text layer's base style and its runs; true when any style changed. +fn apply_text(n: &mut Node, f: fn(&mut TextStyle) -> bool) -> Option { + let NodeKind::Text(t) = &mut n.kind else { return Some(false) }; + let TextData { style, runs, .. } = t; + let mut changed = f(style); + for run in runs { + changed |= f(&mut run.style); + } + Some(changed) +} + +fn cap_weight(s: &mut TextStyle) -> bool { + if s.font_size >= 20.0 && s.weight() > 600 { + s.set_font_style("Semi Bold"); + true + } else { + false + } +} + +fn unitalic(s: &mut TextStyle) -> bool { + if !s.italic() { + return false; + } + let words: Vec<&str> = s.font_style.split_whitespace().filter(|w| !w.eq_ignore_ascii_case("italic")).collect(); + let name = if words.is_empty() { "Regular".to_string() } else { words.join(" ") }; + s.set_font_style(name); + true +} + +fn zero_tracking(s: &mut TextStyle) -> bool { + let px = s.letter_spacing.resolve(s.font_size); + if s.font_size > 0.0 && s.font_size < 24.0 && px.is_finite() && px < -0.01 { + s.letter_spacing = LetterSpacing::Percent(0.0); + true + } else { + false + } +} + +fn apply_glow(n: &mut Node) -> Option { + let before = n.effects.len(); + n.effects.retain(|e| !is_glow(e)); + Some(n.effects.len() != before) +} + +fn apply_neutral_shadows(n: &mut Node) -> Option { + let mut changed = false; + for e in &mut n.effects { + if let EffectKind::DropShadow(s) | EffectKind::InnerShadow(s) = &mut e.kind + && is_colored_shadow(s) + { + s.color = Color::new(0.0, 0.0, 0.0, s.color.a); + changed = true; + } + } + Some(changed) +} + +fn apply_border(n: &mut Node) -> Option { + let mut changed = false; + for p in &mut n.strokes { + if p.visible && p.opacity > 0.08 { + p.opacity = 0.08; + changed = true; + } + } + Some(changed) +} diff --git a/crates/engine/src/design/mod.rs b/crates/engine/src/design/mod.rs new file mode 100644 index 000000000..7e8229323 --- /dev/null +++ b/crates/engine/src/design/mod.rs @@ -0,0 +1,378 @@ +//! Design review: deterministic checks for the usual AI-generated interface tells. +//! +//! `design.audit` reads a selection, a page or the whole document and reports what a designer +//! would fix first — spacing off the 4px grid, radii outside the scale, too many type sizes, +//! gradient text, glows, low-contrast text, emoji labels. It changes nothing. `design.fix` (the +//! planned follow-up) repairs the findings marked `fixable`. +//! +//! The rules are our own reading of the public "unslop" checklist (CC BY 4.0, heydamir/unslop): +//! only the ideas, no text or assets from it. + +mod audit; +mod fix; +mod rules; + +#[cfg(test)] +mod tests; + +use std::collections::{BTreeMap, BTreeSet}; + +use figcraft_doc::{CollectionId, DesignPreset, DesignReview, Document, GRID_MAX, GRID_MIN, MAX_BRAND_COLORS, MAX_RADII, ModeId, NodeId}; +use serde_json::{Value, json}; + +use crate::cmd::CommandSpec; +use crate::params; +use crate::{EngineError, Result, Session, bad, spec}; +use rules::{RULES, Severity, presets_of, rule}; + +pub fn specs() -> Vec { + vec![ + spec!( + "design.audit", + "Check design", + "{scope?: selection|page|document (default: selection when something is selected, else page), ids?: [layer ids] (instead of scope), rules?: [rule ids], minSeverity?: low|medium|high (default low), preset?: recommended|strict|accessibility (default: the file's), modes?: {collection: mode} (resolve bound colours in these variable modes; the contrast check uses them)} → {preset, grid, modes?, scope, score, counts: {high, medium, low}, byRule: {rule: count}, nodes, findings: [{rule, severity, node, path, message, fixable, suggestion?}], truncated} reads the design and reports the AI-slop tells; changes nothing", + false, + audit_cmd + ), + spec!( + "design.fix", + "Fix design", + "{scope?: selection|page|document (default: selection when something is selected, else page), ids?: [layer ids] (instead of scope), rules?: [rule ids], preset?: recommended|strict|accessibility (default: the file's), exact?: bool (with ids: repair only findings on those layers, not their descendants), dryRun?: bool (default false)} → {scope, dryRun, changed, skipped, byRule, before: {score, counts, nodes, findings}, after: {score, counts, nodes, findings}} repairs the findings marked fixable in one undo step; content, naming and gradients are left alone", + true, + fix_cmd + ), + spec!( + "design.assert", + "Assert design", + "{scope?: selection|page|document (default: selection when something is selected, else page), ids?: [layer ids] (instead of scope), rules?: [rule ids], preset?: recommended|strict|accessibility (default: the file's), modes?: {collection: mode} (resolve bound colours in these variable modes), failOn?: low|medium|high (default high), minScore?: 0-100 (default 0)} → {ok: true, score, counts} fails with an error when a finding at or above failOn exists or the score is below minScore; read-only, for CI", + false, + assert_cmd + ), + spec!( + "design.configure", + "Configure design review", + "{preset?: recommended|strict|accessibility, grid?: 1-64 (px, default 4), radii?: [px] (empty: the grid scale and a pill), brand?: [colour] (accent colours the file owns), disabled?: [rule ids] (rules off in this file), reset?: bool} → {preset, grid, radii, brand, disabled} changes the file's design review settings in one undo step; audit, fix and assert use them from then on", + true, + configure_cmd + ), + spec!( + "design.rules", + "List design rules", + "{} → {rules: [{id, severity, fixable, description, presets}], presets: [{id, description}]}", + false, + |_, _| Ok(json!({ + "rules": RULES.iter().map(|r| json!({ + "id": r.id, + "severity": r.severity.id(), + "fixable": r.fixable, + "description": r.description, + "presets": presets_of(r.id), + })).collect::>(), + "presets": DesignPreset::ALL.iter().map(|p| json!({ + "id": p.id(), + "description": preset_description(*p), + })).collect::>(), + })) + ), + ] +} + +fn audit_cmd(s: &mut Session, p: &Value) -> Result { + let (label, roots, anchor, path) = scope_of(s, "design.audit", p)?; + let min = severity_arg("design.audit", p)?; + let filter = filter_arg("design.audit", p)?; + let preset = preset_arg("design.audit", p)?; + let modes = modes_arg("design.audit", p, s.doc()?)?; + Ok(audit::run(s.doc()?, &roots, &label, anchor, &path, min, filter.as_ref(), preset, modes)) +} + +fn fix_cmd(s: &mut Session, p: &Value) -> Result { + let (label, roots, anchor, path) = scope_of(s, "design.fix", p)?; + let filter = filter_arg("design.fix", p)?; + let preset = preset_arg("design.fix", p)?; + let exact = params::boolean(p, "exact").unwrap_or(false); + let dry = params::boolean(p, "dryRun").unwrap_or(false); + Ok(fix::run(s.doc_mut()?, &roots, anchor, &path, &label, preset, filter.as_ref(), exact, dry)) +} + +/// `design.assert`: a read-only gate for CI. Returns the score when the design passes; an error +/// that names the counts when it does not. +fn assert_cmd(s: &mut Session, p: &Value) -> Result { + let (label, roots, anchor, path) = scope_of(s, "design.assert", p)?; + let filter = filter_arg("design.assert", p)?; + let fail_on = severity_named("design.assert", p, "failOn", Severity::High)?; + let preset = preset_arg("design.assert", p)?; + let modes = modes_arg("design.assert", p, s.doc()?)?; + let min_score = match params::get(p, "minScore") { + None => 0.0, + Some(v) => match params::f64_of(v) { + Some(v) if (0.0..=100.0).contains(&v) => v, + _ => return Err(bad("design.assert", "`minScore` must be a number between 0 and 100")), + }, + }; + // The score covers the whole review (as the window shows it); only findings at or above + // `failOn` fail the gate. + let report = audit::run(s.doc()?, &roots, &label, anchor, &path, Severity::Low, filter.as_ref(), preset, modes); + let failing: Vec<&Value> = report["findings"] + .as_array() + .map(|v| v.iter().filter(|f| f["severity"].as_str().and_then(Severity::from_id).is_some_and(|s| s >= fail_on)).collect()) + .unwrap_or_default(); + let score = report["score"].as_f64().unwrap_or(0.0); + if !failing.is_empty() || score < min_score { + let mut by_rule: std::collections::BTreeMap<&str, usize> = std::collections::BTreeMap::new(); + for f in &failing { + if let Some(rule) = f["rule"].as_str() { + *by_rule.entry(rule).or_default() += 1; + } + } + let rules: Vec = by_rule.iter().take(4).map(|(rule, count)| format!("{rule} ×{count}")).collect(); + let detail = if rules.is_empty() { String::new() } else { format!(" ({})", rules.join(", ")) }; + return Err(EngineError::Other(format!( + "design review failed: score {score:.0}, {} finding(s) at {} or above{detail}", + failing.len(), + fail_on.id() + ))); + } + Ok(json!({"ok": true, "score": score, "counts": report["counts"]})) +} + +fn severity_named(cmd: &str, p: &Value, key: &str, default: Severity) -> Result { + match params::string(p, key).map(|s| s.trim().to_ascii_lowercase()).filter(|s| !s.is_empty()) { + None => Ok(default), + Some(s) => Severity::from_id(&s).ok_or_else(|| bad(cmd, format!("`{key}` must be low, medium or high, not `{s}`"))), + } +} + +fn preset_arg(cmd: &str, p: &Value) -> Result> { + match params::string(p, "preset").map(|s| s.trim().to_ascii_lowercase()).filter(|s| !s.is_empty()) { + None => Ok(None), + Some(s) => { + DesignPreset::from_id(&s).map(Some).ok_or_else(|| bad(cmd, format!("`preset` must be recommended, strict or accessibility, not `{s}`"))) + } + } +} + +fn preset_description(preset: DesignPreset) -> &'static str { + match preset { + DesignPreset::Recommended => "The usual AI-generated tells", + DesignPreset::Strict => "Recommended plus accent colours and frames without auto layout", + DesignPreset::Accessibility => "Contrast, the type floor, gradient text and clipped text only", + } +} + +/// The variable modes a run resolves colours in: `{collection: mode}`, by id or by name. +fn modes_arg(cmd: &str, p: &Value, doc: &Document) -> Result> { + let Some(v) = params::get(p, "modes") else { return Ok(BTreeMap::new()) }; + let Value::Object(map) = v else { return Err(bad(cmd, "`modes` must be an object of collection → mode")) }; + if map.len() > 64 { + return Err(bad(cmd, "at most 64 collections in `modes`")); + } + let mut out = BTreeMap::new(); + for (collection_key, mode_value) in map { + let Some(mode_key) = mode_value.as_str().map(str::trim).filter(|s| !s.is_empty()) else { + return Err(bad(cmd, "`modes` values must be mode ids or names")); + }; + let Some(collection) = doc.variables.collection(collection_key.trim()) else { + return Err(bad(cmd, format!("unknown collection `{collection_key}`"))); + }; + let Some(mode) = collection.find_mode(mode_key) else { + return Err(bad(cmd, format!("unknown mode `{mode_key}` in `{}`", collection.name))); + }; + out.insert(collection.id.clone(), mode.id.clone()); + } + Ok(out) +} + +/// `design.configure`: change the file's design system and rules in one undo step. +fn configure_cmd(s: &mut Session, p: &Value) -> Result { + let mut config = if params::boolean(p, "reset").unwrap_or(false) { DesignReview::default() } else { s.doc()?.design_review.clone() }; + if let Some(preset) = preset_arg("design.configure", p)? { + config.preset = preset; + } + if let Some(v) = params::get(p, "grid") { + let grid = params::f64_of(v) + .filter(|g| g.is_finite() && (GRID_MIN..=GRID_MAX).contains(g)) + .ok_or_else(|| bad("design.configure", format!("`grid` must be a number from {GRID_MIN} to {GRID_MAX}")))?; + config.grid = grid; + } + if let Some(v) = params::get(p, "radii") { + let Value::Array(items) = v else { return Err(bad("design.configure", "`radii` must be an array of numbers")) }; + if items.len() > MAX_RADII { + return Err(bad("design.configure", format!("at most {MAX_RADII} radii"))); + } + let mut radii = Vec::new(); + for item in items { + let r = params::f64_of(item) + .filter(|r| r.is_finite() && (0.0..=999.0).contains(r)) + .ok_or_else(|| bad("design.configure", "each radius must be a number from 0 to 999"))?; + radii.push((r * 100.0).round() / 100.0); + } + radii.sort_by(f64::total_cmp); + radii.dedup_by(|a, b| (*a - *b).abs() <= 1e-6); + config.radii = radii; + } + if let Some(v) = params::get(p, "brand") { + let Value::Array(items) = v else { return Err(bad("design.configure", "`brand` must be an array of colours")) }; + if items.len() > MAX_BRAND_COLORS { + return Err(bad("design.configure", format!("at most {MAX_BRAND_COLORS} brand colours"))); + } + let mut brand = Vec::new(); + for item in items { + let color = params::color_of(item).ok_or_else(|| bad("design.configure", "each brand colour must be a colour"))?; + if color.a > 0.05 { + brand.push(color); + } + } + config.brand = brand; + } + if let Some(v) = params::get(p, "disabled") { + let Value::Array(items) = v else { return Err(bad("design.configure", "`disabled` must be an array of rule ids")) }; + let mut ids = BTreeSet::new(); + for item in items { + let Some(id) = item.as_str().map(str::trim) else { + return Err(bad("design.configure", "`disabled` must be an array of rule ids")); + }; + if rule(id).is_none() { + return Err(bad("design.configure", format!("unknown rule `{id}` (run design.rules for the list)"))); + } + ids.insert(id.to_string()); + } + config.disabled = ids.into_iter().collect(); + } + if s.doc()?.design_review == config { + return Ok(settings_json(&config)); + } + let doc = s.doc_mut()?; + doc.design_review = config; + Ok(settings_json(&doc.design_review)) +} + +fn settings_json(config: &DesignReview) -> Value { + let brand: Vec = config + .brand + .iter() + .map(|c| { + let rgba = c.to_rgba8(); + format!("#{:02X}{:02X}{:02X}", rgba[0], rgba[1], rgba[2]) + }) + .collect(); + json!({ + "preset": config.preset.id(), + "grid": config.grid(), + "radii": config.radii, + "brand": brand, + "disabled": config.disabled, + }) +} + +/// The layers a command works on, its scope label, the layer aggregate findings point at and that +/// layer's path. +fn scope_of(s: &Session, cmd: &str, p: &Value) -> Result<(String, Vec, Option, String)> { + let doc = s.doc()?; + // `ids` names the layers directly (the review window fixes only the findings the user kept). + if let Some(v) = params::get(p, "ids") { + let Value::Array(items) = v else { return Err(bad(cmd, "`ids` must be an array of layer ids")) }; + let mut ids = Vec::new(); + for item in items { + let Some(id) = params::id_of(item) else { return Err(bad(cmd, "`ids` must be an array of layer ids")) }; + ids.push(id); + } + let roots = top_most(doc, &ids); + let anchor = roots.first().copied(); + let path = anchor.map(|id| node_label(doc, id)).unwrap_or_default(); + return Ok(("selection".into(), roots, anchor, path)); + } + let scope = scope_arg(cmd, p)?; + let selection = s.selection(); + let page = s.page()?; + let (roots, label, anchor, path) = match scope.as_deref() { + None if selection.is_empty() => (vec![page], "page", Some(page), node_label(doc, page)), + None => selection_scope(doc, &selection), + Some("selection") => selection_scope(doc, &selection), + Some("page") => (vec![page], "page", Some(page), node_label(doc, page)), + Some("document") => { + let roots = doc.pages.clone(); + let anchor = roots.first().copied(); + let path = anchor.map(|id| node_label(doc, id)).unwrap_or_default(); + (roots, "document", anchor, path) + } + Some(other) => return Err(bad(cmd, format!("`scope` must be selection, page or document, not `{other}`"))), + }; + Ok((label.to_string(), roots, anchor, path)) +} + +fn selection_scope(doc: &Document, selection: &[NodeId]) -> (Vec, &'static str, Option, String) { + let roots = top_most(doc, selection); + let anchor = roots.first().copied(); + let path = anchor.map(|id| node_label(doc, id)).unwrap_or_default(); + (roots, "selection", anchor, path) +} + +fn scope_arg(cmd: &str, p: &Value) -> Result> { + let Some(v) = params::get(p, "scope") else { return Ok(None) }; + let Value::String(s) = v else { return Err(bad(cmd, "`scope` must be a string")) }; + let s = s.trim().to_ascii_lowercase(); + if s.is_empty() { + return Ok(None); + } + if matches!(s.as_str(), "selection" | "page" | "document") { + Ok(Some(s)) + } else { + Err(bad(cmd, format!("`scope` must be selection, page or document, not `{s}`"))) + } +} + +fn severity_arg(cmd: &str, p: &Value) -> Result { + match params::string(p, "minSeverity").map(|s| s.trim().to_ascii_lowercase()).filter(|s| !s.is_empty()) { + None => Ok(Severity::Low), + Some(s) => Severity::from_id(&s).ok_or_else(|| bad(cmd, format!("`minSeverity` must be low, medium or high, not `{s}`"))), + } +} + +fn filter_arg(cmd: &str, p: &Value) -> Result>> { + let Some(v) = params::get(p, "rules") else { return Ok(None) }; + let Value::Array(items) = v else { return Err(bad(cmd, "`rules` must be an array of rule ids")) }; + let mut set = BTreeSet::new(); + for item in items { + let Some(s) = item.as_str() else { return Err(bad(cmd, "`rules` must be an array of rule ids")) }; + let id = s.trim(); + if rule(id).is_none() { + return Err(bad(cmd, format!("unknown rule `{id}` (run design.rules for the list)"))); + } + set.insert(id.to_string()); + } + Ok(Some(set)) +} + +/// Selected layers without the ones whose ancestor is selected too: their subtrees would be +/// audited twice. +fn top_most(doc: &Document, ids: &[NodeId]) -> Vec { + let mut out: Vec = Vec::new(); + for id in ids { + if out.contains(id) { + continue; + } + let mut parent = doc.node(*id).and_then(|n| n.parent); + let mut depth = 0; + let mut nested = false; + while let Some(pid) = parent { + if depth > 256 { + break; + } + if ids.contains(&pid) { + nested = true; + break; + } + parent = doc.node(pid).and_then(|n| n.parent); + depth += 1; + } + if !nested { + out.push(*id); + } + } + out +} + +fn node_label(doc: &Document, id: NodeId) -> String { + doc.node(id).map(|n| n.name.trim().to_string()).filter(|s| !s.is_empty()).unwrap_or_else(|| format!("Layer {}", id.0)) +} diff --git a/crates/engine/src/design/rules.rs b/crates/engine/src/design/rules.rs new file mode 100644 index 000000000..89fdc700e --- /dev/null +++ b/crates/engine/src/design/rules.rs @@ -0,0 +1,132 @@ +//! The rules `design.audit` checks, with the severity and fixability the report carries. + +use figcraft_doc::DesignPreset; + +/// How much a finding matters: `High` first. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub(crate) enum Severity { + Low, + Medium, + High, +} + +impl Severity { + pub(crate) fn id(self) -> &'static str { + match self { + Severity::Low => "low", + Severity::Medium => "medium", + Severity::High => "high", + } + } + + pub(crate) fn from_id(s: &str) -> Option { + match s.trim().to_ascii_lowercase().as_str() { + "low" => Some(Severity::Low), + "medium" | "med" => Some(Severity::Medium), + "high" => Some(Severity::High), + _ => None, + } + } + + /// `0` for low, `1` for medium, `2` for high. + pub(crate) fn index(self) -> usize { + match self { + Severity::Low => 0, + Severity::Medium => 1, + Severity::High => 2, + } + } + + /// The points a finding of this severity takes off the score. + pub(crate) fn penalty(self) -> f64 { + match self { + Severity::Low => 0.5, + Severity::Medium => 2.0, + Severity::High => 5.0, + } + } +} + +/// One check: what it looks for, how much it matters and whether `design.fix` can repair it. +pub(crate) struct Rule { + pub id: &'static str, + pub severity: Severity, + /// The planned fixer can change this without guessing (see `docs/design-review.md`). + pub fixable: bool, + pub description: &'static str, +} + +pub(crate) const RULES: &[Rule] = &[ + Rule { id: "spacing.off-grid", severity: Severity::Medium, fixable: true, description: "Auto layout gap or padding is not on the 4px grid" }, + Rule { id: "radius.off-scale", severity: Severity::Low, fixable: true, description: "A corner radius is not on the 4px scale or a pill" }, + Rule { id: "type.sizes", severity: Severity::Medium, fixable: false, description: "More than five font sizes in one scope" }, + Rule { id: "type.families", severity: Severity::Medium, fixable: false, description: "More than two font families in one scope" }, + Rule { id: "type.weight", severity: Severity::Low, fixable: true, description: "A heading uses a weight above 600" }, + Rule { id: "type.italic", severity: Severity::Low, fixable: true, description: "Interface text is italic" }, + Rule { id: "type.too-small", severity: Severity::Medium, fixable: false, description: "Body text is smaller than 11px" }, + Rule { id: "type.negative-tracking", severity: Severity::Low, fixable: true, description: "Small text has negative letter spacing" }, + Rule { id: "color.gradient", severity: Severity::Medium, fixable: false, description: "A shape is filled or stroked with a gradient" }, + Rule { id: "color.gradient-text", severity: Severity::High, fixable: false, description: "Text is painted with a gradient" }, + Rule { + id: "color.glow", + severity: Severity::Medium, + fixable: true, + description: "A shadow has no offset and a large blur, so it reads as a glow", + }, + Rule { id: "color.colored-shadow", severity: Severity::Low, fixable: true, description: "A shadow has a visible hue instead of a neutral" }, + Rule { id: "color.border-opacity", severity: Severity::Low, fixable: true, description: "A border is more opaque than a hairline" }, + Rule { id: "color.contrast", severity: Severity::High, fixable: true, description: "Text contrast is below 4.5:1 (3:1 for large text)" }, + Rule { id: "color.accents", severity: Severity::Medium, fixable: false, description: "More than two accent colours in one scope (Strict)" }, + Rule { id: "token.hardcoded-color", severity: Severity::Low, fixable: false, description: "A colour matches a variable but is not bound to it" }, + Rule { + id: "token.hardcoded-number", + severity: Severity::Low, + fixable: false, + description: "A spacing, radius, size or opacity value matches a variable but is not bound", + }, + Rule { id: "icon.emoji", severity: Severity::Low, fixable: false, description: "Text or a layer name contains an emoji" }, + Rule { id: "copy.exclamation", severity: Severity::Low, fixable: false, description: "Interface copy uses an exclamation mark" }, + Rule { id: "copy.trailing-period", severity: Severity::Low, fixable: false, description: "A short label ends with a period" }, + Rule { id: "copy.hype", severity: Severity::Low, fixable: false, description: "Copy uses hype words such as \"AI-powered\"" }, + Rule { id: "naming.auto", severity: Severity::Low, fixable: false, description: "A layer still has its default auto name (Frame 12)" }, + Rule { id: "detail.shadow-count", severity: Severity::Low, fixable: false, description: "Shadows and blurs sit on too many layers" }, + Rule { + id: "layout.no-auto-layout", + severity: Severity::Low, + fixable: false, + description: "A frame or component with several children has no auto layout (Strict)", + }, + Rule { + id: "layout.text-overflow", + severity: Severity::High, + fixable: false, + description: "A fixed-width text box is shorter than the text it holds, so it clips or overlaps", + }, + Rule { + id: "layout.clipped", + severity: Severity::High, + fixable: false, + description: "A fixed-size auto layout frame clips children that overflow it, so they are invisible", + }, +]; + +pub(crate) fn rule(id: &str) -> Option<&'static Rule> { + RULES.iter().find(|r| r.id == id) +} + +/// Whether `preset` checks `id`. Recommended and Strict check every rule except the Strict-only +/// ones; Accessibility checks only the findings that keep a design usable. +pub(crate) fn enabled(id: &str, preset: DesignPreset) -> bool { + match preset { + DesignPreset::Recommended => !matches!(id, "color.accents" | "layout.no-auto-layout"), + DesignPreset::Strict => true, + DesignPreset::Accessibility => { + matches!(id, "color.contrast" | "color.gradient-text" | "type.too-small" | "layout.text-overflow" | "layout.clipped") + } + } +} + +/// The presets that check `id`, for `design.rules`. +pub(crate) fn presets_of(id: &str) -> Vec<&'static str> { + DesignPreset::ALL.iter().copied().filter(|p| enabled(id, *p)).map(DesignPreset::id).collect() +} diff --git a/crates/engine/src/design/tests.rs b/crates/engine/src/design/tests.rs new file mode 100644 index 000000000..0033dcb9d --- /dev/null +++ b/crates/engine/src/design/tests.rs @@ -0,0 +1,863 @@ +//! `design.audit`, `design.fix` and `design.rules`: the checks, the repairs and the report. + +use figcraft_doc::{EffectKind, NodeId, NodeKind, Sizing}; +use serde_json::{Value, json}; + +use crate::Session; +use crate::params::id_of; + +fn ex(s: &mut Session, cmd: &str, p: Value) -> Value { + s.execute(cmd, &p).unwrap() +} + +fn id(v: &Value) -> NodeId { + id_of(&v["id"]).unwrap() +} + +fn rules(report: &Value) -> Vec { + report["findings"].as_array().unwrap().iter().filter_map(|f| f["rule"].as_str().map(str::to_string)).collect() +} + +fn has(report: &Value, rule: &str) -> bool { + rules(report).iter().any(|r| r == rule) +} + +fn rule_nodes(report: &Value, rule: &str) -> Vec { + report["findings"].as_array().unwrap().iter().filter(|f| f["rule"] == rule).filter_map(|f| f["node"].as_u64()).collect() +} + +#[test] +fn reports_spacing_radius_copy_and_small_type() { + let mut s = Session::new(); + let f = id(&ex( + &mut s, + "node.create", + json!({"type": "frame", "x": 0, "y": 0, "width": 320, "height": 480, + "props": {"layout": "vertical", "gap": 13, "padding": 11, "cornerRadius": 7}}), + )); + ex(&mut s, "text.create", json!({"text": "Welcome back, Sam!", "x": 0, "y": 0, "parent": f, "props": {"fontSize": 10}})); + let r = ex(&mut s, "design.audit", json!({"scope": "page"})); + for rule in ["spacing.off-grid", "radius.off-scale", "copy.exclamation", "type.too-small"] { + assert!(has(&r, rule), "{rule} missing from {r}"); + } + let spacing = r["findings"].as_array().unwrap().iter().find(|f| f["rule"] == "spacing.off-grid").unwrap(); + assert_eq!(spacing["suggestion"]["gap"], 12.0, "{r}"); + assert_eq!(spacing["suggestion"]["padding"], json!([12.0, 12.0, 12.0, 12.0]), "{r}"); + assert_eq!(spacing["details"]["gap"], 13.0, "{r}"); + assert_eq!(spacing["details"]["padding"], json!([11.0, 11.0, 11.0, 11.0]), "{r}"); + assert_eq!(spacing["details"]["grid"], 4.0, "{r}"); + assert_eq!(spacing["fixable"], true); +} + +#[test] +fn reports_gradient_text_glow_and_low_contrast() { + let mut s = Session::new(); + let t = id(&ex(&mut s, "text.create", json!({"text": "Ship it", "x": 0, "y": 0}))); + ex(&mut s, "node.set", json!({"id": t, "fills": [{"type": "linearGradient", "stops": ["#ff0000", "#0000ff"]}]})); + let box_id = id(&ex(&mut s, "node.create", json!({"type": "frame", "x": 0, "y": 200, "width": 200, "height": 100}))); + ex( + &mut s, + "node.set", + json!({"id": box_id, "props": {"effects": [{"type": "dropShadow", "color": "#00000040", "offset": [0, 0], "radius": 24}]}}), + ); + let white = id(&ex(&mut s, "text.create", json!({"text": "Invisible", "x": 0, "y": 400}))); + ex(&mut s, "node.set", json!({"id": white, "props": {"fill": "#FFFFFF"}})); + let r = ex(&mut s, "design.audit", json!({"scope": "page"})); + for rule in ["color.gradient-text", "color.glow", "color.contrast"] { + assert!(has(&r, rule), "{rule} missing from {r}"); + } + let contrast = r["findings"].as_array().unwrap().iter().find(|f| f["rule"] == "color.contrast").unwrap(); + assert!(contrast["details"]["ratio"].as_f64().is_some_and(|v| v < 4.5), "{r}"); + assert_eq!(contrast["details"]["foreground"], "FFFFFF", "{r}"); +} + +#[test] +fn reports_a_gradient_on_a_shape() { + let mut s = Session::new(); + let rect = id(&ex(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 100, "height": 50}))); + ex(&mut s, "node.set", json!({"id": rect, "fills": [{"type": "linearGradient", "stops": ["#ff0000", "#0000ff"]}]})); + let r = ex(&mut s, "design.audit", json!({"scope": "page"})); + assert!(has(&r, "color.gradient"), "{r}"); + assert!(!has(&r, "color.gradient-text"), "{r}"); +} + +#[test] +fn counts_type_sizes_and_families_across_the_scope() { + let mut s = Session::new(); + for size in [12, 13, 14, 15, 16, 17, 18, 19] { + ex(&mut s, "text.create", json!({"text": "Text", "x": 0, "y": size as f64 * 20.0, "props": {"fontSize": size}})); + } + let r = ex(&mut s, "design.audit", json!({"scope": "page"})); + assert!(has(&r, "type.sizes"), "{r}"); + let f = r["findings"].as_array().unwrap().iter().find(|f| f["rule"] == "type.sizes").unwrap(); + assert!(f["message"].as_str().unwrap().contains("8 font sizes"), "{r}"); + assert_eq!(f["details"]["count"], 8, "{r}"); + assert_eq!(f["details"]["sizes"].as_array().map(Vec::len), Some(8), "{r}"); +} + +#[test] +fn selection_scope_ignores_other_layers() { + let mut s = Session::new(); + let bad = id(&ex( + &mut s, + "node.create", + json!({"type": "frame", "x": 0, "y": 0, "width": 200, "height": 100, "props": {"layout": "vertical", "gap": 13}}), + )); + let good = id(&ex( + &mut s, + "node.create", + json!({"type": "frame", "x": 300, "y": 0, "width": 200, "height": 100, "props": {"layout": "vertical", "gap": 8}}), + )); + s.set_selection(vec![good]); + let r = ex(&mut s, "design.audit", json!({"scope": "selection"})); + assert!(!has(&r, "spacing.off-grid"), "{r}"); + s.set_selection(vec![bad]); + let r = ex(&mut s, "design.audit", json!({"scope": "selection"})); + assert!(has(&r, "spacing.off-grid"), "{r}"); +} + +#[test] +fn a_nested_selection_is_audited_once() { + let mut s = Session::new(); + let f = id(&ex(&mut s, "node.create", json!({"type": "frame", "x": 0, "y": 0, "width": 200, "height": 100}))); + let child = id(&ex(&mut s, "node.create", json!({"type": "rectangle", "parent": f, "x": 0, "y": 0, "width": 20, "height": 20}))); + s.set_selection(vec![f, child]); + let r = ex(&mut s, "design.audit", json!({"scope": "selection"})); + // The rectangle is only in the report through the frame's subtree. + let rect_findings = r["findings"].as_array().unwrap().iter().filter(|f| f["path"].as_str().unwrap().contains("Rectangle")).count(); + assert!(rect_findings <= 1, "{r}"); +} + +#[test] +fn filters_by_rule_and_severity() { + let mut s = Session::new(); + ex(&mut s, "node.create", json!({"type": "frame", "x": 0, "y": 0, "width": 200, "height": 100, "props": {"layout": "vertical", "gap": 13}})); + let only = ex(&mut s, "design.audit", json!({"scope": "page", "rules": ["spacing.off-grid"]})); + assert_eq!(rules(&only), vec!["spacing.off-grid".to_string()], "{only}"); + assert_eq!(only["byRule"]["spacing.off-grid"], 1, "{only}"); + let high = ex(&mut s, "design.audit", json!({"scope": "page", "minSeverity": "high"})); + assert!(rules(&high).is_empty(), "{high}"); + assert_eq!(high["score"], 100.0, "{high}"); + let all = ex(&mut s, "design.audit", json!({"scope": "page"})); + assert!(all["score"].as_f64().unwrap() < 100.0, "{all}"); + assert!(all["nodes"].as_u64().unwrap() >= 2, "the report counts the layers it walked: {all}"); +} + +#[test] +fn a_light_border_is_a_hairline() { + let mut s = Session::new(); + let light = id(&ex( + &mut s, + "node.create", + json!({ + "type": "frame", "x": 0, "y": 0, "width": 200, "height": 60, + "props": {"stroke": "#E0E0E0", "strokeWeight": 1} + }), + )); + let strong = id(&ex( + &mut s, + "node.create", + json!({ + "type": "frame", "x": 0, "y": 100, "width": 200, "height": 60, + "props": {"stroke": "#333333", "strokeWeight": 1} + }), + )); + // An inside stroke on a dark panel sits on the panel, not on the page behind it. + let dark_panel = id(&ex( + &mut s, + "node.create", + json!({ + "type": "frame", "x": 0, "y": 200, "width": 200, "height": 60, + "props": {"fill": "#1E1E1E", "stroke": "#2A2A2A", "strokeWeight": 1, "strokeAlign": "inside"} + }), + )); + let r = ex(&mut s, "design.audit", json!({"scope": "page", "rules": ["color.border-opacity"]})); + let flagged: Vec = r["findings"].as_array().unwrap().iter().filter_map(|f| f["node"].as_u64()).collect(); + assert!(!flagged.contains(&light.0), "{r}"); + assert!(flagged.contains(&strong.0), "{r}"); + assert!(!flagged.contains(&dark_panel.0), "a dark border on a dark panel is not a strong hairline: {r}"); +} + +#[test] +fn reports_emoji_and_default_names() { + let mut s = Session::new(); + let f = id(&ex(&mut s, "node.create", json!({"type": "frame", "x": 0, "y": 0, "width": 200, "height": 100}))); + ex(&mut s, "text.create", json!({"text": "Ship it 🚀", "x": 0, "y": 0, "parent": f, "props": {"fontSize": 16}})); + let r = ex(&mut s, "design.audit", json!({"scope": "page"})); + assert!(has(&r, "icon.emoji"), "{r}"); + assert!(has(&r, "naming.auto"), "{r}"); +} + +#[test] +fn lists_the_rules() { + let mut s = Session::new(); + let r = ex(&mut s, "design.rules", json!({})); + let rules = r["rules"].as_array().unwrap(); + assert!(rules.len() >= 15, "{r}"); + let spacing = rules.iter().find(|r| r["id"] == "spacing.off-grid").unwrap(); + assert_eq!(spacing["severity"], "medium"); + assert_eq!(spacing["fixable"], true); + assert_eq!(spacing["presets"], json!(["recommended", "strict"])); + let accents = rules.iter().find(|r| r["id"] == "color.accents").unwrap(); + assert_eq!(accents["presets"], json!(["strict"])); + assert_eq!(r["presets"].as_array().unwrap().len(), 3, "{r}"); +} + +#[test] +fn configure_changes_the_files_design_system() { + let mut s = Session::new(); + let r = ex( + &mut s, + "design.configure", + json!({"preset": "strict", "grid": 8, "radii": [0, 10, 20], "brand": ["#3366FF"], "disabled": ["icon.emoji"]}), + ); + assert_eq!(r["preset"], "strict", "{r}"); + assert_eq!(r["grid"], 8.0, "{r}"); + assert_eq!(r["radii"], json!([0.0, 10.0, 20.0]), "{r}"); + assert_eq!(r["brand"], json!(["#3366FF"]), "{r}"); + assert_eq!(r["disabled"], json!(["icon.emoji"]), "{r}"); + assert_eq!(s.doc().unwrap().design_review.grid(), 8.0); + // The settings are part of the file and undoable with it. + let reset = ex(&mut s, "design.configure", json!({"reset": true})); + assert_eq!(reset["preset"], "recommended", "{reset}"); + assert_eq!(reset["grid"], 4.0, "{reset}"); + assert!(s.doc().unwrap().design_review.is_default()); + assert!(s.execute("design.configure", &json!({"grid": 0})).is_err()); + assert!(s.execute("design.configure", &json!({"radii": ["wide"]})).is_err()); + assert!(s.execute("design.configure", &json!({"disabled": ["no.such.rule"]})).is_err()); +} + +#[test] +fn the_configured_grid_drives_spacing_and_the_fixer() { + let mut s = Session::new(); + ex(&mut s, "design.configure", json!({"grid": 8})); + let on = id(&ex( + &mut s, + "node.create", + json!({"type": "frame", "x": 0, "y": 0, "width": 200, "height": 100, + "props": {"layout": "vertical", "gap": 8, "padding": 8, "cornerRadius": 8}}), + )); + let off = id(&ex( + &mut s, + "node.create", + json!({"type": "frame", "x": 300, "y": 0, "width": 200, "height": 100, + "props": {"layout": "vertical", "gap": 6, "padding": 10, "cornerRadius": 12}}), + )); + let only = json!(["spacing.off-grid", "radius.off-scale"]); + let r = ex(&mut s, "design.audit", json!({"scope": "page", "rules": &only})); + assert!(!rule_nodes(&r, "spacing.off-grid").contains(&on.0), "{r}"); + assert!(!rule_nodes(&r, "radius.off-scale").contains(&on.0), "{r}"); + assert_eq!(rule_nodes(&r, "spacing.off-grid"), vec![off.0], "{r}"); + assert_eq!(rule_nodes(&r, "radius.off-scale"), vec![off.0], "{r}"); + assert!(r["grid"] == json!(8.0), "{r}"); + ex(&mut s, "design.fix", json!({"scope": "page"})); + let n = s.doc().unwrap().node(off).unwrap(); + assert_eq!(n.layout.as_ref().unwrap().gap, 8.0); + assert_eq!(n.layout.as_ref().unwrap().padding, [8.0; 4]); + assert_eq!(n.corners.radii, [16.0; 4]); +} + +#[test] +fn a_custom_radius_scale_is_the_only_scale() { + let mut s = Session::new(); + ex(&mut s, "design.configure", json!({"radii": [10, 20]})); + let ok = id(&ex(&mut s, "node.create", json!({"type": "frame", "x": 0, "y": 0, "width": 200, "height": 100, "props": {"cornerRadius": 10}}))); + let off = id(&ex(&mut s, "node.create", json!({"type": "frame", "x": 300, "y": 0, "width": 200, "height": 100, "props": {"cornerRadius": 8}}))); + let r = ex(&mut s, "design.audit", json!({"scope": "page", "rules": ["radius.off-scale"]})); + assert!(!rule_nodes(&r, "radius.off-scale").contains(&ok.0), "{r}"); + assert_eq!(rule_nodes(&r, "radius.off-scale"), vec![off.0], "{r}"); + ex(&mut s, "design.fix", json!({"scope": "page"})); + assert_eq!(s.doc().unwrap().node(off).unwrap().corners.radii, [10.0; 4]); +} + +#[test] +fn presets_choose_the_rules_and_disabled_rules_stay_off() { + let mut s = Session::new(); + for (i, fill) in ["#FF0000", "#00AA00", "#0000FF"].iter().enumerate() { + ex(&mut s, "node.create", json!({"type": "rectangle", "x": i * 60, "y": 0, "width": 40, "height": 40, "props": {"fill": fill}})); + } + let stack = id(&ex(&mut s, "node.create", json!({"type": "frame", "x": 0, "y": 100, "width": 200, "height": 200}))); + for i in 0..3 { + ex(&mut s, "node.create", json!({"type": "rectangle", "x": i * 20, "y": 0, "width": 10, "height": 10, "parent": stack})); + } + let off_grid = id(&ex( + &mut s, + "node.create", + json!({"type": "frame", "x": 300, "y": 100, "width": 200, "height": 100, "props": {"layout": "vertical", "gap": 13}}), + )); + + let recommended = ex(&mut s, "design.audit", json!({"scope": "page"})); + assert_eq!(recommended["preset"], "recommended", "{recommended}"); + assert!(!has(&recommended, "color.accents"), "{recommended}"); + assert!(!has(&recommended, "layout.no-auto-layout"), "{recommended}"); + let strict = ex(&mut s, "design.audit", json!({"scope": "page", "preset": "strict"})); + assert!(has(&strict, "color.accents"), "{strict}"); + assert!(has(&strict, "layout.no-auto-layout"), "{strict}"); + let a11y = ex(&mut s, "design.audit", json!({"scope": "page", "preset": "accessibility"})); + assert!(!has(&a11y, "spacing.off-grid"), "{a11y}"); + + // The file can make Strict its own, and a disabled rule is neither reported nor fixed. + ex(&mut s, "design.configure", json!({"preset": "strict", "disabled": ["spacing.off-grid"]})); + let file = ex(&mut s, "design.audit", json!({"scope": "page"})); + assert_eq!(file["preset"], "strict", "{file}"); + assert!(has(&file, "color.accents"), "{file}"); + assert!(!has(&file, "spacing.off-grid"), "{file}"); + ex(&mut s, "design.fix", json!({"scope": "page"})); + assert_eq!(s.doc().unwrap().node(off_grid).unwrap().layout.as_ref().unwrap().gap, 13.0, "a disabled rule is not fixed"); +} + +#[test] +fn contrast_is_checked_in_the_given_variable_modes() { + let mut s = Session::new(); + ex(&mut s, "variable.createCollection", json!({"name": "Theme"})); + ex(&mut s, "variable.addMode", json!({"collection": "Theme", "name": "Dark"})); + ex(&mut s, "variable.create", json!({"collection": "Theme", "name": "surface", "type": "color", "value": "#FFFFFF"})); + ex(&mut s, "variable.set", json!({"variable": "surface", "mode": "Dark", "value": "#222222"})); + ex(&mut s, "variable.create", json!({"collection": "Theme", "name": "ink", "type": "color", "value": "#111111"})); + ex(&mut s, "variable.set", json!({"variable": "ink", "mode": "Dark", "value": "#777777"})); + let f = id(&ex(&mut s, "node.create", json!({"type": "frame", "x": 0, "y": 0, "width": 200, "height": 100, "props": {"fill": "#FFFFFF"}}))); + let t = id(&ex(&mut s, "text.create", json!({"text": "Read me", "x": 10, "y": 10, "parent": f}))); + ex(&mut s, "node.set", json!({"id": t, "fills": [{"type": "solid", "color": "#111111"}]})); + ex(&mut s, "variable.bind", json!({"ids": [f], "field": "fill", "variable": "surface"})); + ex(&mut s, "variable.bind", json!({"ids": [t], "field": "fill", "variable": "ink"})); + let only = json!(["color.contrast"]); + let light = ex(&mut s, "design.audit", json!({"scope": "page", "rules": &only})); + assert!(!has(&light, "color.contrast"), "{light}"); + let dark = ex(&mut s, "design.audit", json!({"scope": "page", "rules": &only, "modes": {"Theme": "Dark"}})); + assert!(has(&dark, "color.contrast"), "{dark}"); + assert_eq!(dark["modes"], json!({"Theme": "Dark"}), "{dark}"); + let finding = dark["findings"].as_array().unwrap().iter().find(|f| f["rule"] == "color.contrast").unwrap(); + assert_eq!(finding["fixable"], false, "{dark}"); + assert_eq!(finding["reason"], "modes", "{dark}"); + assert!(finding["message"].as_str().unwrap().contains("Theme: Dark"), "{finding}"); + assert!(s.execute("design.audit", &json!({"scope": "page", "modes": {"Theme": "Dusk"}})).is_err()); + assert!(s.execute("design.assert", &json!({"scope": "page", "modes": {"Theme": "Dark"}, "failOn": "high"})).is_err()); +} + +#[test] +fn unfixable_findings_carry_a_reason_code() { + let mut s = Session::new(); + let bound = id(&ex( + &mut s, + "node.create", + json!({"type": "frame", "x": 0, "y": 0, "width": 200, "height": 100, "props": {"layout": "vertical", "gap": 13}}), + )); + ex(&mut s, "variable.createCollection", json!({"name": "C"})); + ex(&mut s, "variable.create", json!({"collection": "C", "name": "space", "type": "number", "value": 13})); + ex(&mut s, "variable.bind", json!({"ids": [bound], "field": "gap", "variable": "space"})); + let loose = id(&ex( + &mut s, + "node.create", + json!({"type": "frame", "x": 300, "y": 0, "width": 200, "height": 100, "props": {"layout": "vertical", "gap": 13}}), + )); + let r = ex(&mut s, "design.audit", json!({"scope": "page", "rules": ["spacing.off-grid", "naming.auto"]})); + let findings = r["findings"].as_array().unwrap(); + let bound_f = findings.iter().find(|f| f["node"] == bound.0 && f["rule"] == "spacing.off-grid").unwrap(); + assert_eq!(bound_f["fixable"], false, "{r}"); + assert_eq!(bound_f["reason"], "bound", "{r}"); + let loose_f = findings.iter().find(|f| f["node"] == loose.0 && f["rule"] == "spacing.off-grid").unwrap(); + assert_eq!(loose_f["fixable"], true, "{r}"); + assert!(loose_f.get("reason").is_none(), "{r}"); + let named = findings.iter().find(|f| f["rule"] == "naming.auto").unwrap(); + assert_eq!(named["reason"], "decision", "{r}"); +} + +#[test] +fn brand_colours_do_not_count_as_stray_accents() { + let mut s = Session::new(); + for (i, fill) in ["#FF0000", "#00AA00", "#0000FF"].iter().enumerate() { + ex(&mut s, "node.create", json!({"type": "rectangle", "x": i * 60, "y": 0, "width": 40, "height": 40, "props": {"fill": fill}})); + } + let loose = ex(&mut s, "design.audit", json!({"scope": "page", "preset": "strict"})); + assert!(has(&loose, "color.accents"), "{loose}"); + let brand = ex(&mut s, "design.configure", json!({"brand": ["#FF0000", "#00AA00"]})); + assert_eq!(brand["brand"], json!(["#FF0000", "#00AA00"]), "{brand}"); + let kept = ex(&mut s, "design.audit", json!({"scope": "page", "preset": "strict"})); + assert!(!has(&kept, "color.accents"), "{kept}"); +} + +#[test] +fn junk_params_are_errors_not_panics() { + let mut s = Session::new(); + for junk in [ + json!({"scope": {"x": 1}}), + json!({"scope": "everything"}), + json!({"rules": [1]}), + json!({"rules": "spacing.off-grid"}), + json!({"rules": ["no.such.rule"]}), + json!({"minSeverity": "loud"}), + ] { + assert!(s.execute("design.audit", &junk).is_err(), "{junk} was accepted"); + } + assert!(s.execute("design.audit", &json!({})).is_ok()); + // Nulls mean "the default", not junk. + assert!(s.execute("design.audit", &json!({"scope": "document", "rules": null, "minSeverity": null})).is_ok()); +} + +fn spaced_frame(s: &mut Session) -> NodeId { + id(&ex( + s, + "node.create", + json!({"type": "frame", "x": 0, "y": 0, "width": 200, "height": 100, + "props": {"layout": "vertical", "gap": 13, "padding": 11, "cornerRadius": 7}}), + )) +} + +#[test] +fn fix_snaps_spacing_and_radius_as_one_undo_step() { + let mut s = Session::new(); + let f = spaced_frame(&mut s); + let r = ex(&mut s, "design.fix", json!({"scope": "page"})); + assert_eq!(r["dryRun"], false, "{r}"); + assert!(r["changed"].as_u64().unwrap() >= 1, "{r}"); + assert!(r["byRule"]["spacing.off-grid"].as_u64().unwrap() >= 1, "{r}"); + assert!(r["byRule"]["radius.off-scale"].as_u64().unwrap() >= 1, "{r}"); + { + let n = s.doc().unwrap().node(f).unwrap(); + let al = n.layout.as_ref().unwrap(); + assert_eq!((al.gap, al.padding[0], al.padding[1]), (12.0, 12.0, 12.0)); + assert_eq!(n.corners.uniform(), Some(8.0)); + } + let after = ex(&mut s, "design.audit", json!({"scope": "page"})); + assert!(!has(&after, "spacing.off-grid"), "{after}"); + assert!(!has(&after, "radius.off-scale"), "{after}"); + // The whole repair is one undo step. + ex(&mut s, "edit.undo", json!({})); + let n = s.doc().unwrap().node(f).unwrap(); + assert_eq!(n.layout.as_ref().unwrap().gap, 13.0); + assert_eq!(n.corners.uniform(), Some(7.0)); +} + +#[test] +fn dry_run_reports_without_changing_anything() { + let mut s = Session::new(); + let f = spaced_frame(&mut s); + let r = ex(&mut s, "design.fix", json!({"scope": "page", "dryRun": true})); + assert_eq!(r["dryRun"], true, "{r}"); + assert!(r["changed"].as_u64().unwrap() >= 1, "{r}"); + assert_eq!(s.doc().unwrap().node(f).unwrap().layout.as_ref().unwrap().gap, 13.0); +} + +#[test] +fn fix_filters_by_rule() { + let mut s = Session::new(); + let f = spaced_frame(&mut s); + ex(&mut s, "design.fix", json!({"scope": "page", "rules": ["radius.off-scale"]})); + let n = s.doc().unwrap().node(f).unwrap(); + assert_eq!(n.layout.as_ref().unwrap().gap, 13.0, "spacing was not asked for"); + assert_eq!(n.corners.uniform(), Some(8.0)); +} + +#[test] +fn fix_caps_heading_weight_and_removes_tracking() { + let mut s = Session::new(); + let heading = id(&ex(&mut s, "text.create", json!({"text": "Title", "x": 0, "y": 0, "props": {"fontSize": 28, "fontStyle": "Bold"}}))); + let small = id(&ex( + &mut s, + "text.create", + json!({"text": "Label", "x": 0, "y": 60, + "props": {"fontSize": 16, "letterSpacing": {"unit": "pixels", "value": -1.5}}}), + )); + let r = ex(&mut s, "design.fix", json!({"scope": "page"})); + assert!(r["changed"].as_u64().unwrap() >= 2, "{r}"); + let doc = s.doc().unwrap(); + let NodeKind::Text(h) = &doc.node(heading).unwrap().kind else { panic!() }; + assert_eq!(h.style.weight(), 600); + let NodeKind::Text(l) = &doc.node(small).unwrap().kind else { panic!() }; + assert_eq!(l.style.letter_spacing.resolve(16.0), 0.0); + let after = ex(&mut s, "design.audit", json!({"scope": "page"})); + assert!(!has(&after, "type.weight"), "{after}"); + assert!(!has(&after, "type.negative-tracking"), "{after}"); +} + +#[test] +fn fix_removes_glows_and_neutralises_coloured_shadows() { + let mut s = Session::new(); + let f = id(&ex(&mut s, "node.create", json!({"type": "frame", "x": 0, "y": 0, "width": 200, "height": 100}))); + ex( + &mut s, + "node.set", + json!({"id": f, "props": {"effects": [ + {"type": "dropShadow", "color": "#00000040", "offset": [0, 0], "radius": 24}, + {"type": "dropShadow", "color": "#7048E880", "offset": [0, 4], "radius": 12} + ]}}), + ); + let r = ex(&mut s, "design.fix", json!({"scope": "page"})); + assert!(r["changed"].as_u64().unwrap() >= 1, "{r}"); + let effects = &s.doc().unwrap().node(f).unwrap().effects; + assert_eq!(effects.len(), 1, "the glow is gone: {effects:?}"); + let EffectKind::DropShadow(shadow) = &effects[0].kind else { panic!() }; + assert_eq!((shadow.color.r, shadow.color.g, shadow.color.b), (0.0, 0.0, 0.0)); + let after = ex(&mut s, "design.audit", json!({"scope": "page"})); + assert!(!has(&after, "color.glow"), "{after}"); + assert!(!has(&after, "color.colored-shadow"), "{after}"); +} + +#[test] +fn fix_leaves_content_and_gradients_alone() { + let mut s = Session::new(); + let t = id(&ex(&mut s, "text.create", json!({"text": "Ship it 🚀!", "x": 0, "y": 0, "props": {"fontSize": 16}}))); + ex(&mut s, "node.set", json!({"id": t, "fills": [{"type": "linearGradient", "stops": ["#ff0000", "#0000ff"]}]})); + ex(&mut s, "design.fix", json!({"scope": "page"})); + let doc = s.doc().unwrap(); + let NodeKind::Text(td) = &doc.node(t).unwrap().kind else { panic!() }; + assert_eq!(td.characters, "Ship it 🚀!"); + assert!(matches!(&td.style.fills.as_deref().unwrap_or(&doc.node(t).unwrap().fills)[0].kind, figcraft_color::PaintKind::Gradient(_))); +} + +#[test] +fn fix_darkens_low_contrast_text() { + let mut s = Session::new(); + let f = id(&ex(&mut s, "node.create", json!({"type": "frame", "x": 0, "y": 0, "width": 200, "height": 100}))); + let t = id(&ex(&mut s, "text.create", json!({"text": "Invisible", "x": 0, "y": 0, "parent": f, "props": {"fontSize": 16, "fill": "#FFFFFF"}}))); + assert!(has(&ex(&mut s, "design.audit", json!({"scope": "page"})), "color.contrast")); + let r = ex(&mut s, "design.fix", json!({"scope": "page", "rules": ["color.contrast"]})); + assert!(r["changed"].as_u64().unwrap() >= 1, "{r}"); + { + let doc = s.doc().unwrap(); + let n = doc.node(t).unwrap(); + let NodeKind::Text(td) = &n.kind else { panic!() }; + let paints = td.style.fills.as_deref().unwrap_or(&n.fills); + let color = paints.iter().rev().find_map(|p| p.solid_color()).unwrap(); + assert!(color.contrast(figcraft_color::Color::WHITE) >= 4.5, "{color:?}"); + } + assert!(!has(&ex(&mut s, "design.audit", json!({"scope": "page"})), "color.contrast")); +} + +#[test] +fn reports_text_that_overflows_its_box() { + let mut s = Session::new(); + let t = id(&ex( + &mut s, + "node.create", + json!({"type": "text", "text": "A long headline that needs several lines in a narrow box", + "x": 0, "y": 0, "width": 120, "height": 40, + "props": {"fontSize": 24, "textAutoResize": "none"}}), + )); + let r = ex(&mut s, "design.audit", json!({"scope": "page"})); + let f = r["findings"].as_array().unwrap().iter().find(|f| f["rule"] == "layout.text-overflow").unwrap_or_else(|| panic!("{r}")); + assert_eq!(f["node"], t.0, "{r}"); +} + +#[test] +fn a_sibling_background_is_the_text_backdrop() { + let mut s = Session::new(); + let f = id(&ex(&mut s, "node.create", json!({"type": "frame", "x": 0, "y": 0, "width": 300, "height": 200, "props": {"fill": "#F4F1EA"}}))); + ex(&mut s, "node.create", json!({"type": "rectangle", "parent": f, "x": 0, "y": 0, "width": 120, "height": 200, "props": {"fill": "#1E1E1E"}})); + let white = + id(&ex(&mut s, "text.create", json!({"text": "White on dark", "x": 20, "y": 20, "parent": f, "props": {"fontSize": 16, "fill": "#FFFFFF"}}))); + let dark = + id(&ex(&mut s, "text.create", json!({"text": "Dark on dark", "x": 20, "y": 80, "parent": f, "props": {"fontSize": 16, "fill": "#111111"}}))); + let r = ex(&mut s, "design.audit", json!({"scope": "page", "rules": ["color.contrast"]})); + let flagged = rule_nodes(&r, "color.contrast"); + assert!(!flagged.contains(&white.0), "white on the dark sibling is legible: {r}"); + assert!(flagged.contains(&dark.0), "dark on the dark sibling is not: {r}"); +} + +#[test] +fn a_background_inside_a_group_is_found() { + let mut s = Session::new(); + let f = id(&ex(&mut s, "node.create", json!({"type": "frame", "x": 0, "y": 0, "width": 300, "height": 200, "props": {"fill": "#F4F1EA"}}))); + let rect = id(&ex(&mut s, "shape.rectangle", json!({"parent": f, "x": 0, "y": 0, "width": 120, "height": 200, "props": {"fill": "#1E1E1E"}}))); + s.set_selection(vec![rect]); + ex(&mut s, "object.group", json!({})); + let white = id(&ex( + &mut s, + "text.create", + json!({"text": "White on grouped dark", "x": 20, "y": 20, "parent": f, "props": {"fontSize": 16, "fill": "#FFFFFF"}}), + )); + let r = ex(&mut s, "design.audit", json!({"scope": "page", "rules": ["color.contrast"]})); + assert!(!rule_nodes(&r, "color.contrast").contains(&white.0), "the grouped background is under the text: {r}"); +} + +#[test] +fn fix_uses_the_sibling_background_for_contrast() { + let mut s = Session::new(); + let f = id(&ex(&mut s, "node.create", json!({"type": "frame", "x": 0, "y": 0, "width": 300, "height": 200, "props": {"fill": "#F4F1EA"}}))); + ex(&mut s, "node.create", json!({"type": "rectangle", "parent": f, "x": 0, "y": 0, "width": 120, "height": 200, "props": {"fill": "#1E1E1E"}})); + let white = + id(&ex(&mut s, "text.create", json!({"text": "White on dark", "x": 20, "y": 20, "parent": f, "props": {"fontSize": 16, "fill": "#FFFFFF"}}))); + let dark = + id(&ex(&mut s, "text.create", json!({"text": "Dark on dark", "x": 20, "y": 80, "parent": f, "props": {"fontSize": 16, "fill": "#111111"}}))); + ex(&mut s, "design.fix", json!({"scope": "page", "rules": ["color.contrast"]})); + let doc = s.doc().unwrap(); + let fill = |id| { + let n = doc.node(id).unwrap(); + let NodeKind::Text(t) = &n.kind else { panic!() }; + t.style.fills.as_deref().unwrap_or(&n.fills).iter().rev().find_map(|p| p.solid_color()).unwrap() + }; + let w = fill(white); + assert_eq!((w.r, w.g, w.b), (1.0, 1.0, 1.0), "the legible white text is left alone"); + let d = fill(dark); + assert!(d.contrast(figcraft_color::Color::from_rgb8_const(0x1E, 0x1E, 0x1E)) >= 4.5, "the dark text is lightened: {d:?}"); +} + +#[test] +fn locked_layers_are_left_alone() { + let mut s = Session::new(); + let f = spaced_frame(&mut s); + ex(&mut s, "node.set", json!({"id": f, "props": {"locked": true}})); + let r = ex(&mut s, "design.audit", json!({"scope": "page"})); + assert!(!has(&r, "spacing.off-grid") && !has(&r, "radius.off-scale"), "{r}"); + ex(&mut s, "design.fix", json!({"scope": "page"})); + let n = s.doc().unwrap().node(f).unwrap(); + assert_eq!((n.layout.as_ref().unwrap().gap, n.corners.uniform()), (13.0, Some(7.0))); +} + +#[test] +fn a_bound_spacing_value_is_reported_but_not_fixed() { + let mut s = Session::new(); + let f = spaced_frame(&mut s); + ex(&mut s, "variable.createCollection", json!({"name": "C"})); + ex(&mut s, "variable.create", json!({"collection": "C", "name": "gap", "type": "number", "value": 13})); + ex(&mut s, "variable.bind", json!({"ids": [f], "field": "gap", "variable": "gap"})); + let r = ex(&mut s, "design.audit", json!({"scope": "page", "rules": ["spacing.off-grid"]})); + let finding = r["findings"].as_array().unwrap().iter().find(|f| f["rule"] == "spacing.off-grid").unwrap_or_else(|| panic!("{r}")); + assert_eq!(finding["fixable"], false, "{r}"); + assert!(finding["message"].as_str().unwrap().contains("bound"), "{r}"); + ex(&mut s, "design.fix", json!({"scope": "page", "rules": ["spacing.off-grid"]})); + assert_eq!(s.doc().unwrap().node(f).unwrap().layout.as_ref().unwrap().gap, 13.0); +} + +#[test] +fn a_padding_binding_owns_the_spacing() { + let mut s = Session::new(); + let f = spaced_frame(&mut s); + ex(&mut s, "variable.createCollection", json!({"name": "C"})); + ex(&mut s, "variable.create", json!({"collection": "C", "name": "space", "type": "number", "value": 11})); + ex(&mut s, "variable.bind", json!({"ids": [f], "field": "padding", "variable": "space"})); + let r = ex(&mut s, "design.audit", json!({"scope": "page", "rules": ["spacing.off-grid"]})); + let finding = r["findings"].as_array().unwrap().iter().find(|f| f["rule"] == "spacing.off-grid").unwrap_or_else(|| panic!("{r}")); + assert_eq!(finding["fixable"], false, "{r}"); + ex(&mut s, "design.fix", json!({"scope": "page", "rules": ["spacing.off-grid"]})); + let n = s.doc().unwrap().node(f).unwrap(); + let al = n.layout.as_ref().unwrap(); + assert_eq!((al.gap, al.padding[0]), (13.0, 11.0), "a padding binding owns the whole layout"); +} + +#[test] +fn a_blended_background_is_not_sampled() { + let mut s = Session::new(); + let f = id(&ex(&mut s, "node.create", json!({"type": "frame", "x": 0, "y": 0, "width": 300, "height": 200, "props": {"fill": "#F4F1EA"}}))); + ex( + &mut s, + "node.create", + json!({"type": "rectangle", "parent": f, "x": 0, "y": 0, "width": 120, "height": 200, "props": {"fill": "#1E1E1E", "blend": "multiply"}}), + ); + let dark = id(&ex( + &mut s, + "text.create", + json!({"text": "Dark on a blended dark", "x": 20, "y": 20, "parent": f, "props": {"fontSize": 16, "fill": "#111111"}}), + )); + let r = ex(&mut s, "design.audit", json!({"scope": "page", "rules": ["color.contrast"]})); + assert!(!rule_nodes(&r, "color.contrast").contains(&dark.0), "a blend mode makes the backdrop unknown: {r}"); +} + +#[test] +fn fix_with_ids_leaves_other_layers_alone() { + let mut s = Session::new(); + let a = spaced_frame(&mut s); + let b = spaced_frame(&mut s); + let r = ex(&mut s, "design.fix", json!({"ids": [a]})); + assert_eq!(r["scope"], "selection", "{r}"); + let doc = s.doc().unwrap(); + assert_eq!(doc.node(a).unwrap().layout.as_ref().unwrap().gap, 12.0); + assert_eq!(doc.node(b).unwrap().layout.as_ref().unwrap().gap, 13.0); +} + +#[test] +fn fix_with_exact_leaves_a_child_finding_alone() { + let mut s = Session::new(); + let parent = id(&ex( + &mut s, + "node.create", + json!({"type": "frame", "name": "Parent", "x": 0, "y": 0, "width": 200, "height": 100, + "props": {"layout": "vertical", "cornerRadius": 3}}), + )); + let child = id(&ex( + &mut s, + "node.create", + json!({"type": "rectangle", "name": "Child", "parent": parent, "x": 0, "y": 0, "width": 80, "height": 40, + "props": {"cornerRadius": 3}}), + )); + let r = ex(&mut s, "design.fix", json!({"ids": [parent], "rules": ["radius.off-scale"], "exact": true})); + assert_eq!(r["changed"], 1, "{r}"); + let doc = s.doc().unwrap(); + assert_ne!(doc.node(parent).unwrap().corners.radii[0], 3.0, "the root is repaired"); + assert_eq!(doc.node(child).unwrap().corners.radii[0], 3.0, "an ignored child finding stays: exact means the listed layers only"); +} + +#[test] +fn hardcoded_values_that_match_variables_are_reported() { + let mut s = Session::new(); + ex(&mut s, "variable.createCollection", json!({"name": "C"})); + ex(&mut s, "variable.create", json!({"collection": "C", "name": "red", "type": "color", "value": "#FF0000"})); + ex(&mut s, "variable.create", json!({"collection": "C", "name": "space", "type": "number", "value": 12})); + let r = id(&ex(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 100, "height": 50, "props": {"fill": "#FF0000"}}))); + let f = id(&ex( + &mut s, + "node.create", + json!({"type": "frame", "x": 0, "y": 100, "width": 200, "height": 100, "props": {"layout": "vertical", "gap": 12}}), + )); + let only_rules = json!(["token.hardcoded-color", "token.hardcoded-number"]); + let before = ex(&mut s, "design.audit", json!({"scope": "page", "rules": &only_rules})); + assert!(has(&before, "token.hardcoded-color"), "{before}"); + assert!(has(&before, "token.hardcoded-number"), "{before}"); + ex(&mut s, "variable.bind", json!({"ids": [r], "field": "fill", "variable": "red"})); + ex(&mut s, "variable.bind", json!({"ids": [f], "field": "gap", "variable": "space"})); + let after = ex(&mut s, "design.audit", json!({"scope": "page", "rules": &only_rules})); + assert!(rules(&after).is_empty(), "{after}"); +} + +#[test] +fn assert_is_a_ci_gate_on_severity_and_score() { + let mut s = Session::new(); + let _f = spaced_frame(&mut s); + // Off-grid spacing is medium: a high gate passes, a medium gate fails. + assert!(s.execute("design.assert", &json!({"scope": "page", "failOn": "high"})).is_ok()); + let err = s.execute("design.assert", &json!({"scope": "page", "failOn": "medium"})).unwrap_err().to_string(); + assert!(err.contains("spacing.off-grid"), "{err}"); + assert!(s.execute("design.assert", &json!({"scope": "page", "minScore": 100})).is_err()); + assert!(s.execute("design.assert", &json!({"scope": "page", "minScore": "high"})).is_err()); + assert!(s.execute("design.assert", &json!({"scope": "page", "failOn": "loud"})).is_err()); + // A frame on the grid and the scale has nothing to report. + let mut clean = Session::new(); + ex( + &mut clean, + "node.create", + json!({"type": "frame", "x": 0, "y": 0, "width": 200, "height": 100, + "props": {"layout": "vertical", "gap": 8, "padding": 8, "cornerRadius": 8}}), + ); + let ok = ex(&mut clean, "design.assert", json!({"scope": "page", "failOn": "medium"})); + assert_eq!(ok["ok"], true, "{ok}"); + assert_eq!(ok["score"], 100.0, "{ok}"); +} + +#[test] +fn fix_junk_is_an_error_not_a_panic() { + let mut s = Session::new(); + assert!(s.execute("design.fix", &json!({"scope": "everything"})).is_err()); + assert!(s.execute("design.fix", &json!({"rules": ["no.such.rule"]})).is_err()); + assert!(s.execute("design.fix", &json!({})).is_ok()); +} + +#[test] +fn a_fixed_frame_that_clips_children_is_reported() { + let mut s = Session::new(); + let f = id(&ex( + &mut s, + "node.create", + json!({"type": "frame", "name": "Card", "x": 0, "y": 0, "width": 200, "height": 40, + "props": {"layout": "vertical", "gap": 8, "padding": 8, "fill": "#FFFFFF"}}), + )); + ex(&mut s, "text.create", json!({"text": "Row one", "parent": f})); + ex(&mut s, "text.create", json!({"text": "Row two", "parent": f})); + let only = json!(["layout.clipped"]); + let r = ex(&mut s, "design.audit", json!({"scope": "page", "rules": &only})); + assert!(has(&r, "layout.clipped"), "{r}"); + let finding = r["findings"].as_array().unwrap().iter().find(|f| f["rule"] == "layout.clipped").unwrap(); + assert_eq!(finding["fixable"], false, "{r}"); + assert_eq!(finding["suggestion"]["sizingV"], "hug", "{r}"); + // A frame that hugs grows with its rows, so it cannot clip. + ex(&mut s, "node.set", json!({"id": f, "props": {"sizingV": "hug"}})); + let after = ex(&mut s, "design.audit", json!({"scope": "page", "rules": &only})); + assert!(rules(&after).is_empty(), "{after}"); +} + +#[test] +fn a_plain_clipping_frame_is_not_a_layout_finding() { + let mut s = Session::new(); + let f = id(&ex( + &mut s, + "node.create", + json!({"type": "frame", "name": "Crop", "x": 0, "y": 0, "width": 200, "height": 40, + "props": {"fill": "#FFFFFF"}}), + )); + // A manual frame clipping its artwork is a crop, not a layout mistake: `sizingV` cannot fix it. + ex(&mut s, "node.create", json!({"type": "rectangle", "parent": f, "x": 0, "y": 30, "width": 200, "height": 40})); + let only = json!(["layout.clipped"]); + let r = ex(&mut s, "design.audit", json!({"scope": "page", "rules": &only})); + assert!(rules(&r).is_empty(), "clipping a manual frame is intentional: {r}"); +} + +#[test] +fn an_auto_layout_frame_hugs_the_axes_no_size_names() { + let mut s = Session::new(); + let f = id(&ex( + &mut s, + "node.create", + json!({"type": "frame", "name": "Card", "x": 0, "y": 0, "props": {"layout": "vertical", "gap": 8, "padding": 8}}), + )); + ex(&mut s, "text.create", json!({"text": "Row one", "parent": f})); + ex(&mut s, "text.create", json!({"text": "Row two", "parent": f})); + let n = s.doc().unwrap().node(f).unwrap(); + assert_eq!(n.child_layout.sizing_h, Sizing::Hug); + assert_eq!(n.child_layout.sizing_v, Sizing::Hug); + assert!(n.height > 40.0 && n.height < 90.0, "hug height fits the rows, got {}", n.height); + // An explicit width stays fixed; the unnamed height hugs. + let g = id(&ex( + &mut s, + "node.create", + json!({"type": "frame", "name": "Bar", "x": 300, "y": 0, "width": 320, "props": {"layout": "vertical", "gap": 8}}), + )); + let n = s.doc().unwrap().node(g).unwrap(); + assert_eq!(n.child_layout.sizing_h, Sizing::Fixed); + assert_eq!(n.child_layout.sizing_v, Sizing::Hug); + // No auto layout: the 100×100 defaults stay. + let p = id(&ex(&mut s, "node.create", json!({"type": "frame", "name": "Plain", "x": 700, "y": 0}))); + let n = s.doc().unwrap().node(p).unwrap(); + assert_eq!(n.child_layout.sizing_h, Sizing::Fixed); + assert_eq!(n.width, 100.0); + // A size in props is explicit too: it keeps that axis fixed and the other one hugs. + let q = id(&ex( + &mut s, + "node.create", + json!({"type": "frame", "name": "Props height", "x": 1000, "y": 0, + "props": {"layout": "vertical", "height": 300}}), + )); + let n = s.doc().unwrap().node(q).unwrap(); + assert_eq!(n.height, 300.0); + assert_eq!(n.child_layout.sizing_v, Sizing::Fixed); + assert_eq!(n.child_layout.sizing_h, Sizing::Hug); + let r = id(&ex( + &mut s, + "node.create", + json!({"type": "frame", "name": "Props width", "x": 1000, "y": 400, + "props": {"layout": "vertical", "w": 320}}), + )); + let n = s.doc().unwrap().node(r).unwrap(); + assert_eq!(n.width, 320.0); + assert_eq!(n.child_layout.sizing_h, Sizing::Fixed); + assert_eq!(n.child_layout.sizing_v, Sizing::Hug); +} + +#[test] +fn an_icons_stroke_is_not_a_border() { + let mut s = Session::new(); + ex( + &mut s, + "node.create", + json!({"type": "vector", "name": "Chevron", "x": 0, "y": 0, "points": [[0, 0], [8, 8], [0, 16]], + "props": {"stroke": "#6B7280", "strokeWeight": 1.5, "fills": []}}), + ); + let only = json!(["color.border-opacity"]); + let r = ex(&mut s, "design.audit", json!({"scope": "page", "rules": &only})); + assert!(rules(&r).is_empty(), "an icon's stroke is its drawing, not a border: {r}"); + ex( + &mut s, + "node.create", + json!({"type": "rectangle", "name": "Panel", "x": 100, "y": 0, "width": 48, "height": 48, + "props": {"fills": [], "stroke": "#6B7280", "strokeWeight": 1.5}}), + ); + let r = ex(&mut s, "design.audit", json!({"scope": "page", "rules": &only})); + assert!(has(&r, "color.border-opacity"), "{r}"); +} + +#[test] +fn a_bad_parent_error_names_the_node() { + let mut s = Session::new(); + let t = id(&ex(&mut s, "text.create", json!({"text": "Label", "x": 0, "y": 0}))); + let err = s.execute("node.create", &json!({"type": "rectangle", "parent": t, "x": 0, "y": 0})).unwrap_err().to_string(); + assert!(err.contains("TEXT \"Label\""), "{err}"); + assert!(err.contains("can't contain"), "{err}"); +} diff --git a/crates/engine/src/inspect_fields_tests.rs b/crates/engine/src/inspect_fields_tests.rs index 2083a5108..b7b93fd0d 100644 --- a/crates/engine/src/inspect_fields_tests.rs +++ b/crates/engine/src/inspect_fields_tests.rs @@ -116,6 +116,7 @@ fn empty_options_keep_the_main_tree_and_document_output() { "fontFamily": "Synthetic", "fontSize": 18.0, "fontStyle": "Bold", + "fontWeight": 700, "height": 24.0, "id": 3, "letterSpacing": "1", diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 302e7053e..ca5feaa32 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -16,6 +16,7 @@ mod canvas; pub mod catalog; pub mod cmd; mod content; +mod design; mod dev; pub mod events; mod extensions; diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index 48d68a901..b2200777a 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -106,6 +106,9 @@ pub struct Prefs { /// files opened or made later start with them. Missing: the toggle's default. #[serde(skip_serializing_if = "BTreeMap::is_empty")] pub view: BTreeMap, + /// Design review ignores, by document path: whole rule ids and `rule@layer` entries. + #[serde(skip_serializing_if = "BTreeMap::is_empty")] + pub design_review_ignored: BTreeMap>, /// The board canvas's background grid (`board.grid`). #[serde(deserialize_with = "crate::board_grid::read")] pub board_grid: crate::board_grid::BoardGrid, @@ -158,6 +161,7 @@ impl Default for Prefs { home_sort: "modified".into(), home_order: "desc".into(), view: BTreeMap::new(), + design_review_ignored: BTreeMap::new(), board_grid: Default::default(), recent_actions: Vec::new(), team_libraries: Vec::new(), diff --git a/crates/mcp/src/prompts.rs b/crates/mcp/src/prompts.rs index 59b4ee818..12b74e448 100644 --- a/crates/mcp/src/prompts.rs +++ b/crates/mcp/src/prompts.rs @@ -18,7 +18,7 @@ pub struct PromptDef { pub defaults: &'static [(&'static str, &'static str)], } -const VERIFY: &str = "\n\nVerify as you go: after each major step call inspect_document (or get_node on the frame) and check sizes, fills, layout and text; call screenshot at the end and look at it. Fix anything that is off before finishing, then report the ids of the frames you made."; +const VERIFY: &str = "\n\nVerify as you go: after each major step call inspect_document (or get_node on the frame) and check sizes, fills, layout and text. Before finishing, run design.audit on the target you were asked to change — the requested selection or page, or the frames you created — not the rest of the document, and fix every high finding you are permitted to repair, running it again until none are left (run_command design.rules lists the checks). Call screenshot at the end and look at it. Fix anything that is off, then report the ids of the frames you made."; pub const PROMPTS: &[PromptDef] = &[ PromptDef { @@ -30,7 +30,7 @@ pub const PROMPTS: &[PromptDef] = &[ PromptArg { name: "device", description: "Frame preset (default \"iPhone 16\"; see run_command frame.presets)", required: false }, PromptArg { name: "brand_color", description: "Primary colour (default #3B5BDB)", required: false }, ], - template: "Design a {screen} screen for a mobile app in FigCraft.\n\n1. run_command frame.create {\"preset\": \"{device}\", \"x\": 0, \"y\": 0, \"name\": \"{screen}\"} and give it a white fill.\n2. set_properties on the frame: {\"layout\": \"vertical\", \"padding\": [64, 24, 32, 24], \"gap\": 16, \"sizingV\": \"fixed\"}.\n3. Add content with create_node using parent = the frame id: a title (text, fontSize 28, fontStyle Bold), supporting text (fontSize 16, colour #555555), inputs or list rows (frames with layout horizontal, padding 16, cornerRadius 12, stroke #E0E0E0, sizingH fill) and a primary button (frame, layout horizontal, mainAlign center, padding [14,24,14,24], cornerRadius 12, fill {brand_color}, sizingH fill, white Bold text inside).\n4. Keep spacing on an 8-point grid and text left-aligned.{verify}", + template: "Design a {screen} screen for a mobile app in FigCraft.\n\n1. run_command frame.create {\"preset\": \"{device}\", \"x\": 0, \"y\": 0, \"name\": \"{screen}\"} and give it a white fill.\n2. set_properties on the frame: {\"layout\": \"vertical\", \"padding\": [64, 24, 32, 24], \"gap\": 16, \"sizingV\": \"fixed\"}.\n3. Add content with create_node using parent = the frame id: a title (text, fontSize 28, fontStyle Semi Bold), supporting text (fontSize 16, colour #555555), inputs or list rows (frames with layout horizontal, padding 16, cornerRadius 12, stroke #E0E0E0, sizingH fill) and a primary button (frame, layout horizontal, mainAlign center, padding [16,24,16,24], cornerRadius 12, fill {brand_color}, sizingH fill, white Semi Bold text inside). Name every layer by what it is.\n4. Keep spacing on an 8-point grid, text left-aligned, and no emoji in the interface.{verify}", defaults: &[("device", "iPhone 16"), ("brand_color", "#3B5BDB")], }, PromptDef { @@ -41,7 +41,7 @@ pub const PROMPTS: &[PromptDef] = &[ PromptArg { name: "name", description: "Design system name (default \"Core\")", required: false }, PromptArg { name: "primary", description: "Primary colour (default #3B5BDB)", required: false }, ], - template: "Set up the \"{name}\" design system in FigCraft.\n\n1. Variables: run_command variable.createCollection {\"name\": \"{name} colours\", \"modes\": [\"Light\", \"Dark\"]}, then variable.create for color/bg, color/fg and color/primary with values per mode ({\"values\": {\"Light\": …, \"Dark\": …}}); primary is {primary} in Light.\n2. Paint styles: create a swatch rectangle per colour and run style.create {\"type\": \"paint\", \"name\": \"{name}/Primary\", \"from\": }; text styles likewise from text layers (Heading 32 Bold, Body 16 Regular, Caption 12).\n3. Button component: a frame with auto layout (horizontal, padding [12,20,12,20], cornerRadius 8, mainAlign center) containing a text \"Button\"; style.apply the primary paint style; component.create on it. Make a secondary variant (duplicate, outline style), then component.combineVariants on both.\n4. Bind the button fill to color/primary with variable.bind {\"ids\": [..], \"field\": \"fill\", \"variable\": } and check both modes by variable.setMode on a frame.\n5. list_commands with filter \"style\" or \"variable\" shows the exact params.{verify}", + template: "Set up the \"{name}\" design system in FigCraft.\n\n1. Variables: run_command variable.createCollection {\"name\": \"{name} colours\", \"modes\": [\"Light\", \"Dark\"]}, then variable.create for color/bg, color/fg and color/primary with values per mode ({\"values\": {\"Light\": …, \"Dark\": …}}); primary is {primary} in Light.\n2. Paint styles: create a swatch rectangle per colour and run style.create {\"type\": \"paint\", \"name\": \"{name}/Primary\", \"from\": }; text styles likewise from text layers (Heading 32 Semi Bold, Body 16 Regular, Caption 12).\n3. Button component: a frame with auto layout (horizontal, padding [12,20,12,20], cornerRadius 8, mainAlign center) containing a text \"Button\"; style.apply the primary paint style; component.create on it. Make a secondary variant (duplicate, outline style), then component.combineVariants on both.\n4. Bind the button fill to color/primary with variable.bind {\"ids\": [..], \"field\": \"fill\", \"variable\": } and check both modes by variable.setMode on a frame.\n5. list_commands with filter \"style\" or \"variable\" shows the exact params.{verify}", defaults: &[("name", "Core"), ("primary", "#3B5BDB")], }, PromptDef { @@ -51,10 +51,18 @@ pub const PROMPTS: &[PromptDef] = &[ args: &[ PromptArg { name: "product", description: "What the page sells", required: true }, PromptArg { name: "width", description: "Page width (default 1440)", required: false }, - PromptArg { name: "accent", description: "Accent colour (default #7048E8)", required: false }, + PromptArg { name: "accent", description: "Accent colour (default #2563EB)", required: false }, ], - template: "Design a landing page for {product} in FigCraft.\n\n1. create_node a frame {\"type\": \"frame\", \"x\": 0, \"y\": 0, \"width\": {width}, \"height\": 2400, \"name\": \"Landing\", \"props\": {\"fill\": \"#FFFFFF\", \"layout\": \"vertical\", \"gap\": 0}}.\n2. Sections are child frames with sizingH fill and their own auto layout: Nav (horizontal, spaceBetween, padding [20,80,20,80]); Hero (vertical, center, padding 120, gap 24: a 64px Bold headline, an 20px subhead, a CTA button filled {accent}); Features (horizontal, gap 32, padding 80: three cards with cornerRadius 16, padding 32, a soft dropShadow effect, title + body text, each sizingH fill); CTA band filled {accent} with white text; Footer (padding 40, small grey text).\n3. Use batch to apply repeated styling to several ids in one undo step.\n4. Finish with sizingV hug on the page frame so it fits its content.{verify}", - defaults: &[("width", "1440"), ("accent", "#7048E8")], + template: "Design a landing page for {product} in FigCraft.\n\n1. create_node a frame {\"type\": \"frame\", \"x\": 0, \"y\": 0, \"width\": {width}, \"height\": 2400, \"name\": \"Landing\", \"props\": {\"fill\": \"#FFFFFF\", \"layout\": \"vertical\", \"gap\": 0}}.\n2. Sections are child frames with sizingH fill and their own auto layout: Nav (horizontal, spaceBetween, padding [20,80,20,80]); Hero (vertical, center, padding 120, gap 24: a 64px Semi Bold headline, a 20px subhead, a CTA button filled {accent}); Features (horizontal, gap 32, padding 80: three cards with cornerRadius 16, padding 32, a soft neutral dropShadow, title + body text, each sizingH fill); CTA band filled {accent} with white text; Footer (padding 40, small grey text, no lower than #6B7280).\n3. Name every layer by what it is. Use one accent, one neutral ramp and at most three text colours; no emoji, gradient text or glows.\n4. Use batch to apply repeated styling to several ids in one undo step.\n5. Finish with sizingV hug on the page frame so it fits its content.{verify}", + defaults: &[("width", "1440"), ("accent", "#2563EB")], + }, + PromptDef { + name: "design_review", + title: "Review a design", + description: "Audit the selection, page or document for the usual AI-generated UI tells, fix the mechanical ones, then use judgment for copy, naming, gradients and overflow; re-audit and report what a person still has to decide.", + args: &[PromptArg { name: "target", description: "selection, page or document (default page)", required: false }], + template: "Review and finish the design in this FigCraft document.\n\n1. Read the screen first with inspect_document and note the product and audience from its text. Write a five-line direction before editing: product (one plain sentence), character (two or three concrete words, never clean/modern/minimal), world (the material or place it belongs to), moments (one or two places for colour, material and detail), signature (one small recurring detail). Do not change what the product is, its features or its section order, and keep every claim true.\n2. Run run_command {\"command\": \"design.audit\", \"params\": {\"scope\": \"{target}\"}}. `design.rules` lists the checks.\n3. Repair what arithmetic can: run run_command {\"command\": \"design.fix\", \"params\": {\"scope\": \"{target}\"}} (one undo step), then audit again. A finding marked `fixable: false`, or one whose message says it is bound to a style or variable, belongs to the design system: leave it and name it in the report.\n4. Handle what the audit cannot, worst first, with the smallest edit and one batch per area: rewrite exclamation, hype and greeting copy into specific product copy; name default layers by what they are; replace hue gradients and gradient text with a solid from the direction unless the brand owns them; resize or reflow a box whose text overflows. If the whole screen is generic, change spacing, type and one moment of colour or material — not the structure. Do not invent features, data or claims.\n5. Run design.audit again until no high findings are left that steps 3 and 4 can repair. Stop when no permitted repair remains. Report the score and counts before and after, the direction, what you fixed mechanically, what you fixed by judgment, and every finding you left with its reason.{verify}\n6. Take a screenshot of the frame you changed and look at it.", + defaults: &[("target", "page")], }, PromptDef { name: "prototype_flow", diff --git a/crates/mcp/src/server.rs b/crates/mcp/src/server.rs index 70ac05999..78be68cec 100644 --- a/crates/mcp/src/server.rs +++ b/crates/mcp/src/server.rs @@ -42,8 +42,12 @@ screenshot returns a PNG of the page or of given layers to look at. undo/redo st Comments: comment.list returns threads (text, anchor node id, frame, page, x/y, replies); fix open ones, \ reply with what changed, then resolve (a reply reopens a thread). To react to new feedback, call \ wait_for_changes {after, timeoutMs} and pass the returned cursor back. \ +Design review: design.audit {scope} reports spacing, radii, type, colour, contrast, copy and naming findings \ +with severities; design.fix repairs the fixable ones as one undo step; design.rules lists the rules and \ +presets; design.configure {preset, grid, radii, brand, disabled} sets the file's design system, and \ +design.assert {failOn, minScore} is a read-only CI gate. \ Resources: figcraft://document, figcraft://node/{id}, figcraft://command/{id}, figcraft://comments. \ -prompts/list has workflows, including fix_comments."; +prompts/list has workflows, including fix_comments and design_review."; /// An MCP server bound to one backend. pub struct Server { diff --git a/crates/mcp/tests/it/protocol.rs b/crates/mcp/tests/it/protocol.rs index cadadbad0..1e83e5646 100644 --- a/crates/mcp/tests/it/protocol.rs +++ b/crates/mcp/tests/it/protocol.rs @@ -219,13 +219,16 @@ fn prompts_list_and_get() { let mut c = Client::new(); let r = c.rpc("prompts/list", json!({})); let names: Vec<&str> = r["result"]["prompts"].as_array().unwrap().iter().map(|p| p["name"].as_str().unwrap()).collect(); - assert_eq!(names, ["mobile_screen", "design_system", "landing_page", "prototype_flow", "fix_comments", "watch_comments"]); + assert_eq!(names, ["mobile_screen", "design_system", "landing_page", "design_review", "prototype_flow", "fix_comments", "watch_comments"]); let r = c.rpc("prompts/get", json!({"name": "mobile_screen", "arguments": {"screen": "login"}})); let text = r["result"]["messages"][0]["content"]["text"].as_str().unwrap(); assert!(text.contains("login") && text.contains("iPhone 16") && text.contains("#3B5BDB") && !text.contains("{device}")); assert_eq!(c.rpc("prompts/get", json!({"name": "mobile_screen"}))["error"]["code"], -32602); assert_eq!(c.rpc("prompts/get", json!({"name": "nope"}))["error"]["code"], -32602); assert_eq!(c.rpc("prompts/get", json!({"name": "landing_page", "arguments": {"product": ["x"]}}))["error"]["code"], -32602); + let r = c.rpc("prompts/get", json!({"name": "design_review", "arguments": {"target": "document"}})); + let text = r["result"]["messages"][0]["content"]["text"].as_str().unwrap(); + assert!(text.contains("design.audit") && text.contains("\"document\"") && !text.contains("{target}"), "{text}"); let r = c.rpc("prompts/get", json!({"name": "prototype_flow"})); assert!(r["result"]["messages"][0]["content"]["text"].as_str().unwrap().contains("Home, Details, Checkout")); let r = c.rpc("prompts/get", json!({"name": "fix_comments", "arguments": {"auto_resolve": "no", "author": "Ada"}}));