mirror of
https://github.com/storytold/figcraft.git
synced 2026-11-29 17:55:59 +01:00
M13: design review commands (engine and MCP)
This commit is contained in:
1 parent
a2e87433d8
commit
1959fc3d71
17 files changed
+3183
-12
No files matched your search
@@ -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<Self> {
|
||||
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<f64>,
|
||||
/// The brand's accent colours: they don't count as stray accents (`color.accents`).
|
||||
pub brand: Vec<Color>,
|
||||
/// Rule ids this file turns off.
|
||||
pub disabled: Vec<String>,
|
||||
}
|
||||
|
||||
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());
|
||||
}
|
||||
}
|
||||
@@ -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<ImagePreset>,
|
||||
/// 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<Vec<AnnotationCategory>>,
|
||||
@@ -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,
|
||||
|
||||
@@ -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<String, Value>, 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));
|
||||
|
||||
@@ -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());
|
||||
|
||||
@@ -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<CommandSpec> {
|
||||
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<Value> {
|
||||
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<Value> {
|
||||
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];
|
||||
|
||||
@@ -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), \
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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<NodeId>,
|
||||
anchor_path: &str,
|
||||
scope: &str,
|
||||
preset: Option<DesignPreset>,
|
||||
filter: Option<&BTreeSet<String>>,
|
||||
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::<f64>()).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<bool> {
|
||||
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<bool> {
|
||||
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<bool> {
|
||||
// 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<bool> {
|
||||
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<bool> {
|
||||
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<bool> {
|
||||
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<bool> {
|
||||
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<bool> {
|
||||
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)
|
||||
}
|
||||
@@ -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<CommandSpec> {
|
||||
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::<Vec<_>>(),
|
||||
"presets": DesignPreset::ALL.iter().map(|p| json!({
|
||||
"id": p.id(),
|
||||
"description": preset_description(*p),
|
||||
})).collect::<Vec<_>>(),
|
||||
}))
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
fn audit_cmd(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
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<Value> {
|
||||
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<Value> {
|
||||
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<String> = 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<Severity> {
|
||||
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<Option<DesignPreset>> {
|
||||
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<BTreeMap<CollectionId, ModeId>> {
|
||||
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<Value> {
|
||||
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<String> = 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<NodeId>, Option<NodeId>, 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<NodeId>, &'static str, Option<NodeId>, 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<Option<String>> {
|
||||
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<Severity> {
|
||||
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<Option<BTreeSet<String>>> {
|
||||
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<NodeId> {
|
||||
let mut out: Vec<NodeId> = 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))
|
||||
}
|
||||
@@ -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<Self> {
|
||||
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()
|
||||
}
|
||||
@@ -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<String> {
|
||||
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<u64> {
|
||||
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<u64> = 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}");
|
||||
}
|
||||
@@ -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",
|
||||
|
||||
@@ -16,6 +16,7 @@ mod canvas;
|
||||
pub mod catalog;
|
||||
pub mod cmd;
|
||||
mod content;
|
||||
mod design;
|
||||
mod dev;
|
||||
pub mod events;
|
||||
mod extensions;
|
||||
|
||||
@@ -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<String, bool>,
|
||||
/// 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<String, Vec<String>>,
|
||||
/// 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(),
|
||||
|
||||
@@ -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\": <id>}; 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\": <id>} 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\": <id>}; 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\": <id>} 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",
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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"}}));
|
||||
|
||||
Reference in new issue
Block a user