mirror of
https://github.com/storytold/figcraft.git
synced 2026-11-29 01:34:37 +01:00
Merge branch 'main' into formats/penpot-craft-zip-9-8-2
This commit is contained in:
commit
a992fdeb74
11 files changed
+737
-4
No files matched your search
@@ -366,6 +366,7 @@ Ranked; detail and milestones in [`docs/roadmap.md`](docs/roadmap.md).
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-11-27 | minor | M8: visual verification for agents. `inspect.compare` and the MCP tool `compare_design` compare a capture of a built page, made by the agent's own browser tools, with a frame, on this computer: the layers that differ, deepest and largest first, each a position (with its offset), colour (expected and actual) or content difference, with text held to twice the tolerance. A retina capture is the same design. Numbers unchanged. Tests: `visual_compare_tests`, MCP `compare_design`. |
|
||||
| 2026-11-26 | minor | #1396, craft-contrib#95: `figcraft-cli` follows RFC-0018. The CLI is a library with `run(args, out, err)` (`main` is a thin wrapper), failures are typed errors (exit 1, usage errors exit 2), output goes through the caller's writers, a closed stdout is quiet, `-V` works after subcommands, `FIGCRAFT_NO_SYSTEM_FONTS` and `FIGCRAFT_SERVER_KEY` are declared on `--no-system-fonts` and `plugin publish --key`, the packages install the man pages and Bash, Zsh and Fish completions (Linux and FreeBSD). Changed behaviour: `convert`/`run` refuse an output that is the input unless `--in-place` is given (it needs `--in`/`--out`); `export -o` and `render -o` refuse the file they read; `plugin publish` accepts `--key`; a blank `FIGCRAFT_NO_SYSTEM_FONTS` counts as unset and an unrecognised value is a usage error. Tests in `apps/figcraft-cli/tests/it/rfc18.rs`. Numbers unchanged |
|
||||
| 2026-11-24 | minor | M7: New York, Apple's serif that macOS installs as the hidden `.New York`, is found and listed under its public name (it was a missing font). Numbers unchanged. |
|
||||
| 2026-11-15 | patch | Removed the obsolete duplicate live-session bullet from the browser crate docs; the existing server publishing and remote wss guidance remains authoritative. Runtime behavior unchanged. |
|
||||
|
||||
@@ -103,6 +103,7 @@ fn registry() -> &'static Registry {
|
||||
list.extend(crate::design_context::specs());
|
||||
list.extend(crate::asset_handoff::specs());
|
||||
list.extend(crate::responsive::specs());
|
||||
list.extend(crate::visual_compare::specs());
|
||||
list.extend(crate::component_codegen::specs());
|
||||
list.extend(crate::playground::specs());
|
||||
list.extend(crate::code_connect::specs());
|
||||
|
||||
@@ -10,3 +10,4 @@ pub mod devcompare;
|
||||
pub mod devinspect;
|
||||
pub mod responsive;
|
||||
pub mod tailwind;
|
||||
pub mod visual_compare;
|
||||
@@ -0,0 +1,368 @@
|
||||
//! Compare a capture of a built page with the design (`inspect.compare`, the MCP tool
|
||||
//! `compare_design`). A browser's text and antialiasing never match pixel for pixel, so the answer
|
||||
//! isn't one score: it is the layers that differ, each with what kind of difference it looks like,
|
||||
//! deepest first so a difference is reported once. It runs here, on the computer, on a capture the
|
||||
//! developer's own tools made.
|
||||
|
||||
use figcraft_doc::{Document, NodeId, NodeKind};
|
||||
use figcraft_geom::Rect;
|
||||
use figcraft_render::Pixmap;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::cmd::CommandSpec;
|
||||
use crate::cmd::file::read_capped;
|
||||
use crate::params::{get, req_targets, string};
|
||||
use crate::{Result, Session, bad, spec};
|
||||
|
||||
/// Largest capture read (bytes).
|
||||
const MAX_CAPTURE: u64 = 256 << 20;
|
||||
/// The largest side compared: bigger images are compared at this size.
|
||||
const MAX_SIDE: u32 = 2_000;
|
||||
/// How far (in compared pixels) a layer may have moved to count as moved.
|
||||
const MAX_SHIFT: i32 = 16;
|
||||
/// How different a pixel's channels must be to count, out of 255.
|
||||
const DEFAULT_TOLERANCE: f64 = 24.0;
|
||||
/// Text differs between renderers even when it's right: it needs this many times the tolerance.
|
||||
const TEXT_FACTOR: f64 = 2.0;
|
||||
/// The share of a layer's own pixels that must differ for it to be reported.
|
||||
const MIN_SHARE: f64 = 0.02;
|
||||
/// Most differences listed.
|
||||
const MAX_LISTED: usize = 100;
|
||||
/// Most layers looked at.
|
||||
const MAX_LAYERS: usize = 5_000;
|
||||
/// Most layers whose drawn shape is worked out; past it, a layer is matched by its box.
|
||||
const MAX_DRAWN: usize = 300;
|
||||
/// Longest `data` read (base64 characters): [`MAX_CAPTURE`] encoded, checked before decoding.
|
||||
const MAX_DATA: usize = (MAX_CAPTURE as usize / 3 + 1) * 4;
|
||||
|
||||
/// Straight RGB over white, in a grid of `w` × `h`.
|
||||
struct Image {
|
||||
w: usize,
|
||||
h: usize,
|
||||
rgb: Vec<[f32; 3]>,
|
||||
}
|
||||
|
||||
impl Image {
|
||||
/// `p` box-filtered to `w` × `h`, which also smooths away most antialiasing.
|
||||
fn from(p: &Pixmap, w: usize, h: usize) -> Self {
|
||||
let (pw, ph) = (p.width() as usize, p.height() as usize);
|
||||
let data = p.data();
|
||||
let mut rgb = Vec::with_capacity(w * h);
|
||||
for y in 0..h {
|
||||
let (y0, y1) = (y * ph / h, ((y + 1) * ph / h).max(y * ph / h + 1).min(ph));
|
||||
for x in 0..w {
|
||||
let (x0, x1) = (x * pw / w, ((x + 1) * pw / w).max(x * pw / w + 1).min(pw));
|
||||
let mut sum = [0f32; 3];
|
||||
let mut count = 0f32;
|
||||
for sy in y0..y1 {
|
||||
for sx in x0..x1 {
|
||||
let Some(px) = data.get((sy * pw + sx) * 4..(sy * pw + sx) * 4 + 4) else { continue };
|
||||
// Premultiplied: over white adds what the alpha lets through.
|
||||
let rest = 255.0 - f32::from(px[3]);
|
||||
for (s, c) in sum.iter_mut().zip(px) {
|
||||
*s += f32::from(*c) + rest;
|
||||
}
|
||||
count += 1.0;
|
||||
}
|
||||
}
|
||||
rgb.push(sum.map(|v| v / count.max(1.0)));
|
||||
}
|
||||
}
|
||||
Self { w, h, rgb }
|
||||
}
|
||||
|
||||
fn at(&self, x: i32, y: i32) -> Option<&[f32; 3]> {
|
||||
(x >= 0 && y >= 0 && (x as usize) < self.w && (y as usize) < self.h).then(|| self.rgb.get(y as usize * self.w + x as usize)).flatten()
|
||||
}
|
||||
}
|
||||
|
||||
/// How far apart two colours are: their most different channel.
|
||||
fn delta(a: &[f32; 3], b: &[f32; 3]) -> f32 {
|
||||
a.iter().zip(b).map(|(x, y)| (x - y).abs()).fold(0.0, f32::max)
|
||||
}
|
||||
|
||||
/// A rectangle of the grid: x0, y0, x1, y1.
|
||||
type Area = (i32, i32, i32, i32);
|
||||
|
||||
/// The mean colour of `area` in `img` as hex.
|
||||
fn mean(img: &Image, (x0, y0, x1, y1): Area) -> Option<String> {
|
||||
let (mut sum, mut n) = ([0f32; 3], 0f32);
|
||||
for y in y0..y1 {
|
||||
for x in x0..x1 {
|
||||
if let Some(c) = img.at(x, y) {
|
||||
for (s, v) in sum.iter_mut().zip(c) {
|
||||
*s += v;
|
||||
}
|
||||
n += 1.0;
|
||||
}
|
||||
}
|
||||
}
|
||||
(n > 0.0).then(|| format!("#{:02X}{:02X}{:02X}", (sum[0] / n) as u8, (sum[1] / n) as u8, (sum[2] / n) as u8))
|
||||
}
|
||||
|
||||
/// How much `area` of the design differs from the capture moved by `dx`, `dy`, sampled.
|
||||
fn cost(design: &Image, capture: &Image, (x0, y0, x1, y1): Area, dx: i32, dy: i32) -> f32 {
|
||||
let step = (((x1 - x0) * (y1 - y0)) / 4_000).clamp(1, 16);
|
||||
let (mut sum, mut n) = (0f32, 0f32);
|
||||
for y in (y0..y1).step_by(step as usize) {
|
||||
for x in (x0..x1).step_by(step as usize) {
|
||||
if let (Some(a), Some(b)) = (design.at(x, y), capture.at(x + dx, y + dy)) {
|
||||
sum += delta(a, b);
|
||||
n += 1.0;
|
||||
}
|
||||
}
|
||||
}
|
||||
if n > 0.0 { sum / n } else { f32::MAX }
|
||||
}
|
||||
|
||||
/// Where `area` of the design best matches the capture, if a move explains it.
|
||||
fn moved(design: &Image, capture: &Image, area: Area, tolerance: f32) -> Option<(i32, i32)> {
|
||||
let here = cost(design, capture, area, 0, 0);
|
||||
let mut best = (here, 0, 0);
|
||||
for dy in -MAX_SHIFT..=MAX_SHIFT {
|
||||
for dx in -MAX_SHIFT..=MAX_SHIFT {
|
||||
let c = cost(design, capture, area, dx, dy);
|
||||
if c < best.0 {
|
||||
best = (c, dx, dy);
|
||||
}
|
||||
}
|
||||
}
|
||||
(best.0 < here / 2.0 && best.0 < tolerance).then_some((best.1, best.2))
|
||||
}
|
||||
|
||||
/// The visible layers under `id`, parents first, at most [`MAX_LAYERS`] (without recursion, so a
|
||||
/// deep tree can't overflow the stack); and whether some were left out.
|
||||
fn visible(doc: &Document, id: NodeId) -> (Vec<NodeId>, bool) {
|
||||
let (mut out, mut stack) = (Vec::new(), vec![id]);
|
||||
while let Some(c) = stack.pop() {
|
||||
let Some(n) = doc.node(c) else { continue };
|
||||
if !n.visible {
|
||||
continue;
|
||||
}
|
||||
if out.len() >= MAX_LAYERS {
|
||||
return (out, true);
|
||||
}
|
||||
out.push(c);
|
||||
stack.extend(n.children.iter().rev());
|
||||
}
|
||||
(out, false)
|
||||
}
|
||||
|
||||
/// The cells of `area` (a grid of `per` cells to a CSS pixel from `origin`) that layer `id` draws
|
||||
/// on, from its own drawing: what it leaves see-through (an ellipse's corners, the space around
|
||||
/// glyphs) stays with the layers under it. `None` when it can't be drawn.
|
||||
fn coverage(doc: &Document, id: NodeId, origin: (f64, f64), per: f64, (x0, y0, x1, y1): Area) -> Option<Vec<bool>> {
|
||||
let (w, h) = (usize::try_from(x1 - x0).ok()?, usize::try_from(y1 - y0).ok()?);
|
||||
if w == 0 || h == 0 {
|
||||
return Some(Vec::new());
|
||||
}
|
||||
let at = |cell: i32, o: f64| o + f64::from(cell) / per;
|
||||
let page = Rect::new(at(x0, origin.0), at(y0, origin.1), at(x1, origin.0), at(y1, origin.1));
|
||||
let drawn = figcraft_render::render_area(doc, &[id], page, per)?;
|
||||
let (pw, ph) = (drawn.width() as usize, drawn.height() as usize);
|
||||
let data = drawn.data();
|
||||
let span = |i: usize, n: usize, of: usize| (i * of / n, ((i + 1) * of / n).max(i * of / n + 1).min(of));
|
||||
let mut out = Vec::with_capacity(w * h);
|
||||
for y in 0..h {
|
||||
let (sy0, sy1) = span(y, h, ph);
|
||||
for x in 0..w {
|
||||
let (sx0, sx1) = span(x, w, pw);
|
||||
out.push((sy0..sy1).any(|sy| (sx0..sx1).any(|sx| data.get((sy * pw + sx) * 4 + 3).is_some_and(|a| *a > 0))));
|
||||
}
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// Number parameter `key`: `None` when left out; anything but a number is refused.
|
||||
fn number(cmd: &str, p: &Value, key: &str) -> Result<Option<f64>> {
|
||||
match get(p, key) {
|
||||
None => Ok(None),
|
||||
Some(Value::Number(n)) => Ok(n.as_f64()),
|
||||
Some(_) => Err(bad(cmd, format!("`{key}` must be a number"))),
|
||||
}
|
||||
}
|
||||
|
||||
fn compare(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "inspect.compare";
|
||||
// Everything but the capture first: it's the costly part.
|
||||
let id = match req_targets(cmd, s, p)?.as_slice() {
|
||||
[id] => *id,
|
||||
[] => return Err(bad(cmd, "select the frame to compare with")),
|
||||
_ => return Err(bad(cmd, "compare one frame at a time")),
|
||||
};
|
||||
// A page is built from a frame, a component or an instance of one. Any other layer would still
|
||||
// give a result, and it would look like a real answer: refuse it instead.
|
||||
let target = s.doc()?.get(id)?;
|
||||
if !target.kind.is_frame_like() || matches!(target.kind, NodeKind::ComponentSet { .. }) {
|
||||
let kind = target.kind.type_name().to_lowercase();
|
||||
return Err(bad(cmd, format!("{:?} is a {kind}: compare a frame, component or instance", target.name)));
|
||||
}
|
||||
let (density, tolerance) = (number(cmd, p, "density")?, number(cmd, p, "tolerance")?);
|
||||
let bytes = match (get(p, "data"), string(p, "path")) {
|
||||
(Some(_), Some(_)) => return Err(bad(cmd, "pass `path` or `data`, not both")),
|
||||
(Some(Value::String(d)), None) => {
|
||||
use base64::Engine as _;
|
||||
let d = d.trim();
|
||||
if d.len() > MAX_DATA {
|
||||
return Err(bad(cmd, format!("data: a capture up to {} MB", MAX_CAPTURE >> 20)));
|
||||
}
|
||||
base64::engine::general_purpose::STANDARD.decode(d).map_err(|_| bad(cmd, "data: base64"))?
|
||||
}
|
||||
(Some(_), None) => return Err(bad(cmd, "data: a base64 string")),
|
||||
(None, Some(path)) => read_capped(&path, MAX_CAPTURE)?,
|
||||
(None, None) => return Err(bad(cmd, "pass `path` or `data`: a capture of the page")),
|
||||
};
|
||||
let capture = figcraft_render::images::decode(&bytes).ok_or_else(|| bad(cmd, "the capture isn't an image FigCraft can read"))?;
|
||||
let doc = s.doc()?;
|
||||
let root = doc.get(id)?;
|
||||
let bounds = doc.world_bounds(id).ok_or_else(|| bad(cmd, "the layer has no size"))?;
|
||||
let (fw, fh) = (bounds.width(), bounds.height());
|
||||
if !(fw > 0.0 && fh > 0.0) {
|
||||
return Err(bad(cmd, "the layer has no size"));
|
||||
}
|
||||
// A capture at 2x device pixels is the same design: the frame sets the scale.
|
||||
let density = density.filter(|d| d.is_finite() && *d > 0.0).unwrap_or_else(|| f64::from(capture.width()) / fw).clamp(0.1, 8.0);
|
||||
let tolerance = tolerance.filter(|t| t.is_finite()).unwrap_or(DEFAULT_TOLERANCE).clamp(1.0, 255.0) as f32;
|
||||
let (cw, ch) = (f64::from(capture.width()) / density, f64::from(capture.height()) / density);
|
||||
let same_size = (cw - fw).abs() < 1.0 && (ch - fh).abs() < 1.0;
|
||||
// Compared on the area both have, at one size.
|
||||
let (w, h) = (fw.min(cw), fh.min(ch));
|
||||
// Bounded by the larger of the two as well: both are gridded whole, so a capture far smaller
|
||||
// than the frame must not make the frame's grid (and its drawing) huge. No floor: a gigantic
|
||||
// frame just gets a coarser grid.
|
||||
let per = (f64::from(MAX_SIDE) / fw.max(fh).max(cw).max(ch)).min(density);
|
||||
// Every grid comes from `per` itself, never from a rounded overlap: one cell of a tiny capture
|
||||
// must not stand for thousands of the frame's.
|
||||
let cells = |css: f64| ((css * per).ceil() as usize).max(1);
|
||||
// Only the frame's own rectangle, as the capture holds it: not its export area, which takes in
|
||||
// strokes, effects and layers past an edge that doesn't clip. Drawn at twice the compared size
|
||||
// at most (enough to smooth its edges as the capture's are), not at the capture's density: a
|
||||
// tall page at 2x would be hundreds of megabytes.
|
||||
let drawn = figcraft_render::render_area(doc, &[id], bounds, density.min(per * 2.0)).ok_or_else(|| bad(cmd, "the layer can't be rendered"))?;
|
||||
let (gw, gh) = (cells(w), cells(h));
|
||||
let design = Image::from(&drawn, cells(fw), cells(fh));
|
||||
let shot = Image::from(&capture, cells(cw), cells(ch));
|
||||
let mut differing = vec![false; gw * gh];
|
||||
let mut changed = 0usize;
|
||||
for y in 0..gh {
|
||||
for x in 0..gw {
|
||||
if let (Some(a), Some(b)) = (design.at(x as i32, y as i32), shot.at(x as i32, y as i32))
|
||||
&& delta(a, b) > tolerance
|
||||
{
|
||||
changed += 1;
|
||||
if let Some(d) = differing.get_mut(y * gw + x) {
|
||||
*d = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let (layers, layers_cut) = visible(doc, id);
|
||||
let mut claimed = vec![false; gw * gh];
|
||||
let (mut drawn_shapes, mut by_box) = (0usize, 0usize);
|
||||
// (weight, layer, its area, share differing, is text)
|
||||
let mut found: Vec<(f64, NodeId, Area, f64, bool)> = Vec::new();
|
||||
// Deepest first: a child's difference isn't its parent's too.
|
||||
for layer in layers.iter().rev() {
|
||||
let (Some(n), Some(b)) = (doc.node(*layer), doc.world_bounds(*layer)) else { continue };
|
||||
let corner = |v: f64, origin: f64, limit: usize| (((v - origin) * per).round().max(0.0) as usize).min(limit) as i32;
|
||||
let area = (corner(b.x0, bounds.x0, gw), corner(b.y0, bounds.y0, gh), corner(b.x1, bounds.x0, gw), corner(b.y1, bounds.y0, gh));
|
||||
let (x0, y0, x1, y1) = area;
|
||||
// A layer with an unclaimed difference in its box claims only the cells it draws on, so a
|
||||
// see-through part leaves them to the layers under it. Drawing each one costs, so it is
|
||||
// done only for those, and only up to a limit (said in the result).
|
||||
let open = (y0..y1).any(|y| {
|
||||
(x0..x1).any(|x| {
|
||||
let at = y as usize * gw + x as usize;
|
||||
claimed.get(at).is_some_and(|c| !c) && differing.get(at).is_some_and(|d| *d)
|
||||
})
|
||||
});
|
||||
let shape = if !open {
|
||||
None
|
||||
} else if drawn_shapes < MAX_DRAWN {
|
||||
drawn_shapes += 1;
|
||||
coverage(doc, *layer, (bounds.x0, bounds.y0), per, area)
|
||||
} else {
|
||||
by_box += 1;
|
||||
None
|
||||
};
|
||||
let (mut own, mut bad_pixels) = (0usize, 0usize);
|
||||
let text = matches!(n.kind, NodeKind::Text(_));
|
||||
let width = (x1 - x0).max(0) as usize;
|
||||
for y in y0..y1 {
|
||||
for x in x0..x1 {
|
||||
if shape.as_ref().is_some_and(|c| !c.get((y - y0) as usize * width + (x - x0) as usize).copied().unwrap_or(false)) {
|
||||
continue;
|
||||
}
|
||||
let at = y as usize * gw + x as usize;
|
||||
let (Some(free), Some(differs)) = (claimed.get_mut(at), differing.get(at)) else { continue };
|
||||
if *free {
|
||||
continue;
|
||||
}
|
||||
own += 1;
|
||||
let far =
|
||||
!text || design.at(x, y).zip(shot.at(x, y)).is_some_and(|(a, b)| f64::from(delta(a, b)) > f64::from(tolerance) * TEXT_FACTOR);
|
||||
bad_pixels += usize::from(*differs && far);
|
||||
*free = true;
|
||||
}
|
||||
}
|
||||
let share = if own > 0 { bad_pixels as f64 / own as f64 } else { 0.0 };
|
||||
if own == 0 || share < MIN_SHARE {
|
||||
continue;
|
||||
}
|
||||
found.push(((own as f64) * share, *layer, area, share, text));
|
||||
}
|
||||
found.sort_by(|a, b| b.0.total_cmp(&a.0));
|
||||
let count = found.len();
|
||||
found.truncate(MAX_LISTED);
|
||||
// Only the listed ones are searched for a move: it tries every offset, so it is the costly part.
|
||||
let differences: Vec<Value> = found
|
||||
.into_iter()
|
||||
.filter_map(|(_, layer, area, share, text)| {
|
||||
let n = doc.node(layer)?;
|
||||
let shift = moved(&design, &shot, area, tolerance);
|
||||
let (expected, actual) = (mean(&design, area), mean(&shot, area));
|
||||
let mut d = json!({
|
||||
"id": layer, "name": n.name, "type": n.kind.type_name(),
|
||||
"kind": if shift.is_some() { "position" } else if expected != actual && share > 0.8 { "color" } else { "content" },
|
||||
"percent": (share * 1000.0).round() / 10.0,
|
||||
"expected": expected, "actual": actual,
|
||||
});
|
||||
if let Some((dx, dy)) = shift {
|
||||
d["offset"] = json!({"x": (f64::from(dx) / per).round(), "y": (f64::from(dy) / per).round()});
|
||||
}
|
||||
if text {
|
||||
d["note"] = json!("text: check the font, size and line height before anything else");
|
||||
}
|
||||
Some(d)
|
||||
})
|
||||
.collect();
|
||||
let mut out = json!({
|
||||
"target": {"id": id, "name": root.name, "width": fw, "height": fh},
|
||||
"viewport": {"width": fw.ceil(), "height": fh.ceil()},
|
||||
"capture": {"width": capture.width(), "height": capture.height(), "density": density, "sameSize": same_size, "cssWidth": cw, "cssHeight": ch},
|
||||
"changedPercent": ((changed as f64 / (gw * gh) as f64) * 1000.0).round() / 10.0,
|
||||
"differences": differences,
|
||||
"total": count,
|
||||
"note": "changedPercent alone proves nothing: fonts and antialiasing differ between renderers. Work through `differences`, and take a position or colour difference more seriously than text content",
|
||||
});
|
||||
if layers_cut {
|
||||
// Layers past the cap weren't looked at: their differences fall to the layers above them.
|
||||
out["truncated"]["maxLayers"] = json!(MAX_LAYERS);
|
||||
}
|
||||
if by_box > 0 {
|
||||
// Past the limit, a layer was matched by its whole box: a see-through part of it may
|
||||
// hide a difference that belongs to a layer under it.
|
||||
out["truncated"]["matchedByBox"] = json!(by_box);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![spec!(
|
||||
"inspect.compare",
|
||||
"Compare with a capture",
|
||||
"{id? (a frame, component or instance; default the first selected layer, refused when it is anything else), path | data (base64; not both): a capture of the built page, density? (device pixels per CSS pixel; default from the widths), tolerance? (out of 255, default 24)} the layers that differ, deepest first → {target, viewport {width, height}, capture {width, height, density, sameSize, cssWidth, cssHeight}, changedPercent, differences: [{id, name, type, kind: position|color|content, percent, expected, actual, offset?, note?}] (at most 100, largest first), total, note, truncated? {maxLayers?, matchedByBox?}}",
|
||||
false,
|
||||
compare
|
||||
)]
|
||||
}
|
||||
@@ -74,6 +74,7 @@ pub use dev::devcompare;
|
||||
pub use dev::devinspect;
|
||||
pub use dev::responsive;
|
||||
pub use dev::tailwind;
|
||||
pub use dev::visual_compare;
|
||||
pub use extensions::plugin_directory;
|
||||
pub use extensions::plugins;
|
||||
pub use extensions::widgets;
|
||||
@@ -725,3 +726,5 @@ mod paste_properties_tests;
|
||||
mod selection_reorder_tests;
|
||||
#[cfg(test)]
|
||||
mod selection_spacing_tests;
|
||||
#[cfg(test)]
|
||||
mod visual_compare_tests;
|
||||
@@ -3,10 +3,11 @@ use super::{
|
||||
components, events, find_command, guard, library, normalize, params, textpreview,
|
||||
};
|
||||
|
||||
/// Whether a command, or a batch wrapping one, imports a file passed as Base64 `data`.
|
||||
/// Whether a command, or a batch wrapping one, passes a file as Base64 `data`: an import, or a
|
||||
/// capture to compare with the design.
|
||||
fn command_carries_import_bytes(id: &str, params: &Value) -> bool {
|
||||
match id {
|
||||
"file.import" | "image.replace" => params::get(params, "data").is_some(),
|
||||
"file.import" | "image.replace" | "inspect.compare" => params::get(params, "data").is_some(),
|
||||
"command.batch" => params.get("commands").and_then(Value::as_array).is_some_and(|commands| {
|
||||
commands.iter().any(|c| {
|
||||
c.get("command").and_then(Value::as_str).zip(c.get("params")).is_some_and(|(id, params)| command_carries_import_bytes(id, params))
|
||||
@@ -122,8 +123,8 @@ impl Session {
|
||||
if spec.history && id != "edit.repeat" {
|
||||
self.last_command = Some((id.to_string(), params.clone()));
|
||||
}
|
||||
// Imported bytes already live in the document: a Base64 copy in the log would stay
|
||||
// for the whole session.
|
||||
// Imported bytes already live in the document, and a capture is only read: a
|
||||
// Base64 copy in the log would stay for the whole session.
|
||||
if !command_carries_import_bytes(id, params) {
|
||||
self.journal.push((id.to_string(), params.clone()));
|
||||
if self.journal.len() > 5000 {
|
||||
|
||||
@@ -0,0 +1,259 @@
|
||||
//! `inspect.compare` on captures made from the design itself, then changed the way a build can be
|
||||
//! wrong, so the expected answer is known.
|
||||
|
||||
use base64::Engine as _;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::Session;
|
||||
|
||||
fn session() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn make(s: &mut Session, params: Value) -> u64 {
|
||||
s.execute("node.create", ¶ms).unwrap()["id"].as_u64().unwrap()
|
||||
}
|
||||
|
||||
/// A white 400 × 300 frame with a blue box.
|
||||
fn card(s: &mut Session) -> (u64, u64) {
|
||||
let f = make(s, json!({"type": "frame", "name": "Card", "width": 400, "height": 300, "props": {"fill": "#FFFFFF"}}));
|
||||
let b = make(
|
||||
s,
|
||||
json!({"type": "rectangle", "parent": f, "name": "Box", "x": 100, "y": 80, "width": 120, "height": 60, "props": {"fill": "#2040C0"}}),
|
||||
);
|
||||
(f, b)
|
||||
}
|
||||
|
||||
/// The frame as a PNG, as a browser capture would be, at `scale`.
|
||||
fn capture(s: &mut Session, id: u64, scale: f64) -> String {
|
||||
let v = s.execute("file.export", &json!({"ids": [id], "format": "png", "scale": scale})).unwrap();
|
||||
v["data"].as_str().unwrap().to_string()
|
||||
}
|
||||
|
||||
fn compare(s: &mut Session, id: u64, data: &str) -> Value {
|
||||
s.execute("inspect.compare", &json!({"id": id, "data": data})).unwrap()
|
||||
}
|
||||
|
||||
fn differs<'a>(v: &'a Value, name: &str) -> Option<&'a Value> {
|
||||
v["differences"].as_array().unwrap().iter().find(|d| d["name"] == name)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_faithful_capture_has_no_differences() {
|
||||
let mut s = session();
|
||||
let (f, _) = card(&mut s);
|
||||
let data = capture(&mut s, f, 1.0);
|
||||
let v = compare(&mut s, f, &data);
|
||||
assert_eq!(v["total"], 0, "{v}");
|
||||
assert_eq!(v["changedPercent"], 0.0);
|
||||
assert_eq!(v["viewport"], json!({"width": 400.0, "height": 300.0}));
|
||||
assert_eq!(v["capture"]["sameSize"], true);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_retina_capture_is_the_same_design() {
|
||||
let mut s = session();
|
||||
let (f, _) = card(&mut s);
|
||||
let data = capture(&mut s, f, 2.0);
|
||||
let v = compare(&mut s, f, &data);
|
||||
assert_eq!(v["capture"]["density"], 2.0);
|
||||
assert_eq!(v["total"], 0, "{v}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_wrong_colour_names_the_layer_and_both_colours() {
|
||||
let mut s = session();
|
||||
let (f, b) = card(&mut s);
|
||||
s.execute("node.set", &json!({"ids": [b], "props": {"fill": "#C02020"}})).unwrap();
|
||||
let data = capture(&mut s, f, 1.0);
|
||||
s.execute("node.set", &json!({"ids": [b], "props": {"fill": "#2040C0"}})).unwrap();
|
||||
let v = compare(&mut s, f, &data);
|
||||
let d = differs(&v, "Box").unwrap_or_else(|| panic!("{v}"));
|
||||
assert_eq!(d["kind"], "color");
|
||||
assert_eq!((d["expected"].as_str(), d["actual"].as_str()), (Some("#2040C0"), Some("#C02020")));
|
||||
assert!(differs(&v, "Card").is_none(), "reported once, on the deepest layer: {v}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_moved_layer_says_how_far() {
|
||||
let mut s = session();
|
||||
let (f, b) = card(&mut s);
|
||||
s.execute("node.set", &json!({"ids": [b], "props": {"x": 108, "y": 76}})).unwrap();
|
||||
let data = capture(&mut s, f, 1.0);
|
||||
s.execute("node.set", &json!({"ids": [b], "props": {"x": 100, "y": 80}})).unwrap();
|
||||
let v = compare(&mut s, f, &data);
|
||||
let d = differs(&v, "Box").unwrap_or_else(|| panic!("{v}"));
|
||||
assert_eq!(d["kind"], "position");
|
||||
assert_eq!(d["offset"], json!({"x": 8.0, "y": -4.0}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_capture_of_another_size_says_so() {
|
||||
let mut s = session();
|
||||
let (f, _) = card(&mut s);
|
||||
let wider = make(&mut s, json!({"type": "frame", "name": "Wide", "width": 400, "height": 500, "props": {"fill": "#FFFFFF"}}));
|
||||
let data = capture(&mut s, wider, 1.0);
|
||||
let v = compare(&mut s, f, &data);
|
||||
assert_eq!(v["capture"]["sameSize"], false);
|
||||
assert_eq!(v["capture"]["cssHeight"], 500.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hidden_layers_arent_blamed() {
|
||||
let mut s = session();
|
||||
let (f, b) = card(&mut s);
|
||||
let data = capture(&mut s, f, 1.0);
|
||||
s.execute("node.set", &json!({"ids": [b], "props": {"visible": false}})).unwrap();
|
||||
let v = compare(&mut s, f, &data);
|
||||
assert!(differs(&v, "Box").is_none());
|
||||
assert!(differs(&v, "Card").is_some(), "the frame shows what it didn't expect: {v}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_path_is_read_only_inside_the_automation_roots() {
|
||||
let mut s = session();
|
||||
let (f, _) = card(&mut s);
|
||||
let base = std::env::temp_dir().join(format!("figcraft-compare-{}", std::process::id()));
|
||||
let (inside, outside) = (base.join("inside"), base.join("outside"));
|
||||
std::fs::create_dir_all(&inside).unwrap();
|
||||
std::fs::create_dir_all(&outside).unwrap();
|
||||
let bytes = base64::engine::general_purpose::STANDARD.decode(capture(&mut s, f, 1.0)).unwrap();
|
||||
for dir in [&inside, &outside] {
|
||||
std::fs::write(dir.join("shot.png"), &bytes).unwrap();
|
||||
}
|
||||
let roots = std::sync::Arc::new(crate::file_access::Roots::new(&[inside.to_string_lossy().to_string()], &[]).unwrap());
|
||||
crate::file_access::confined(Some(&roots), || {
|
||||
assert_eq!(s.execute("inspect.compare", &json!({"id": f, "path": inside.join("shot.png")})).unwrap()["total"], 0);
|
||||
let e = s.execute("inspect.compare", &json!({"id": f, "path": outside.join("shot.png")})).unwrap_err().to_string();
|
||||
assert!(e.contains("automation path rejected"), "{e}");
|
||||
});
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn junk_is_refused_without_a_panic() {
|
||||
let mut s = session();
|
||||
let (f, _) = card(&mut s);
|
||||
for p in [
|
||||
json!({"id": f}),
|
||||
json!({"id": f, "data": "not base64!"}),
|
||||
json!({"id": f, "data": "aGVsbG8="}),
|
||||
json!({"id": 999_999, "data": capture(&mut s, f, 1.0)}),
|
||||
] {
|
||||
assert!(s.execute("inspect.compare", &p).is_err(), "{p}");
|
||||
}
|
||||
let data = capture(&mut s, f, 1.0);
|
||||
// Out of range numbers are clamped; a value that isn't a number is a mistake.
|
||||
assert!(s.execute("inspect.compare", &json!({"id": f, "data": data, "tolerance": 1000, "density": -1})).is_ok());
|
||||
for p in [json!({"id": f, "data": data, "tolerance": "x"}), json!({"id": f, "data": data, "density": "2x"}), json!({"id": f, "data": 7})] {
|
||||
assert!(s.execute("inspect.compare", &p).is_err(), "{p}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_malformed_target_is_refused_rather_than_read_as_the_selection() {
|
||||
let mut s = session();
|
||||
let (f, _) = card(&mut s);
|
||||
let data = capture(&mut s, f, 1.0);
|
||||
s.execute("select.set", &json!({"ids": [f]})).unwrap();
|
||||
for target in [json!({"id": "not-an-id"}), json!({"ids": [f, "nope"]})] {
|
||||
let mut p = target.clone();
|
||||
p["data"] = json!(data);
|
||||
assert!(s.execute("inspect.compare", &p).is_err(), "{target}");
|
||||
}
|
||||
// With no target, the selection is the frame.
|
||||
assert_eq!(s.execute("inspect.compare", &json!({"data": data})).unwrap()["target"]["id"], f);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_capture_and_a_path_together_are_refused() {
|
||||
let mut s = session();
|
||||
let (f, _) = card(&mut s);
|
||||
let data = capture(&mut s, f, 1.0);
|
||||
assert!(s.execute("inspect.compare", &json!({"id": f, "data": data, "path": "shot.png"})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn many_differences_are_listed_up_to_the_cap_and_counted() {
|
||||
let mut s = session();
|
||||
let f = make(&mut s, json!({"type": "frame", "name": "Grid", "width": 180, "height": 120, "props": {"fill": "#FFFFFF"}}));
|
||||
let boxes: Vec<u64> = (0..150)
|
||||
.map(|k| {
|
||||
let (x, y) = ((k % 15) * 12, (k / 15) * 12);
|
||||
make(&mut s, json!({"type": "rectangle", "parent": f, "x": x, "y": y, "width": 8, "height": 8, "props": {"fill": "#2040C0"}}))
|
||||
})
|
||||
.collect();
|
||||
for b in &boxes {
|
||||
s.execute("node.set", &json!({"ids": [b], "props": {"fill": "#C02020"}})).unwrap();
|
||||
}
|
||||
let data = capture(&mut s, f, 1.0);
|
||||
for b in &boxes {
|
||||
s.execute("node.set", &json!({"ids": [b], "props": {"fill": "#2040C0"}})).unwrap();
|
||||
}
|
||||
let v = compare(&mut s, f, &data);
|
||||
let listed = v["differences"].as_array().unwrap();
|
||||
assert_eq!(v["total"], 150, "every changed box is counted: {}", v["total"]);
|
||||
assert!(listed.len() < 150, "the list is capped below the count");
|
||||
assert!(listed.iter().all(|d| d["kind"] == "color"), "{v}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_frame_is_compared_at_a_time() {
|
||||
let mut s = session();
|
||||
let (f, b) = card(&mut s);
|
||||
let data = capture(&mut s, f, 1.0);
|
||||
let e = s.execute("inspect.compare", &json!({"ids": [f, b], "data": data})).unwrap_err().to_string();
|
||||
assert!(e.contains("one frame"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_a_frame_component_or_instance_is_compared() {
|
||||
let mut s = session();
|
||||
let (f, b) = card(&mut s);
|
||||
let data = capture(&mut s, f, 1.0);
|
||||
let e = s.execute("inspect.compare", &json!({"id": b, "data": data})).unwrap_err().to_string();
|
||||
assert!(e.contains("frame"), "a rectangle named outright: {e}");
|
||||
s.execute("select.set", &json!({"ids": [b]})).unwrap();
|
||||
let e = s.execute("inspect.compare", &json!({"data": data})).unwrap_err().to_string();
|
||||
assert!(e.contains("frame"), "a rectangle selected: {e}");
|
||||
let c = s.execute("component.create", &json!({"ids": [f]})).unwrap()["id"].as_u64().unwrap();
|
||||
let i = s.execute("instance.create", &json!({"component": c, "x": 800, "y": 0})).unwrap()["id"].as_u64().unwrap();
|
||||
for id in [c, i] {
|
||||
assert!(s.execute("inspect.compare", &json!({"id": id, "data": data})).is_ok(), "{id}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_capture_is_not_kept_in_the_journal() {
|
||||
let mut s = session();
|
||||
let (f, _) = card(&mut s);
|
||||
let data = capture(&mut s, f, 1.0);
|
||||
compare(&mut s, f, &data);
|
||||
assert!(!s.journal.iter().any(|(_, p)| p.to_string().contains(&data)), "the log must not hold the capture");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_the_frames_own_area_is_drawn_for_the_comparison() {
|
||||
let mut s = session();
|
||||
let (f, _) = card(&mut s);
|
||||
s.execute("node.set", &json!({"ids": [f], "props": {"clipsContent": false}})).unwrap();
|
||||
let data = capture(&mut s, f, 1.0);
|
||||
// A layer past the frame's left edge is drawn, but it isn't part of the page.
|
||||
make(&mut s, json!({"type": "rectangle", "parent": f, "x": -160, "y": 20, "width": 100, "height": 100, "props": {"fill": "#00AA00"}}));
|
||||
let v = compare(&mut s, f, &data);
|
||||
assert_eq!(v["total"], 0, "{v}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_shape_with_see_through_corners_leaves_the_layer_under_it_to_blame() {
|
||||
let mut s = session();
|
||||
let (f, b) = card(&mut s);
|
||||
make(&mut s, json!({"type": "ellipse", "parent": f, "name": "Dot", "x": 100, "y": 80, "width": 120, "height": 60, "props": {"fill": "#FFFFFF"}}));
|
||||
s.execute("node.set", &json!({"ids": [b], "props": {"fill": "#C02020"}})).unwrap();
|
||||
let data = capture(&mut s, f, 1.0);
|
||||
s.execute("node.set", &json!({"ids": [b], "props": {"fill": "#2040C0"}})).unwrap();
|
||||
let v = compare(&mut s, f, &data);
|
||||
assert!(differs(&v, "Box").is_some(), "the box shows through the ellipse's corners: {v}");
|
||||
}
|
||||
@@ -104,6 +104,7 @@ pub const TOOL_NAMES: &[&str] = &[
|
||||
"get_node",
|
||||
"design_context",
|
||||
"export_assets",
|
||||
"compare_design",
|
||||
"component_mappings",
|
||||
"sync_mappings",
|
||||
"select",
|
||||
@@ -130,6 +131,7 @@ const DOCUMENT_TOOLS: &[&str] = &[
|
||||
"get_node",
|
||||
"design_context",
|
||||
"export_assets",
|
||||
"compare_design",
|
||||
"component_mappings",
|
||||
"sync_mappings",
|
||||
"select",
|
||||
@@ -292,6 +294,21 @@ fn tools() -> Vec<Value> {
|
||||
),
|
||||
false,
|
||||
),
|
||||
tool(
|
||||
"compare_design",
|
||||
"Compare with the design",
|
||||
"Compare a capture you made of the built page with a frame, on this computer. Size the browser to the `viewport` it returns (the frame's size in CSS pixels), capture the page to a file, and call this again. It names the layers that differ, largest first and each on the deepest layer it belongs to, as a position, colour or content difference with the expected and actual colours and any offset. A layer is listed once at least 2% of its own pixels differ, so an empty list doesn't mean every pixel matches. Fix those; don't aim for a pixel score, because fonts and antialiasing always differ a little between renderers.",
|
||||
obj(
|
||||
json!({
|
||||
"id": id_schema("The frame, component or instance (default the first selected layer; any other kind of layer is refused)"),
|
||||
"image": string("The capture: a PNG, JPEG or WebP file, absolute or relative to where this server runs"),
|
||||
"density": num("Device pixels per CSS pixel (default from the widths)"),
|
||||
"tolerance": num("How different a pixel must be to count, out of 255 (default 24)")
|
||||
}),
|
||||
&["image"],
|
||||
),
|
||||
true,
|
||||
),
|
||||
tool(
|
||||
"component_mappings",
|
||||
"Component mappings",
|
||||
@@ -523,6 +540,20 @@ fn export_assets(b: &mut dyn Backend, a: &Map<String, Value>) -> Result<ToolResu
|
||||
exec(b, "file.exportAssets", Value::Object(params)).map(|v| ToolResult::json(&v))
|
||||
}
|
||||
|
||||
/// `inspect.compare` on a capture file, made absolute here: an attached app runs in another folder.
|
||||
fn compare_design(b: &mut dyn Backend, a: &Map<String, Value>) -> Result<ToolResult, String> {
|
||||
let image = s_arg(a, "image")?.filter(|i| !i.trim().is_empty()).ok_or("`image` required: the capture of the built page")?;
|
||||
let path = std::path::absolute(image).map_err(|e| format!("image: {e}"))?;
|
||||
let mut params = Map::new();
|
||||
for key in ["id", "density", "tolerance"] {
|
||||
if let Some(v) = a.get(key) {
|
||||
params.insert(key.into(), v.clone());
|
||||
}
|
||||
}
|
||||
params.insert("path".into(), json!(path.to_string_lossy()));
|
||||
exec(b, "inspect.compare", Value::Object(params)).map(|v| ToolResult::json(&v))
|
||||
}
|
||||
|
||||
/// `codeConnect.list`, checking source files against `root`, else where this server runs.
|
||||
fn component_mappings(b: &mut dyn Backend, a: &Map<String, Value>) -> Result<ToolResult, String> {
|
||||
let mut params = a.clone();
|
||||
@@ -690,6 +721,7 @@ pub fn call_tool(b: &mut dyn Backend, name: &str, args: &Value) -> ToolResult {
|
||||
"get_node" => get_node(b, &a),
|
||||
"design_context" => design_context(b, &a),
|
||||
"export_assets" => export_assets(b, &a),
|
||||
"compare_design" => compare_design(b, &a),
|
||||
"component_mappings" => component_mappings(b, &a),
|
||||
"sync_mappings" => sync_mappings(b, &a),
|
||||
"select" => select(b, &a),
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
//! `compare_design`: a capture of the frame itself matches it, and the capture is required.
|
||||
|
||||
use base64::Engine as _;
|
||||
use serde_json::json;
|
||||
|
||||
use crate::common::Client;
|
||||
|
||||
#[test]
|
||||
fn a_capture_of_the_frame_matches_and_one_is_required() {
|
||||
let mut c = Client::new();
|
||||
let frame = c
|
||||
.ok("run_command", json!({"command": "node.create", "params": {"type": "frame", "width": 200, "height": 100, "props": {"fill": "#FFFFFF"}}}));
|
||||
let id = frame["id"].clone();
|
||||
let png = c.ok("run_command", json!({"command": "file.export", "params": {"ids": [id], "format": "png"}}));
|
||||
let bytes = base64::engine::general_purpose::STANDARD.decode(png["data"].as_str().unwrap()).unwrap();
|
||||
let dir = std::env::temp_dir().join(format!("figcraft-mcp-compare-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let shot = dir.join("shot.png");
|
||||
std::fs::write(&shot, bytes).unwrap();
|
||||
let v = c.ok("compare_design", json!({"id": id, "image": shot}));
|
||||
assert_eq!(v["total"], 0, "{v}");
|
||||
assert_eq!(v["viewport"], json!({"width": 200.0, "height": 100.0}));
|
||||
for args in [json!({"id": id}), json!({"id": id, "image": " "}), json!({"id": id, "image": 3})] {
|
||||
assert_eq!(c.call("compare_design", args.clone())["isError"], true, "{args}");
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
@@ -12,6 +12,7 @@ mod automation_roots;
|
||||
mod code_connect;
|
||||
#[allow(dead_code, clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
mod common;
|
||||
mod compare_design;
|
||||
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
mod create_warnings;
|
||||
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
|
||||
+39
@@ -416,6 +416,7 @@ a later step can use `{"$step": 0, "field": "ids/0"}` to target the first match.
|
||||
| `get_node {id, depth, fields?, outline?}` | One layer as JSON; takes the same `fields` and `outline` options; `pluginData` (`{key: value}`, values as strings) when the layer or page has layer data written with `set_properties {props: {pluginData}}`. |
|
||||
| `design_context {ids?, scope?, depth?, maxNodes?, maxBytes?}` | Everything needed to build a design in one read: see [Design context](#design-context). |
|
||||
| `export_assets {ids?, dir?, dryRun?}` | Write the selection's images and vectors into `dir` as files named by their content: see [Asset handoff](#asset-handoff). |
|
||||
| `compare_design {image, id?, density?, tolerance?}` | Compare a capture of the built page with a frame, on this computer: see [Visual verification](#visual-verification). |
|
||||
| `component_mappings {ids?, unmapped?, root?}` | Which code component each design component is: `import`, `name`, `source` (and `sourceFound` under `root`, default the server's folder), a ready `snippet`, `properties` with variants, and `values` that need translating. |
|
||||
| `sync_mappings {direction, path?}` | Apply a code repository's `figcraft.connect.json` to the open design (`import`) or write the design's mappings to it (`export`); `path` defaults to that file in the server's folder. |
|
||||
| `select {ids}` | Replace the selection (`[]` deselects). |
|
||||
@@ -486,6 +487,44 @@ and hidden layers stay out. It reads what `inspect.assets` finds, up to 200 laye
|
||||
Fonts are never exported. The file holds only family and style names, and `design_context` lists them
|
||||
under `fonts`. Their licences are for the project to check.
|
||||
|
||||
### Visual verification
|
||||
|
||||
`compare_design` (the command `inspect.compare {id?, path | data}`) checks a built page against the
|
||||
frame it was built from (a frame, a component or an instance; any other layer, given or selected, is
|
||||
refused, since its result would look like a real answer), one at a time, on this computer, with a
|
||||
capture the agent's own browser tools made. FigCraft doesn't drive a browser, and no image leaves the
|
||||
computer through it.
|
||||
|
||||
1. Read the frame's size from `design_context` (or `get_node`): its width and height are the
|
||||
browser's viewport in CSS pixels. Each result repeats it as `viewport`.
|
||||
2. Size the browser to it and capture the page to a file, for example with Playwright:
|
||||
`await page.setViewportSize({width: 1440, height: 900}); await page.screenshot({path: "shot.png"})`.
|
||||
3. Call `compare_design {id: <the frame's id>, image: "shot.png"}` (absolute or relative to where the MCP server runs; the
|
||||
file is read like any other, inside the automation roots when they are set).
|
||||
4. Fix the layers in `differences` and repeat from step 2.
|
||||
|
||||
| Key | Meaning |
|
||||
|---|---|
|
||||
| `differences` | The layers that differ, largest first and at most 100, each on the deepest layer it belongs to: `id`, `name`, `type`, `kind`, `percent` (of the layer's own area), `expected` and `actual` mean colours, `offset` and `note` |
|
||||
| `kind` | `position` with `offset` in CSS pixels, `color`, or `content` for anything else |
|
||||
| `note` | On text: check the font, size and line height first. Text is held to twice the tolerance, since fonts and antialiasing differ between renderers |
|
||||
| `total` | How many layers differ, listed or not |
|
||||
| `capture` | `width`, `height`, `density` (device pixels per CSS pixel, from the widths unless given), `sameSize`, `cssWidth`, `cssHeight`. A page that isn't the frame's size is the first thing to fix |
|
||||
| `changedPercent` | How much of the frame differs, to one decimal. Not a score: fonts and antialiasing always differ a little |
|
||||
| `truncated` | `maxLayers` when the frame has more than 5,000 visible layers: those past it weren't looked at. `matchedByBox`: how many layers were matched by their whole box, not the shape they draw (past 300 drawn), so a see-through part of one may hide a difference of a layer under it |
|
||||
|
||||
`tolerance` (default 24 of 255) is how different a pixel must be to count. A layer is listed only
|
||||
when at least 2% of the pixels it owns (those no layer above it claims) differ by more than that, so
|
||||
a smaller difference, such as a few stray pixels or a thin line on a large background, isn't listed,
|
||||
and `changedPercent`, rounded to one decimal, can read 0 for it. Moves of more than 16 compared
|
||||
pixels show as `content`. Only the area both images have is compared, so content scrolled out of the
|
||||
capture needs a full-page capture. A clean result (`total` 0) says only that no layer looked at
|
||||
differs by that 2% in the area compared; it doesn't verify the rest of the frame (see
|
||||
`capture.sameSize` and `truncated`), and it isn't proof the pages are identical.
|
||||
Images are compared at up to 2,000 pixels a side, the larger of the frame and the capture setting
|
||||
the scale. Each layer claims the pixels it draws on, so a see-through part of a shape leaves a
|
||||
difference to the layer under it.
|
||||
|
||||
### Compact layer trees
|
||||
|
||||
`inspect_document` and `get_node` accept `fields`, an array of exact, case-sensitive top-level node
|
||||
|
||||
Reference in new issue
Block a user