Merge branch 'main' into codex/figcraft-2284-progress

This commit is contained in:
Dylan M. Taylor
2026-11-12 22:47:52 +00:00
17 changed files with 497 additions and 21 deletions
+7 -2
View File
@@ -360,8 +360,13 @@ impl Session {
pub(super) fn eyedrop(&mut self, ev: &PointerEvent) -> Result<()> {
let ds = self.ds()?;
let doc = ds.doc.clone();
let view = figcraft_render::View { origin: (ev.x, ev.y), scale: ev.zoom.max(0.01), width: 1, height: 1 };
let Some(pix) = figcraft_render::render_view(&doc, ds.page, &view, &Default::default()) else { return Ok(()) };
// One screen pixel centred on the pointer (its top left half a pixel up and to the left).
let scale = ev.zoom.max(0.01);
let view = figcraft_render::View { origin: (ev.x - 0.5 / scale, ev.y - 0.5 / scale), scale, width: 1, height: 1 };
// As the canvas draws it: an image magnified past 2x shows its pixels, so the colour picked
// is the pixel under the pointer, not a blend with its neighbours (#2189).
let opts = figcraft_render::Options { magnified_image_pixels: true, ..Default::default() };
let Some(pix) = figcraft_render::render_view(&doc, ds.page, &view, &opts) else { return Ok(()) };
let rgba = figcraft_render::to_rgba8(&pix);
let c = figcraft_color::Color::from_rgba8(
rgba.first().copied().unwrap_or(0),
+11 -2
View File
@@ -113,8 +113,12 @@ pub(super) fn set(s: &mut Session, p: &Value) -> Result<Value> {
// A new rotation for the selection turns it about its moved rotation origin: each layer's
// point under the origin stays put.
let ds = s.ds()?;
let pivot =
ds.moved_origin().filter(|_| props.contains_key("rotation") && !props.contains_key("x") && !props.contains_key("y") && ds.selection == ids);
let pivot = ds.moved_origin().filter(|_| {
(props.contains_key("rotation") || props.contains_key("absoluteRotation"))
&& !props.contains_key("x")
&& !props.contains_key("y")
&& ds.selection == ids
});
let pinned: Vec<(NodeId, figcraft_geom::Point)> = match pivot {
Some(o) => roots(&ds.doc, &ids)
.into_iter()
@@ -161,6 +165,11 @@ pub(super) fn set(s: &mut Session, p: &Value) -> Result<Value> {
}
let doc = s.doc_mut()?;
let before = crate::cmd::styles::bound_before(doc, &ids);
let mut ids = ids;
if props.contains_key("absoluteRotation") {
// A page angle depends on the parents': turn a selected parent before the layers in it.
ids.sort_by_key(|i| doc.ancestors(*i).len());
}
for i in ids {
crate::cmd::props::apply("node.set", doc, i, skipped.get(&i).unwrap_or(&props))?;
}
+23 -2
View File
@@ -16,7 +16,7 @@ use crate::{Result, bad};
pub const STROKE_SIDES: [&str; 4] = ["strokeTopWeight", "strokeRightWeight", "strokeBottomWeight", "strokeLeftWeight"];
/// Keys `node.set` understands (documented for agents).
pub const KEYS: &str = "name, visible, locked, opacity (0-1 or \"50%\"), blend, x, y (relative to the parent frame; groups don't count), width, height, rotation (degrees), \
pub const KEYS: &str = "name, visible, locked, opacity (0-1 or \"50%\"), blend, x, y (relative to the parent frame; groups don't count), width, height, rotation (degrees), absoluteRotation (degrees on the page: the layer's angle plus its parents', what the Design panel's field shows; one of the two per call), \
fills (paints or colours; gradients as {type: linearGradient|radialGradient|angularGradient|diamondGradient, stops: [\"#hex\", ...], from?, to?} too), fill (colour, {$var: variable id or name}, or \"none\"/null: no fill), strokes, stroke (colour, {$var: variable id or name}, or \"none\"/null: no stroke), strokeWeight, strokeAlign (inside|center|outside), strokeSides [t,r,b,l], strokeTopWeight / strokeRightWeight / strokeBottomWeight / strokeLeftWeight (one side; turns on individual strokes), \
strokeCap / startCap / endCap, strokeJoin, miterAngle (degrees: sharper joins bevel; or miterLimit as a ratio), dashes [..], dashCap (none|round|square; null: dashes take startCap and endCap), widthProfile (preset uniform|wedge|taper|eye|rounded|pinch, [[t, scale], ...] or null), brush (preset id, {preset, spacing, sizeJitter, rotationJitter, scatter, seed} or null), cornerRadius (n or [tl,tr,br,bl]), cornerSmoothing (0-1), effects, \
clip, isMask, layout (null|horizontal|vertical|grid|{...}), gap, crossGap, padding (n or [t,r,b,l]), paddingTop/Right/Bottom/Left, \
@@ -456,7 +456,7 @@ fn apply_order(k: &str, v: &Value) -> u8 {
match k {
"path" | "width" | "height" | "w" | "h" => 0,
"layout" | "layoutMode" => 1,
"rotation" => 3,
"rotation" | "absoluteRotation" => 3,
"x" | "y" => 4,
"fillStyle" | "strokeStyle" | "effectStyle" | "textStyle" | "gridStyle" => 5,
"boundVariables" => 6,
@@ -595,6 +595,27 @@ fn apply_geometry(
let n = doc.get_mut(id)?;
n.transform = figcraft_geom::set_rotation_about_center(n.transform, n.width, n.height, deg);
}
"absoluteRotation" => {
let deg = f64_of(v).ok_or_else(|| bad(cmd, "`absoluteRotation` must be degrees"))?;
if props.contains_key("rotation") {
return Err(bad(cmd, "give one of `rotation` and `absoluteRotation`"));
}
let (w, h) = {
let n = doc.get(id)?;
(n.width, n.height)
};
let world = figcraft_geom::set_rotation_about_center(doc.world_transform(id), w, h, deg);
let parent = doc.get(id)?.parent;
let pw = parent.map(|p| doc.world_transform(p)).unwrap_or(figcraft_geom::Affine::IDENTITY);
let local = pw.inverse() * world;
if local.as_coeffs().iter().all(|c| c.is_finite()) {
doc.get_mut(id)?.transform = local;
} else {
// A degenerate parent can't be inverted: turn the local angle instead.
let n = doc.get_mut(id)?;
n.transform = figcraft_geom::set_rotation_about_center(n.transform, n.width, n.height, deg);
}
}
_ => return Ok(false),
}
Ok(true)
@@ -0,0 +1,42 @@
//! #2189: the eyedropper picks the colour the canvas shows under the pointer. A magnified image
//! draws its pixels on the canvas (`magnified_image_pixels`), so the picked colour is that pixel's,
//! not a blend with its neighbours.
use base64::Engine as _;
use serde_json::json;
use crate::Session;
use crate::tools::{PointerEvent, PointerKind};
/// A 9 x 9 image of `back` with a 1 px vertical line of `line` in column 4 (a thin border in a
/// screenshot, as in the report).
fn line_png(back: [u8; 3], line: [u8; 3]) -> Vec<u8> {
let mut p = figcraft_render::Pixmap::new(9, 9).unwrap();
for (i, px) in p.data_mut().chunks_exact_mut(4).enumerate() {
let c = if i % 9 == 4 { line } else { back };
px.copy_from_slice(&[c[0], c[1], c[2], 255]);
}
figcraft_render::encode_png(&p).unwrap()
}
/// The colour the eyedropper picks at page point (x, y) at `zoom`.
fn picked(png: &[u8], x: f64, y: f64, zoom: f64) -> String {
let mut s = Session::new();
let data = base64::engine::general_purpose::STANDARD.encode(png);
s.execute("image.place", &json!({"data": data, "x": 0, "y": 0})).unwrap();
s.execute("edit.pickColor", &json!({"apply": false})).unwrap();
s.pointer(&PointerEvent::at(PointerKind::Down, x, y, zoom)).unwrap();
s.tool.picked.map(|c| c.to_hex()).unwrap_or_default()
}
#[test]
fn the_eyedropper_picks_a_magnified_images_pixel_not_a_blend_with_its_neighbours() {
// The reporter's colours: a #3D444D border, 1 px wide, beside a darker background.
let png = line_png([0x15, 0x1B, 0x23], [0x3D, 0x44, 0x4D]);
for zoom in [2.0, 8.0, 20.0] {
assert_eq!(picked(&png, 4.5, 4.5, zoom), "3D444D", "on the line at {zoom}x");
assert_eq!(picked(&png, 2.5, 4.5, zoom), "151B23", "beside it at {zoom}x");
}
// At 1:1 the canvas pixel is the image's pixel too.
assert_eq!(picked(&png, 4.5, 4.5, 1.0), "3D444D", "on the line at 1x");
}
+2
View File
@@ -327,6 +327,8 @@ mod extended_chain_tests;
#[cfg(test)]
mod eyedropper_create_tests;
#[cfg(test)]
mod eyedropper_image_tests;
#[cfg(test)]
mod facilitate_tests;
#[cfg(test)]
mod fig_export_assets_tests;
@@ -90,6 +90,17 @@ fn rotation_field_and_rotate_commands_turn_about_a_moved_origin() {
assert!(s.execute("transform.setRotationOrigin", &json!({"x": 1})).is_err(), "x without y");
}
#[test]
fn the_absolute_rotation_key_turns_about_a_moved_origin_too() {
let mut s = Session::new();
let r = rect(&mut s);
s.execute("transform.setRotationOrigin", &json!({"x": 100, "y": 100})).unwrap();
s.execute("node.set", &json!({"ids": [r], "props": {"absoluteRotation": 30}})).unwrap();
let doc = s.doc().unwrap();
assert!(near(doc.world_transform(r) * Point::new(100.0, 100.0), Point::new(100.0, 100.0)));
assert!((figcraft_geom::rotation_degrees(doc.world_transform(r)) - 30.0).abs() < 1e-6);
}
#[test]
fn origin_lasts_as_long_as_its_selection() {
let mut s = Session::new();
@@ -533,6 +533,61 @@ fn design_panel_edits_reach_every_selected_layer() {
assert!(near(rotation(&s, a), 30.0) && flipped(&s, a), "{}", rotation(&s, a));
}
#[test]
fn absolute_rotation_sets_the_rotation_on_the_page_keeping_the_centre() {
let mut s = session();
let page = |s: &Session, i: NodeId| rotation_degrees(s.doc().unwrap().world_transform(i));
let f = id(&ex(&mut s, "frame.create", json!({"x": 0, "y": 100, "width": 400, "height": 400})));
set(&mut s, &[f], json!({"rotation": 10}));
let r = rect(&mut s, 100.0, 100.0, 120.0, 80.0, Some(f));
assert!(near(page(&s, r), 10.0) && near(rotation(&s, r), 0.0));
let centre = s.doc().unwrap().world_transform(r) * Point::new(60.0, 40.0);
set(&mut s, &[r], json!({"absoluteRotation": 7}));
assert!(near(page(&s, r), 7.0), "{}", page(&s, r));
assert!(near(rotation(&s, r), -3.0), "{}", rotation(&s, r));
let c = s.doc().unwrap().world_transform(r) * Point::new(60.0, 40.0);
assert!((c - centre).hypot() < 1e-6, "the centre stays put");
set(&mut s, &[r], json!({"absoluteRotation": 0}));
assert!(near(page(&s, r), 0.0) && near(rotation(&s, r), -10.0));
// `node.get` still reports the local angle.
let got = ex(&mut s, "node.get", json!({"id": r}));
let rot = got["rotation"].as_f64().unwrap_or(f64::NAN);
assert!(near(rot, -10.0), "{got}");
// Groups: a child reads and sets the page angle, its sibling keeps its own.
let a = rect(&mut s, 0.0, 600.0, 50.0, 50.0, None);
let b = rect(&mut s, 100.0, 600.0, 50.0, 50.0, None);
let g = id(&ex(&mut s, "object.group", json!({"ids": [a, b]})));
set(&mut s, &[g], json!({"rotation": 10}));
assert!(near(page(&s, a), 10.0));
set(&mut s, &[a], json!({"absoluteRotation": 7}));
assert!(near(page(&s, a), 7.0) && near(page(&s, b), 10.0));
// Several layers: one value on the page for all, one undo step.
let top = rect(&mut s, 800.0, 0.0, 50.0, 50.0, None);
let steps = undo_steps(&s);
set(&mut s, &[r, top], json!({"absoluteRotation": 45}));
assert!(near(page(&s, r), 45.0) && near(page(&s, top), 45.0));
assert_eq!(undo_steps(&s), steps + 1);
// A flip is kept.
ex(&mut s, "object.flipH", json!({"ids": [r]}));
set(&mut s, &[r], json!({"absoluteRotation": 30}));
assert!(near(page(&s, r), 30.0) && flipped(&s, r), "{}", page(&s, r));
// One of the two keys per call.
assert!(s.execute("node.set", &json!({"ids": [r], "props": {"rotation": 1, "absoluteRotation": 2}})).is_err());
}
#[test]
fn absolute_rotation_on_a_frame_and_a_layer_inside_it_lands_both_on_the_page_angle() {
let mut s = session();
let page = |s: &Session, i: NodeId| rotation_degrees(s.doc().unwrap().world_transform(i));
let f = id(&ex(&mut s, "frame.create", json!({"x": 0, "y": 100, "width": 400, "height": 400})));
set(&mut s, &[f], json!({"rotation": 10}));
let r = rect(&mut s, 100.0, 100.0, 120.0, 80.0, Some(f));
// The layer inside comes first in the ids: the frame's turn must not carry it past 45.
set(&mut s, &[r, f], json!({"absoluteRotation": 45}));
assert!(near(page(&s, f), 45.0), "{}", page(&s, f));
assert!(near(page(&s, r), 45.0), "{}", page(&s, r));
}
#[test]
fn constrain_proportions_keeps_the_other_side_in_ratio() {
let mut s = session();
+1 -1
View File
@@ -208,7 +208,7 @@ fn tools() -> Vec<Value> {
tool(
"set_properties",
"Set properties",
"Set properties on one or more layers as one undo step (engine `node.set`). Keys: name, visible, locked, opacity (0-1), blend, x, y (relative to the parent frame; groups don't count), width, height, rotation (degrees), fill (colour) / fills (array of paints: \"#hex\" or {\"type\":\"solid\",\"color\":\"#hex\"} or {\"type\":\"linearGradient\",\"stops\":[\"#hex\",\"#hex\"]} or stops [{\"position\":0..1,\"color\":\"#hex\"}], optional from/to handles in the unit box; radialGradient too), stroke / strokes, strokeWeight, strokeAlign (inside|center|outside), cornerRadius (n or [tl,tr,br,bl]), effects (array, e.g. {\"type\":\"dropShadow\",\"color\":\"#00000040\",\"offset\":[0,4],\"radius\":8}), clip, layout (null|horizontal|vertical|grid), gap, padding (n or [t,r,b,l]), mainAlign (min|center|max|spaceBetween|spaceAround|spaceEvenly), crossAlign, wrap, contentAlign (auto|spaceBetween: wrapped lines), sizingH / sizingV (fixed|hug|fill), constraints {horizontal, vertical}, characters, fontFamily, fontStyle, fontSize, lineHeight, letterSpacing, textAlign, textAutoResize. Auto layout keys (gap, padding, mainAlign, crossAlign, wrap, …) apply to frames, components and instances only: other layers among the ids are skipped and named in `warnings`, and with none that can take them the call is an error. A fontStyle draws in the family's nearest face; `warnings` says when that face has another weight or slant than the name asks for. Run list_commands with filter \"node.set\" for the full list. Unknown keys are an error. Returns the updated layers.",
"Set properties on one or more layers as one undo step (engine `node.set`). Keys: name, visible, locked, opacity (0-1), blend, x, y (relative to the parent frame; groups don't count), width, height, rotation (degrees), absoluteRotation (degrees on the page), fill (colour) / fills (array of paints: \"#hex\" or {\"type\":\"solid\",\"color\":\"#hex\"} or {\"type\":\"linearGradient\",\"stops\":[\"#hex\",\"#hex\"]} or stops [{\"position\":0..1,\"color\":\"#hex\"}], optional from/to handles in the unit box; radialGradient too), stroke / strokes, strokeWeight, strokeAlign (inside|center|outside), cornerRadius (n or [tl,tr,br,bl]), effects (array, e.g. {\"type\":\"dropShadow\",\"color\":\"#00000040\",\"offset\":[0,4],\"radius\":8}), clip, layout (null|horizontal|vertical|grid), gap, padding (n or [t,r,b,l]), mainAlign (min|center|max|spaceBetween|spaceAround|spaceEvenly), crossAlign, wrap, contentAlign (auto|spaceBetween: wrapped lines), sizingH / sizingV (fixed|hug|fill), constraints {horizontal, vertical}, characters, fontFamily, fontStyle, fontSize, lineHeight, letterSpacing, textAlign, textAutoResize. Auto layout keys (gap, padding, mainAlign, crossAlign, wrap, …) apply to frames, components and instances only: other layers among the ids are skipped and named in `warnings`, and with none that can take them the call is an error. A fontStyle draws in the family's nearest face; `warnings` says when that face has another weight or slant than the name asks for. Run list_commands with filter \"node.set\" for the full list. Unknown keys are an error. Returns the updated layers.",
obj(
json!({"ids": ids_schema("Layer ids (default: the selection)"), "props": {"type": "object", "description": "Property values to set"}}),
&["props"],
+153 -1
View File
@@ -209,6 +209,61 @@ fn layout_grids(app: &FigApp, painter: &egui::Painter, doc: &Document, c: NodeId
}
}
/// The solid colour of the fill the next typed character gets (the character before the caret,
/// the first one's at 0, the base style for an empty text): the style's own fills when it has
/// them, else the layer's. `None` when the topmost visible paint isn't a solid (gradient, image,
/// no visible fill), so the caller uses [`caret_fallback`]. Opaque on purpose: Figma's caret
/// is one colour, and the fill's and paint's opacity weren't measured, so it must stay visible.
fn caret_fill(n: &figcraft_doc::Node, caret: usize) -> Option<figcraft_color::Color> {
let t = n.kind.text()?;
let style = t.style_at(caret.saturating_sub(1));
let paints = style.fills.as_ref().unwrap_or(&n.fills);
paints.iter().rev().find(|p| p.visible).and_then(|p| match &p.kind {
figcraft_color::PaintKind::Solid { color } => Some(color.with_alpha(1.0)),
_ => None,
})
}
/// [`caret_fill`] as a screen colour.
fn caret_color(ctx: &egui::Context, n: &figcraft_doc::Node, caret: usize) -> Option<Color32> {
caret_fill(n, caret).map(|c| doc_c32(ctx, c))
}
/// The caret of a text without a solid fill (a gradient, an image, no visible fill): black on a
/// light surface, white on a dark one. The surface is the nearest layer around the text whose
/// topmost visible fill is a solid at least half opaque as drawn (its colour's alpha times its paint's
/// opacity times its own and its containers' layer opacity), else the page; a layer whose top fill is a gradient or an
/// image is passed over. Not the interface's text colour, which is white in the dark theme and
/// vanishes on the default light page (#2190).
fn caret_fallback(doc: &Document, id: NodeId) -> Color32 {
let chain = doc.ancestors(id);
// Each layer's opacity as drawn: its own times every container's above it.
let drawn: Vec<f32> = {
let mut acc = 1.0f32;
let mut out: Vec<f32> = chain
.iter()
.rev()
.map(|a| {
acc *= doc.node(*a).map_or(1.0, |n| if n.opacity.is_finite() { n.opacity.clamp(0.0, 1.0) } else { 1.0 });
acc
})
.collect();
out.reverse();
out
};
let under = chain.iter().zip(drawn).find_map(|(a, alpha)| {
let n = doc.node(*a)?;
match &n.kind {
NodeKind::Page { background, .. } => Some(*background),
_ => n.fills.iter().rev().find(|p| p.visible).and_then(|p| match &p.kind {
figcraft_color::PaintKind::Solid { color } if color.a * p.opacity * alpha >= 0.5 => Some(*color),
_ => None,
}),
}
});
if under.is_some_and(|c| c.is_dark()) { Color32::WHITE } else { Color32::BLACK }
}
fn text_edit_overlay(app: &FigApp, painter: &egui::Painter, t: &Tokens, doc: &Document, te: &figcraft_engine::TextEdit, zoom: f64) {
let preedit = app.preedit_view();
let edoc: &Document = preedit.map(|p| &*p.doc).unwrap_or(doc);
@@ -242,7 +297,8 @@ fn text_edit_overlay(app: &FigApp, painter: &egui::Painter, t: &Tokens, doc: &Do
let caret = preedit.map(|p| p.cursor).unwrap_or(te.caret);
let blink = (painter.ctx().input(|i| i.time) * 2.0) as i64 % 2 == 0;
if blink || a != b {
painter.line_segment(text.caret(app, caret, zoom), stroke(t.text, 1.0));
let col = edoc.node(te.id).and_then(|n| caret_color(painter.ctx(), n, caret)).unwrap_or_else(|| caret_fallback(edoc, te.id));
painter.line_segment(text.caret(app, caret, zoom), stroke(col, 1.0));
}
painter.ctx().request_repaint_after(std::time::Duration::from_millis(500));
}
@@ -782,3 +838,99 @@ fn pick_outline(app: &FigApp, painter: &egui::Painter, doc: &Document) {
draw_outline(app, painter, doc, p, stroke(crate::handles::PINK, 2.0));
}
}
#[cfg(test)]
mod caret_tests {
use super::*;
use figcraft_color::{Color, Paint};
use figcraft_doc::{Node, NodeId, NodeKind, StyleRun, TextData};
fn text(chars: &str, fills: Vec<Paint>) -> Node {
let mut n = Node::new(NodeId(1), NodeKind::Text(TextData { characters: chars.into(), ..TextData::default() }), "Text", 100.0, 20.0);
n.fills = fills;
n
}
fn hex(s: &str) -> Color {
Color::from_hex(s).unwrap()
}
#[test]
fn red_text_has_a_red_caret() {
let n = text("Caret", vec![Paint::solid(hex("#FF0000"))]);
assert_eq!(caret_fill(&n, 2), Some(hex("#FF0000")));
assert_eq!(caret_color(&egui::Context::default(), &n, 2), Some(Color32::from_rgb(255, 0, 0)));
}
#[test]
fn light_grey_text_keeps_its_own_colour_whatever_is_behind_it() {
// Inside a #222222 frame: the frame's fill plays no part.
let n = text("Caret", vec![Paint::solid(hex("#DDDDDD"))]);
assert_eq!(caret_fill(&n, 5), Some(hex("#DDDDDD")));
assert_eq!(caret_color(&egui::Context::default(), &n, 0), Some(Color32::from_rgb(0xDD, 0xDD, 0xDD)));
}
#[test]
fn the_caret_follows_the_run_of_the_character_before_it() {
let mut n = text("ab cd", vec![Paint::solid(hex("#000000"))]);
if let Some(t) = n.kind.text_mut() {
let mut style = t.style.clone();
style.fills = Some(vec![Paint::solid(hex("#FF0000"))]);
t.runs.push(StyleRun { start: 3, end: 5, style });
}
assert_eq!(caret_fill(&n, 2), Some(hex("#000000")), "after a black character");
assert_eq!(caret_fill(&n, 4), Some(hex("#FF0000")), "after a red character");
assert_eq!(caret_fill(&n, 0), Some(hex("#000000")), "at the start: the first character's");
}
#[test]
fn the_caret_is_opaque_whatever_the_fill_opacity() {
let mut p = Paint::solid(hex("#336699"));
p.opacity = 0.2;
assert_eq!(caret_fill(&text("x", vec![p]), 1).map(|c| c.a), Some(1.0));
}
/// #2190: a caret without a solid fill reads on the page: black on the default light page,
/// white on a dark one (the interface's text colour was white in the dark theme).
#[test]
fn without_a_solid_fill_the_caret_contrasts_with_the_page() {
let mut s = figcraft_engine::Session::new();
let r = s.execute("text.create", &serde_json::json!({"text": "Caret", "x": 0, "y": 0})).unwrap();
let id = figcraft_engine::params::id_of(&r["id"]).unwrap();
assert_eq!(caret_fallback(s.doc().unwrap(), id), Color32::BLACK, "the default light page");
s.execute("page.setBackground", &serde_json::json!({"color": "#1E1E1E"})).unwrap();
assert_eq!(caret_fallback(s.doc().unwrap(), id), Color32::WHITE, "a dark page");
}
/// CodeRabbit on #2163: a dark frame on a light page is the surface under its text.
#[test]
fn without_a_solid_fill_the_caret_contrasts_with_the_frame_around_it() {
let mut s = figcraft_engine::Session::new();
let ex = |s: &mut figcraft_engine::Session, c: &str, p: serde_json::Value| s.execute(c, &p).unwrap();
let f = ex(&mut s, "frame.create", serde_json::json!({"x": 0, "y": 0, "width": 300, "height": 200}));
let f = figcraft_engine::params::id_of(&f["id"]).unwrap();
ex(&mut s, "node.set", serde_json::json!({"id": f, "props": {"fill": "#222222"}}));
let r = ex(&mut s, "text.create", serde_json::json!({"text": "Caret", "x": 20, "y": 20, "parent": f}));
let id = figcraft_engine::params::id_of(&r["id"]).unwrap();
assert_eq!(caret_fallback(s.doc().unwrap(), id), Color32::WHITE, "inside a dark frame on the light page");
ex(&mut s, "node.set", serde_json::json!({"id": f, "props": {"fill": "#F0F0F0"}}));
assert_eq!(caret_fallback(s.doc().unwrap(), id), Color32::BLACK, "inside a light frame");
// A dark frame drawn at 20% opacity shows the light page through it.
ex(&mut s, "node.set", serde_json::json!({"id": f, "props": {"fill": "#222222", "opacity": 0.2}}));
assert_eq!(caret_fallback(s.doc().unwrap(), id), Color32::BLACK, "a faint dark frame on the light page");
// The same through the colour's own alpha.
ex(&mut s, "node.set", serde_json::json!({"id": f, "props": {"fill": "#22222233", "opacity": 1.0}}));
assert_eq!(caret_fallback(s.doc().unwrap(), id), Color32::BLACK, "a dark fill at 20% alpha");
}
#[test]
fn gradient_or_missing_fills_have_no_fill_colour() {
let mut g = Paint::solid(hex("#FF0000"));
g.kind = figcraft_color::PaintKind::Gradient(figcraft_color::Gradient::default_for(figcraft_color::GradientKind::Linear, hex("#FF0000")));
assert_eq!(caret_fill(&text("Caret", vec![g]), 2), None);
assert_eq!(caret_fill(&text("Caret", vec![]), 2), None);
let mut hidden = Paint::solid(hex("#FF0000"));
hidden.visible = false;
assert_eq!(caret_fill(&text("Caret", vec![hidden]), 2), None);
}
}
+62
View File
@@ -441,6 +441,68 @@ fn the_arrow_keys_step_by_the_nudge_amounts_and_fractional_fields_by_their_own()
assert!((rot.abs() - 11.0).abs() < 1e-6, "rotation {rot}: the steps stay after Escape");
}
#[test]
fn the_rotation_field_shows_and_sets_the_rotation_on_the_page() {
let mut s = Session::new();
let f = id(s.execute("frame.create", &json!({"x": 0, "y": 100, "width": 400, "height": 400})).unwrap());
s.execute("node.set", &json!({"ids": [f], "props": {"rotation": 10}})).unwrap();
let r = id(s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 120, "height": 80, "parent": f})).unwrap());
s.execute("node.set", &json!({"ids": [r], "props": {"rotation": -10}})).unwrap();
let b = id(s.execute("shape.rectangle", &json!({"x": 600, "y": 0, "width": 50, "height": 50})).unwrap());
s.execute("select.set", &json!({"ids": [r]})).unwrap();
let mut u = Ui::new(s);
u.ctx.enable_accesskit();
u.frame(vec![]);
let page = |u: &Ui, n: NodeId| figcraft_geom::rotation_degrees(u.app.session.doc().unwrap().world_transform(n));
let local = |u: &Ui, n: NodeId| figcraft_geom::rotation_degrees(u.app.session.doc().unwrap().node(n).unwrap().transform);
assert_eq!(field(&mut u, "Rotation").1, "0°");
type_into(&mut u, "Rotation", "7", Key::Enter);
assert!((page(&u, r) - 7.0).abs() < 1e-6 && (local(&u, r) + 3.0).abs() < 1e-6, "{} {}", page(&u, r), local(&u, r));
assert_eq!(field(&mut u, "Rotation").1, "7°");
// Arrows step the shown value.
let shift = Modifiers { shift: true, ..Modifiers::NONE };
let (p, _) = field(&mut u, "Rotation");
click(&mut u, p);
key(&mut u, Key::ArrowUp, Modifiers::NONE);
key(&mut u, Key::ArrowUp, shift);
key(&mut u, Key::Escape, Modifiers::NONE);
assert!((page(&u, r) - 18.0).abs() < 1e-6, "{}", page(&u, r));
assert_eq!(field(&mut u, "Rotation").1, "18°");
// Scrubbing is one undo step.
let steps = undo_steps(&u);
scrub(&mut u, "Rotation", 15.0, Modifiers::NONE);
assert!((page(&u, r) - 33.0).abs() < 1e-6, "{}", page(&u, r));
assert_eq!(undo_steps(&u), steps + 1);
// Mixed: layers in differently turned parents agree when their page angles do.
u.app.session.execute("node.set", &json!({"ids": [b], "props": {"rotation": 33}})).unwrap();
u.app.session.execute("select.set", &json!({"ids": [r, b]})).unwrap();
assert_eq!(field(&mut u, "Rotation").1, "33°");
u.app.session.execute("node.set", &json!({"ids": [b], "props": {"rotation": 20}})).unwrap();
assert_eq!(field(&mut u, "Rotation").1, "Mixed");
let steps = undo_steps(&u);
type_into(&mut u, "Rotation", "+10", Key::Enter);
assert!((page(&u, r) - 43.0).abs() < 1e-6 && (page(&u, b) - 30.0).abs() < 1e-6, "{} {}", page(&u, r), page(&u, b));
assert_eq!(undo_steps(&u), steps + 1);
}
#[test]
fn a_relative_rotation_edit_turns_a_selected_parent_before_its_child_whatever_the_selection_order() {
let mut s = Session::new();
let f = id(s.execute("frame.create", &json!({"x": 0, "y": 0, "width": 400, "height": 400})).unwrap());
let c = id(s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 120, "height": 80, "parent": f})).unwrap());
s.execute("node.set", &json!({"ids": [f], "props": {"rotation": 10}})).unwrap();
s.execute("node.set", &json!({"ids": [c], "props": {"absoluteRotation": 30}})).unwrap();
// The child first, then its parent.
s.execute("select.set", &json!({"ids": [c, f]})).unwrap();
let mut u = Ui::new(s);
u.ctx.enable_accesskit();
u.frame(vec![]);
let page = |u: &Ui, n: NodeId| figcraft_geom::rotation_degrees(u.app.session.doc().unwrap().world_transform(n));
assert_eq!(field(&mut u, "Rotation").1, "Mixed");
type_into(&mut u, "Rotation", "+10", Key::Enter);
assert!((page(&u, f) - 20.0).abs() < 1e-6 && (page(&u, c) - 40.0).abs() < 1e-6, "{} {}", page(&u, f), page(&u, c));
}
#[test]
fn arithmetic_commits_tab_moves_on_and_escape_restores() {
let (mut u, a, _) = setup();
+2
View File
@@ -254,6 +254,8 @@ mod save_as_tests;
#[cfg(test)]
mod select_all_tests;
#[cfg(test)]
mod selection_colors_tests;
#[cfg(test)]
mod shortcut_keys_tests;
#[cfg(test)]
mod shortcuts_tests;
+13 -7
View File
@@ -75,7 +75,12 @@ impl FigApp {
None => return,
};
let Ok(doc) = self.session.doc() else { return };
let values: Vec<(NodeId, f64)> = ids.iter().filter_map(|i| Some((*i, rel.apply(shown(doc.node(*i)?))?))).collect();
let mut values: Vec<(NodeId, f64)> = ids.iter().filter_map(|i| Some((*i, rel.apply(shown(doc.node(*i)?))?))).collect();
if key == "absoluteRotation" {
// A page angle depends on the parents': turn a selected parent before the layers in it
// (as `node.set` orders a multi-id call), whatever order the selection is in.
values.sort_by_key(|(i, _)| doc.ancestors(*i).len());
}
if values.is_empty() || self.session.begin_interaction("Edit").is_err() {
return;
}
@@ -627,8 +632,9 @@ fn y_of(doc: &Document, n: &Node) -> f64 {
(doc.frame_relative(n.id).as_coeffs()[5] * 100.0).round() / 100.0
}
fn rot_of(n: &Node) -> f64 {
(figcraft_geom::rotation_degrees(n.transform) * 100.0).round() / 100.0
/// The layer's rotation on the page (its own angle plus its parents'), what the field shows.
fn rot_of(doc: &Document, n: &Node) -> f64 {
(figcraft_geom::rotation_degrees(doc.world_transform(n.id)) * 100.0).round() / 100.0
}
pub(crate) fn position_values(ctx: &egui::Context, doc: &Arc<Document>, sel: &[NodeId]) -> PositionValues {
@@ -637,7 +643,7 @@ pub(crate) fn position_values(ctx: &egui::Context, doc: &Arc<Document>, sel: &[N
can_align: figcraft_engine::cmd::arrange::can_align(doc, sel),
x: common(doc, sel, |n| x_of(doc, n)),
y: common(doc, sel, |n| y_of(doc, n)),
rot: common(doc, sel, rot_of),
rot: common(doc, sel, |n| rot_of(doc, n)),
parent_al: sel.iter().all(|i| doc.node(*i).and_then(parent).is_some_and(|p| p.layout.is_some())),
absolute: common(doc, sel, |n| n.child_layout.absolute),
// Constraints: children of frames without auto layout, or ignoring it.
@@ -655,7 +661,7 @@ fn position_fields(app: &mut FigApp, ui: &mut Ui, doc: &Arc<Document>, sel: &[No
let col = widgets::col_width(ui.available_width());
align_row(app, ui, sel, pv.can_align, col);
position_row(app, ui, doc, sel, &pv, col);
rotation_row(app, ui, sel, pv.rot, col);
rotation_row(app, ui, doc, sel, pv.rot, col);
if pv.in_frame {
constraints_row(app, ui, sel, pv.constraints, col);
}
@@ -732,12 +738,12 @@ fn position_row(app: &mut FigApp, ui: &mut Ui, doc: &Document, sel: &[NodeId], p
}
/// Rotation, with the rotate and flip buttons.
fn rotation_row(app: &mut FigApp, ui: &mut Ui, sel: &[NodeId], rot: Option<f64>, col: f32) {
fn rotation_row(app: &mut FigApp, ui: &mut Ui, doc: &Document, sel: &[NodeId], rot: Option<f64>, col: f32) {
let ids = sel.to_vec();
widgets::sublabels(ui, tr("Rotation"), None);
row(ui, 32.0, |ui| {
let e = widgets::number_field_mixed(ui, Id::unique("pos_rot"), Lead::Icon(Icon::Angle, tr("Rotation")), rot, "°", col, 1.0);
app.field_of(&ids, "rotation", e, rot_of, |v| json!(v));
app.field_of(&ids, "absoluteRotation", e, |n| rot_of(doc, n), |v| json!(v));
let items = [
(Icon::Rotate, tr("Rotate 90° right")),
(Icon::FlipH, crate::shortcuts::tip(tr("Flip horizontal"), "object.flipH")),
@@ -65,7 +65,7 @@ pub(crate) fn toggle(app: &mut FigApp, targets: Vec<PaintTarget>, response: Opti
}
}
/// Draw the selection-colour groups (at least two): swatch opens the picker, hex and opacity
/// Draw the selection-colour groups (two, or one when a selected layer has children): swatch opens the picker, hex and opacity
/// edits, style/variable detach/apply/bind, a style from this file or an enabled library, Create
/// style, and “select layers with this color”; disabled during an interaction.
pub fn section(app: &mut FigApp, ui: &mut Ui, doc: &Arc<Document>, ids: &[NodeId]) {
@@ -73,7 +73,10 @@ pub fn section(app: &mut FigApp, ui: &mut Ui, doc: &Arc<Document>, ids: &[NodeId
let interacting = ds.interaction.is_some();
let uid = ds.uid;
let colors = colors(ui, uid, doc, ids, interacting);
if colors.len() < 2 {
// Measured in Figma: two distinct colours show the section; one colour does too when a selected
// layer has children (frame, group, component, instance).
let has_children = ids.iter().any(|id| doc.node(*id).is_some_and(|n| !n.children.is_empty()));
if colors.len() < 2 && !(colors.len() == 1 && has_children) {
ui.data_mut(|d| d.remove::<CreateForm>(create_form_id()));
return;
}
@@ -0,0 +1,96 @@
//! When the Design panel shows Selection colors (#2188): measured in Figma's web app, a layer with
//! children shows the section from one distinct colour, while layers without children need two.
//! Driven through egui headless; each row has a "Select layers with this color" button.
use egui::accesskit::Role;
use figcraft_doc::NodeId;
use figcraft_engine::Session;
use serde_json::{Value, json};
use crate::layers_drag_tests::Ui;
const ROW_BUTTON: &str = "Select layers with this color";
fn id(v: Value) -> NodeId {
NodeId(v["id"].as_u64().unwrap())
}
fn rect(s: &mut Session, x: i32, color: &str, parent: Option<NodeId>) -> NodeId {
let mut p = json!({"x": x, "y": 0, "width": 40, "height": 40});
if let Some(parent) = parent {
p["parent"] = json!(parent);
}
let r = id(s.execute("shape.rectangle", &p).unwrap());
s.execute("fill.set", &json!({"ids": [r], "color": color})).unwrap();
r
}
fn frame(s: &mut Session, fill: Option<&str>) -> NodeId {
let f = id(s.execute("frame.create", &json!({"x": 0, "y": 0, "width": 200, "height": 200})).unwrap());
match fill {
Some(c) => s.execute("fill.set", &json!({"ids": [f], "color": c})).unwrap(),
None => s.execute("fill.remove", &json!({"ids": [f], "index": 0})).unwrap(),
};
f
}
/// How many Selection colors rows the Design panel shows with `ids` selected.
fn rows(mut s: Session, ids: &[NodeId]) -> usize {
s.execute("select.set", &json!({"ids": ids})).unwrap();
let mut u = Ui::new(s);
u.ctx.enable_accesskit();
u.frame(vec![]);
let out = u.frame_output(vec![]);
let nodes = out.platform_output.accesskit_update.expect("an AccessKit update").nodes;
nodes.iter().filter(|(_, n)| n.role() == Role::Button && n.label() == Some(ROW_BUTTON)).count()
}
#[test]
fn a_frame_holding_one_red_layer_shows_selection_colors_with_one_row() {
let mut s = Session::new();
let f = frame(&mut s, None);
rect(&mut s, 10, "#FF0000", Some(f));
assert_eq!(rows(s, &[f]), 1);
}
#[test]
fn a_group_of_two_red_layers_shows_one_row() {
let mut s = Session::new();
let a = rect(&mut s, 0, "#FF0000", None);
let b = rect(&mut s, 60, "#FF0000", None);
s.execute("select.set", &json!({"ids": [a, b]})).unwrap();
let g = id(s.execute("object.group", &json!({"ids": [a, b]})).unwrap());
assert_eq!(rows(s, &[g]), 1);
}
#[test]
fn an_instance_whose_child_has_one_fill_shows_selection_colors() {
let mut s = Session::new();
let f = frame(&mut s, None);
rect(&mut s, 10, "#FF0000", Some(f));
let c = id(s.execute("component.create", &json!({"ids": [f]})).unwrap());
let i = id(s.execute("instance.create", &json!({"component": c, "x": 400, "y": 0})).unwrap());
assert_eq!(rows(s, &[i]), 1);
}
#[test]
fn one_layer_or_two_of_the_same_colour_without_children_hide_it() {
let mut s = Session::new();
let a = rect(&mut s, 0, "#FF0000", None);
assert_eq!(rows(s, &[a]), 0, "one red rectangle");
let mut s = Session::new();
let a = rect(&mut s, 0, "#FF0000", None);
let b = rect(&mut s, 60, "#FF0000", None);
assert_eq!(rows(s, &[a, b]), 0, "two red rectangles");
let mut s = Session::new();
let g = frame(&mut s, Some("#00FF00"));
assert_eq!(rows(s, &[g]), 0, "a childless green frame");
}
#[test]
fn two_loose_layers_of_different_colours_show_two_rows() {
let mut s = Session::new();
let a = rect(&mut s, 0, "#FF0000", None);
let b = rect(&mut s, 60, "#0000FF", None);
assert_eq!(rows(s, &[a, b]), 2);
}
+1
View File
@@ -67,6 +67,7 @@ state are answered without a frame (about half a second each), while `ui.screens
Coordinates are page units, y down. `x`/`y` in `node.set`/`node.create` are relative to the parent
frame (groups have no coordinate space of their own).
`rotation` in `node.set` is the layer's angle to its parent; `absoluteRotation` sets its rotation on the page (what the Design panel's field shows); a call takes one of the two.
**Windows.** The desktop app can show files in several windows (`window.new`). Every method takes
an optional `window` (an id from `window.list`; `0` is the main window) and then runs in that
+1
View File
@@ -172,6 +172,7 @@ Or in a project's `.mcp.json`:
- `create_node` and `set_properties` take `x`/`y` **relative to the parent frame** (the page when
there is none, so they are page coordinates then). Groups and boolean groups have no coordinate
space of their own: a layer in a group is placed in the frame (or on the page) the group is in.
`rotation` is the layer's angle to its parent (Figma's plugin API `rotation` is the same); `absoluteRotation` sets its rotation on the page, what the Design panel's field shows; a call takes one of the two.
`inspect_document` reports `x`/`y` the same way, plus `absoluteBounds` in page coordinates.
In `props`, `fill` and `stroke` also accept `"none"` (either case) or `null` as no paint, the
same as an empty `fills`/`strokes` list, so an outline-only shape can be made in one call.
+12 -4
View File
File diff suppressed because one or more lines are too long