diff --git a/.github/workflows/sonarcloud.yml b/.github/workflows/sonarcloud.yml index 50616c871..a8872386f 100644 --- a/.github/workflows/sonarcloud.yml +++ b/.github/workflows/sonarcloud.yml @@ -16,8 +16,8 @@ concurrency: jobs: sonarcloud: - # Pin the coverage setup that checks out this repo's pinned craft-i18n data. - uses: storytold/craft-common-actions/.github/workflows/sonarcloud.yml@ea24c9c24e1997238334182160f60e602e5bce32 + # Pin the coverage setup that provisions test data and fetches locked dependencies before offline metadata tests. + uses: storytold/craft-common-actions/.github/workflows/sonarcloud.yml@5008f8cd1b011b35eed223a7d058d7a8e9075ef6 with: # The shared coverage archive's shards omit the CLI executable used by integration tests. # Run this repository's suite in one instrumented job and provide its pinned test data. diff --git a/crates/doc/src/geometry.rs b/crates/doc/src/geometry.rs index 479ca439b..cc1a218e9 100644 --- a/crates/doc/src/geometry.rs +++ b/crates/doc/src/geometry.rs @@ -152,7 +152,7 @@ fn near_path(path: &BezPath, p: Point, dist: f64) -> bool { /// boolean groups are hit where their `result` is. pub fn hit_leaf(doc: &Document, page: NodeId, pt: Point, tol: f64, result: BoolResult) -> Option { let p = doc.node(page)?; - p.children.iter().rev().find_map(|c| hit_rec(doc, *c, pt, tol, 0, result, None).filter(|_| !masked_out(doc, p, *c, pt))) + p.children.iter().rev().find_map(|c| hit_rec(doc, *c, pt, tol, 0, result, None, HitOpts::default()).filter(|_| !masked_out(doc, p, *c, pt))) } /// Whether child `c` of `parent` is masked at `pt`: a visible mask below it (the nearest mask @@ -175,7 +175,7 @@ fn covers(doc: &Document, id: NodeId, n: &Node, pt: Point, depth: usize) -> bool /// Like [`hit_leaf`], but only within layer `root` (it included). pub fn hit_in(doc: &Document, root: NodeId, pt: Point, tol: f64, result: BoolResult) -> Option { - hit_rec(doc, root, pt, tol, 0, result, None) + hit_rec(doc, root, pt, tol, 0, result, None, HitOpts::default()) } /// [`hit_leaf`] (or [`hit_in`] for a `root` that isn't a page) in outline mode: shapes are hit @@ -185,8 +185,8 @@ pub fn hit_in(doc: &Document, root: NodeId, pt: Point, tol: f64, result: BoolRes /// when it shows them, and every layer on the edge of its box when it shows object bounds. pub fn hit_outlines(doc: &Document, root: NodeId, pt: Point, tol: f64, result: BoolResult, also: OutlineHits) -> Option { match doc.node(root) { - Some(p) if p.is_page() => p.children.iter().rev().find_map(|c| hit_rec(doc, *c, pt, tol, 0, result, Some(also))), - _ => hit_rec(doc, root, pt, tol, 0, result, Some(also)), + Some(p) if p.is_page() => p.children.iter().rev().find_map(|c| hit_rec(doc, *c, pt, tol, 0, result, Some(also), HitOpts::default())), + _ => hit_rec(doc, root, pt, tol, 0, result, Some(also), HitOpts::default()), } } @@ -204,13 +204,30 @@ fn on_box_edge(doc: &Document, id: NodeId, n: &Node, pt: Point, tol: f64) -> boo r.inflate(tol, tol).contains(lp) && !(r.width() > 2.0 * tol && r.height() > 2.0 * tol && r.inflate(-tol, -tol).contains(lp)) } -fn hit_rec(doc: &Document, id: NodeId, pt: Point, tol: f64, depth: usize, result: BoolResult, also: Option) -> Option { +/// Options for the hit tests that the plain pick never sets. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct HitOpts { + /// Reach locked layers (and what a locked frame holds) too. A click, hover or marquee never + /// does; the Select layer list does. + pub locked: bool, +} + +fn hit_rec( + doc: &Document, + id: NodeId, + pt: Point, + tol: f64, + depth: usize, + result: BoolResult, + also: Option, + opts: HitOpts, +) -> Option { if depth > 512 { return None; } let n = doc.node(id)?; let outline = also.is_some(); - if (!n.visible && !also.is_some_and(|a| a.hidden)) || n.locked { + if (!n.visible && !also.is_some_and(|a| a.hidden)) || n.locked && !opts.locked { return None; } if let NodeKind::Section { contents_hidden: true } = n.kind { @@ -228,7 +245,7 @@ fn hit_rec(doc: &Document, id: NodeId, pt: Point, tol: f64, depth: usize, result return None; } for c in n.paint_order().rev() { - if let Some(h) = hit_rec(doc, c, pt, tol, depth + 1, result, also).filter(|_| !masked_out(doc, n, c, pt)) { + if let Some(h) = hit_rec(doc, c, pt, tol, depth + 1, result, also, opts).filter(|_| !masked_out(doc, n, c, pt)) { return Some(h); } } @@ -239,14 +256,20 @@ fn hit_rec(doc: &Document, id: NodeId, pt: Point, tol: f64, depth: usize, result None } -/// Every visible, unlocked layer under `pt` (page coordinates) with its depth below the page, in -/// layer-tree order (each layer before what it contains, the front-most first): what -/// "Select layer" in the context menu lists. Clip content is honoured; boolean groups (hit where -/// their `result` is) and sections with hidden contents count as one layer. +/// Every visible, unlocked layer under `pt`: [`layers_at_opts`] with the default options. pub fn layers_at(doc: &Document, page: NodeId, pt: Point, tol: f64, result: BoolResult) -> Vec<(NodeId, usize)> { - fn rec(doc: &Document, id: NodeId, pt: Point, tol: f64, depth: usize, result: BoolResult, out: &mut Vec<(NodeId, usize)>) { + layers_at_opts(doc, page, pt, tol, result, HitOpts::default()) +} + +/// Every visible layer under `pt` (page coordinates) with its depth below the page, in +/// layer-tree order (each layer before what it contains, the front-most first): what +/// "Select layer" in the context menu lists. Locked layers are left out unless `opts.locked`. +/// Clip content is honoured; boolean groups (hit where their `result` is) and sections with +/// hidden contents count as one layer. +pub fn layers_at_opts(doc: &Document, page: NodeId, pt: Point, tol: f64, result: BoolResult, opts: HitOpts) -> Vec<(NodeId, usize)> { + fn rec(doc: &Document, id: NodeId, pt: Point, tol: f64, depth: usize, result: BoolResult, opts: HitOpts, out: &mut Vec<(NodeId, usize)>) { let Some(n) = doc.node(id) else { return }; - if !n.visible || n.locked || depth > 512 { + if !n.visible || n.locked && !opts.locked || depth > 512 { return; } let clips = n.clip && n.kind.is_frame_like(); @@ -256,14 +279,14 @@ pub fn layers_at(doc: &Document, page: NodeId, pt: Point, tol: f64, result: Bool let at = out.len(); let whole = matches!(n.kind, NodeKind::BooleanOp { .. } | NodeKind::Section { contents_hidden: true }); if whole { - if hit_rec(doc, id, pt, tol, depth, result, None).is_some() { + if hit_rec(doc, id, pt, tol, depth, result, None, opts).is_some() { out.push((id, depth)); } return; } for c in n.paint_order().rev() { let before = out.len(); - rec(doc, c, pt, tol, depth + 1, result, out); + rec(doc, c, pt, tol, depth + 1, result, opts, out); if out.len() > before && masked_out(doc, n, c, pt) { out.truncate(before); } @@ -276,7 +299,7 @@ pub fn layers_at(doc: &Document, page: NodeId, pt: Point, tol: f64, result: Bool if let Some(p) = doc.node(page) { for c in p.children.iter().rev() { let before = out.len(); - rec(doc, *c, pt, tol, 0, result, &mut out); + rec(doc, *c, pt, tol, 0, result, opts, &mut out); if out.len() > before && masked_out(doc, p, *c, pt) { out.truncate(before); } diff --git a/crates/engine/src/al_behaviour_tests.rs b/crates/engine/src/al_behaviour_tests.rs index 514a39fdc..49950de6d 100644 --- a/crates/engine/src/al_behaviour_tests.rs +++ b/crates/engine/src/al_behaviour_tests.rs @@ -336,3 +336,36 @@ fn auto_layout_keys_beside_no_auto_layout_are_refused() { set(&mut s, f, json!({"layout": null, "name": "Plain"})); assert!(s.doc().unwrap().node(f).unwrap().layout.is_none()); } + +#[test] +fn align_is_unavailable_for_a_child_in_an_auto_layout_flow() { + use crate::cmd::arrange::{align_blocked_by_auto_layout, can_align}; + let mut s = Session::new(); + let f = al_frame(&mut s, json!({"gap": 10})); + let a = rect(&mut s, f, 20.0, 20.0, "#ff0000"); + let b = rect(&mut s, f, 20.0, 20.0, "#00ff00"); + let at = |s: &Session, i: NodeId| s.doc().unwrap().world_bounds(i).unwrap(); + let (before_a, before_b) = (at(&s, a), at(&s, b)); + assert_eq!(before_b.x0, 30.0, "the layout placed the second one after the first"); + let doc = s.doc().unwrap(); + assert!(!can_align(doc, &[b]), "Align is greyed out for one child of the frame"); + assert!(align_blocked_by_auto_layout(doc, &[b]), "because its frame places it"); + for cmd in ["align.left", "align.hcenter", "align.right", "align.top", "align.vcenter", "align.bottom"] { + s.execute(cmd, &json!({"ids": [b]})).unwrap(); + assert_eq!((at(&s, a), at(&s, b)), (before_a, before_b), "{cmd} leaves the layout alone"); + } +} + +#[test] +fn an_absolute_child_of_an_auto_layout_frame_still_aligns_to_it() { + use crate::cmd::arrange::{align_blocked_by_auto_layout, can_align}; + let mut s = Session::new(); + let f = al_frame(&mut s, json!({})); + let kid = rect(&mut s, f, 20.0, 20.0, "#ff0000"); + set(&mut s, kid, json!({"absolute": true})); + let doc = s.doc().unwrap(); + assert!(can_align(doc, &[kid])); + assert!(!align_blocked_by_auto_layout(doc, &[kid])); + s.execute("align.right", &json!({"ids": [kid]})).unwrap(); + assert_eq!(s.doc().unwrap().world_bounds(kid).unwrap().x1, 200.0); +} diff --git a/crates/engine/src/canvas/shape_handles.rs b/crates/engine/src/canvas/shape_handles.rs index 6ddd99943..b286010ba 100644 --- a/crates/engine/src/canvas/shape_handles.rs +++ b/crates/engine/src/canvas/shape_handles.rs @@ -6,12 +6,16 @@ //! [`INSET_PX`] in, so it can be grabbed at radius 0). Dragging it along the bisector sets the //! radius of every corner; with Alt, only that corner of a rectangle or frame (the documentation //! is silent on Alt). +//! - **Count**: a polygon's or star's sits on its first point clockwise from the top; dragging it +//! sets the count from the pointer's angle about the centre, measured clockwise from the top +//! point: `round(360 / angle)`, clamped to 3 to 60 (measured in Figma's web app, 2026-11-12; a +//! polygon's maximum wasn't read). //! - **Ratio**: a star's sits on its first inner point; dragging it towards or away from the //! centre sets the inner radius as a share of the outer one. //! //! Positions are in page coordinates and work for rotated and flipped layers at any zoom; the //! handles hide on layers smaller than [`MIN_PX`] on screen. The Move tool's gesture (`tools.rs`) -//! writes the result through `node.set` (`cornerRadius`, `topLeftRadius`…, `innerRadius`), one +//! writes the result through `node.set` (`cornerRadius`, `topLeftRadius`…, `innerRadius`, `pointCount`), one //! undo step per drag. use figcraft_doc::{Document, Node, NodeId, NodeKind}; @@ -20,18 +24,22 @@ use serde::Serialize; use serde_json::{Map, Value, json}; /// One shape handle: a corner's radius (corner index: tl, tr, br, bl; 0 for a polygon's or -/// star's top point) or a star's ratio. +/// star's top point), a star's ratio or a polygon's or star's point count. #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] #[serde(rename_all = "camelCase", tag = "kind")] pub enum ShapeHandle { Radius { corner: usize }, Ratio, + Count, } /// Layers smaller than this on screen (either side, in pixels) show no shape handles. pub const MIN_PX: f64 = 48.0; /// How far in from its corner a handle sits at least (screen pixels). pub const INSET_PX: f64 = 10.0; +/// The fewest and most points the Count handle sets (a star's range in the help center). +const COUNT_MIN: f64 = 3.0; +const COUNT_MAX: f64 = 60.0; /// How near the pointer must be to pick a handle (screen pixels). const HIT_PX: f64 = 6.0; @@ -113,6 +121,34 @@ fn ratio_point(n: &Node, count: u32, ratio: f64) -> Option { figcraft_geom::star_points(n.width, n.height, count, ratio).get(1).copied() } +/// The Count handle (local): a polygon's vertex 1 or a star's outer point 1, the first clockwise +/// from the top. +fn count_point(n: &Node) -> Option { + match n.kind { + NodeKind::Polygon { count } => figcraft_geom::polygon_points(n.width, n.height, count).get(1).copied(), + NodeKind::Star { count, inner_ratio } => figcraft_geom::star_points(n.width, n.height, count, inner_ratio).get(2).copied(), + _ => None, + } +} + +/// The count a pointer at local point `q` sets: `round(360 / angle)` for its clockwise angle from +/// the top about the centre, on the unit circle the shape's box maps from; finite for any `q`. +fn count_at(n: &Node, q: Point) -> Option { + let (rx, ry) = (n.width / 2.0, n.height / 2.0); + if rx.partial_cmp(&0.0) != Some(std::cmp::Ordering::Greater) || ry.partial_cmp(&0.0) != Some(std::cmp::Ordering::Greater) { + return None; + } + let (x, y) = (q.x / rx - 1.0, q.y / ry - 1.0); + // On the centre there is no direction (atan2 of two zeros would read as 180 degrees): treat it + // as no angle, the most points. + if x.hypot(y) < 1e-9 { + return Some(COUNT_MAX); + } + let angle = x.atan2(-y).rem_euclid(std::f64::consts::TAU).to_degrees(); + let count = (360.0 / angle.max(1e-9)).round(); + count.is_finite().then(|| count.clamp(COUNT_MIN, COUNT_MAX)) +} + /// The shape handles of the selection at `zoom` (screen pixels per page unit): each handle and /// where it is (page coordinates). pub fn handles(doc: &Document, sel: &[NodeId], zoom: f64) -> Vec<(ShapeHandle, [f64; 2])> { @@ -128,6 +164,9 @@ pub fn handles(doc: &Document, sel: &[NodeId], zoom: f64) -> Vec<(ShapeHandle, [ { out.push((ShapeHandle::Ratio, pt(p))); } + if let Some(p) = count_point(n) { + out.push((ShapeHandle::Count, pt(p))); + } out } @@ -160,6 +199,10 @@ pub fn drag(doc: &Document, id: NodeId, h: ShapeHandle, p: Point, alt: bool) -> }; Some(Map::from_iter([(key.to_string(), json!(r))])) } + ShapeHandle::Count => { + count_point(n)?; + Some(Map::from_iter([("pointCount".to_string(), json!(count_at(n, q)?))])) + } ShapeHandle::Ratio => { let NodeKind::Star { count, .. } = n.kind else { return None }; // Along the inner point's ray, measured on the unit circle the star's box maps from. @@ -172,11 +215,12 @@ pub fn drag(doc: &Document, id: NodeId, h: ShapeHandle, p: Point, alt: bool) -> } } -/// The live readout while dragging `h` of `id`: the corner's radius, or the star's ratio in percent. +/// The live readout while dragging `h` of `id`: the corner's radius, the star's ratio in percent or the point count. pub fn value(doc: &Document, id: NodeId, h: ShapeHandle) -> Option { let n = doc.node(id)?; let v = match (h, &n.kind) { (ShapeHandle::Ratio, NodeKind::Star { inner_ratio, .. }) => inner_ratio * 100.0, + (ShapeHandle::Count, NodeKind::Polygon { count }) | (ShapeHandle::Count, NodeKind::Star { count, .. }) => f64::from(*count), (ShapeHandle::Radius { corner }, _) => corners(n).into_iter().nth(corner).map(|(c, r)| r.clamp(0.0, c.max_r))?, _ => return None, }; diff --git a/crates/engine/src/canvas/tools.rs b/crates/engine/src/canvas/tools.rs index d9c265f88..f876885ef 100644 --- a/crates/engine/src/canvas/tools.rs +++ b/crates/engine/src/canvas/tools.rs @@ -586,8 +586,9 @@ pub struct ToolState { /// Vector edit mode's pen: where the last press that started something new (no path being /// drawn) was, and the undo depth before it, so a double-click there takes that edit back. pub(crate) pen_press: Option<(Point, usize)>, - /// The Scale tool's anchor: column and row (0 start, 1 middle, 2 end) of the point of the - /// selection box that stays put (`tool.scaleAnchor`). + /// The Scale tool's origin: column and row (0 start, 1 middle, 2 end) of the point of the + /// selection box that stays put when the Scale field sets a factor (`tool.scaleAnchor`; the + /// centre, `(1, 1)`, until set). Handle drags ignore it and pivot on the opposite handle. pub scale_anchor: (u8, u8), /// The last drag move handled (a held button repeats it every frame). pub(crate) last_move: Option, diff --git a/crates/engine/src/canvas/tools/drag.rs b/crates/engine/src/canvas/tools/drag.rs index ea336a142..2208f74ee 100644 --- a/crates/engine/src/canvas/tools/drag.rs +++ b/crates/engine/src/canvas/tools/drag.rs @@ -640,7 +640,7 @@ impl Session { /// text included, children by the same factor whatever their constraints. fn scale_drag(&mut self, ev: &PointerEvent, r: &ResizeStart, q: Point, guides: Vec) -> Result<()> { let (frame, w0, h0) = r.frame; - let Some((k, pivot)) = scale_factor(r.handle, q, w0, h0, self.tool.scale_anchor, ev.alt) else { return Ok(()) }; + let Some((k, pivot)) = scale_factor(r.handle, q, w0, h0, ev.alt) else { return Ok(()) }; let nodes = r.nodes.clone(); let inv = frame.inverse(); // A layer's place in the box scales about the pivot; a negative factor turns it over. diff --git a/crates/engine/src/canvas/tools/handles.rs b/crates/engine/src/canvas/tools/handles.rs index 6a871ceaf..65de07b52 100644 --- a/crates/engine/src/canvas/tools/handles.rs +++ b/crates/engine/src/canvas/tools/handles.rs @@ -392,30 +392,22 @@ fn opposite(h: Handle) -> Handle { } /// The Scale tool's factor and pivot (in the box's axes) for dragging `handle` of a `w0`×`h0` box -/// to `q`. The pivot is the anchor point (`anchor`: column, row), or the opposite handle when the -/// anchor lies on the side being dragged, or the centre (`from_center`). Corners follow the axis -/// that moved the most; a negative factor flips. None when the box has no size to scale by. -pub(crate) fn scale_factor(handle: Handle, q: Point, w0: f64, h0: f64, anchor: (u8, u8), from_center: bool) -> Option<(f64, Point)> { +/// to `q`. The pivot is the opposite handle's point, or the centre (`from_center`); the origin grid +/// never decides it (measured in Figma's web app, 2026-11-09). Corners follow the axis that moved +/// the most; a negative factor flips. None when the box has no size to scale by. +pub(crate) fn scale_factor(handle: Handle, q: Point, w0: f64, h0: f64, from_center: bool) -> Option<(f64, Point)> { const EPS: f64 = 1e-9; if !(q.x.is_finite() && q.y.is_finite() && w0.is_finite() && h0.is_finite()) || matches!(handle, Handle::Rotate(_)) { return None; } let h = handle_point(handle, w0, h0); - let anchor_pt = anchor_in_box(anchor, w0, h0); // The axes the handle moves along. let (ax_x, ax_y) = match handle { Handle::Edge(0) | Handle::Edge(2) => (false, true), Handle::Edge(_) => (true, false), _ => (true, true), }; - let on_side = (ax_x && (anchor_pt.x - h.x).abs() < EPS) || (ax_y && (anchor_pt.y - h.y).abs() < EPS); - let pivot = if from_center { - Point::new(w0 / 2.0, h0 / 2.0) - } else if on_side { - handle_point(opposite(handle), w0, h0) - } else { - anchor_pt - }; + let pivot = if from_center { Point::new(w0 / 2.0, h0 / 2.0) } else { handle_point(opposite(handle), w0, h0) }; let ratio = |on: bool, to: f64, from: f64, p: f64| (on && (from - p).abs() > EPS).then(|| (to - p) / (from - p)); let kx = ratio(ax_x, q.x, h.x, pivot.x); let ky = ratio(ax_y, q.y, h.y, pivot.y); diff --git a/crates/engine/src/cmd/arrange.rs b/crates/engine/src/cmd/arrange.rs index 88146ea95..d32064271 100644 --- a/crates/engine/src/cmd/arrange.rs +++ b/crates/engine/src/cmd/arrange.rs @@ -164,12 +164,27 @@ pub fn can_align(doc: &Document, ids: &[NodeId]) -> bool { align_target(doc, &roots(doc, ids)).is_some() } +/// Whether `ids` is one layer that its auto layout frame places: Figma greys out Align for it, +/// since the frame decides where it goes (measured in Figma's web app, 2026-11-12). +pub fn align_blocked_by_auto_layout(doc: &Document, ids: &[NodeId]) -> bool { + matches!(roots(doc, ids).as_slice(), [id] if in_auto_layout_flow(doc, *id)) +} + +/// Whether the layer sits in an auto layout frame and takes part in its flow (not absolutely positioned). +fn in_auto_layout_flow(doc: &Document, id: NodeId) -> bool { + let Some(n) = doc.node(id) else { return false }; + !n.child_layout.absolute && n.parent.and_then(|p| doc.node(p)).is_some_and(|p| p.layout.is_some()) +} + /// What `roots` align to: one layer to its parent frame, several to their combined bounds. fn align_target(doc: &Document, roots: &[NodeId]) -> Option { match roots { [] => None, [id] => { let parent = doc.node(*id)?.parent.filter(|pp| !doc.node(*pp).is_some_and(Node::is_page))?; + if in_auto_layout_flow(doc, *id) { + return None; + } Some(doc.world_bounds(parent).unwrap_or_default()) } _ => Some(doc.bounds_of(roots).unwrap_or_default()), @@ -223,53 +238,25 @@ fn distribute(s: &mut Session, p: &Value, horizontal: bool) -> Result { ok() } -/// Tidy up: snap the selection into a grid of rows/columns with even spacing. +/// Tidy up: even the gaps of a row, a column or a grid, keeping the order and sizes (see +/// `selection::tidy`). Nothing moves, and no undo step is added, when it is unavailable. fn tidy(s: &mut Session, p: &Value) -> Result { let ids = req_targets("arrange.tidy", s, p)?; + let spacing = num(p, "spacing"); + if spacing.is_some_and(|v| !v.is_finite() || v.abs() > 1_000_000.0) { + return Err(bad("arrange.tidy", "spacing out of range")); + } + let snap = s.ds()?.view.snap_pixel; + let moves = crate::tidy::tidy_moves(s.doc()?, &ids, spacing, snap); + if moves.is_empty() { + return ok(); + } + if moves.iter().any(|(_, dx, dy)| !dx.is_finite() || !dy.is_finite()) { + return Err(bad("arrange.tidy", "non-finite result")); + } let doc = s.doc_mut()?; - let ids = roots(doc, &ids); - let mut items: Vec<(NodeId, Rect)> = ids.iter().filter_map(|i| doc.world_bounds(*i).map(|b| (*i, b))).collect(); - if items.len() < 2 { - return ok(); - } - // Group into rows by vertical centre overlap. - items.sort_by(|a, b| a.1.y0.total_cmp(&b.1.y0)); - let mut rows: Vec> = Vec::new(); - for it in items { - match rows.last_mut() { - Some(row) if row.iter().any(|(_, b)| it.1.center().y < b.y1 && it.1.center().y > b.y0) => row.push(it), - _ => rows.push(vec![it]), - } - } - let all: Vec = rows.iter().flatten().map(|(_, b)| *b).collect(); - let (Some(origin), maxw, maxh) = ( - all.iter().copied().reduce(|a, b| a.union(b)), - all.iter().map(Rect::width).fold(0.0, f64::max), - all.iter().map(Rect::height).fold(0.0, f64::max), - ) else { - return ok(); - }; - let gap = num(p, "spacing").unwrap_or_else(|| { - // Keep the average existing horizontal gap (min 10). - 10f64.max( - rows.iter() - .filter(|r| r.len() > 1) - .map(|r| { - (r.iter().map(|(_, b)| b.x1).fold(f64::MIN, f64::max) - - r.iter().map(|(_, b)| b.x0).fold(f64::MAX, f64::min) - - r.iter().map(|(_, b)| b.width()).sum::()) - / (r.len() - 1) as f64 - }) - .fold(0.0, f64::max), - ) - }); - for (ri, row) in rows.iter_mut().enumerate() { - row.sort_by(|a, b| a.1.x0.total_cmp(&b.1.x0)); - for (ci, (id, b)) in row.iter().enumerate() { - let x = origin.x0 + ci as f64 * (maxw + gap); - let y = origin.y0 + ri as f64 * (maxh + gap); - move_world(doc, *id, x - b.x0, y - b.y0)?; - } + for (id, dx, dy) in moves { + move_world(doc, id, dx, dy)?; } ok() } diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index c03721af4..29b0f63a8 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -207,7 +207,7 @@ pub fn specs() -> Vec { spec!( "select.layersAt", "Layers at a point", - "{x, y (page coordinates)} → {layers: [{id, name, type, depth}]} (every layer under the point, front-most first; what the context menu's Select layer lists)", + "{x, y (page coordinates)} → {layers: [{id, name, type, depth, locked}]} (every layer under the point, locked ones too, front-most first; locked is true when the layer or an ancestor is locked; what the context menu's Select layer lists)", false, layers_at ), diff --git a/crates/engine/src/cmd/edit/select.rs b/crates/engine/src/cmd/edit/select.rs index 27eaf7d83..17f80af6b 100644 --- a/crates/engine/src/cmd/edit/select.rs +++ b/crates/engine/src/cmd/edit/select.rs @@ -8,9 +8,13 @@ pub(super) fn layers_at(s: &mut Session, p: &Value) -> Result { let zoom = s.ds()?.view.zoom.max(1e-6); let sel = s.selection(); let result = crate::booleans::result_outline(doc, &sel); - let layers: Vec = figcraft_doc::geometry::layers_at(doc, s.page()?, figcraft_geom::Point::new(x, y), 2.0 / zoom, Some(&result)) + let opts = figcraft_doc::geometry::HitOpts { locked: true }; + let layers: Vec = figcraft_doc::geometry::layers_at_opts(doc, s.page()?, figcraft_geom::Point::new(x, y), 2.0 / zoom, Some(&result), opts) .into_iter() - .filter_map(|(id, depth)| doc.node(id).map(|n| json!({"id": id, "name": n.name, "type": n.kind.type_name(), "depth": depth}))) + .filter_map(|(id, depth)| { + doc.node(id) + .map(|n| json!({"id": id, "name": n.name, "type": n.kind.type_name(), "depth": depth, "locked": crate::tools::locked_in(doc, id)})) + }) .collect(); Ok(json!({"layers": layers})) } diff --git a/crates/engine/src/cmd/view.rs b/crates/engine/src/cmd/view.rs index 3a8bc553b..56f4aff27 100644 --- a/crates/engine/src/cmd/view.rs +++ b/crates/engine/src/cmd/view.rs @@ -650,7 +650,7 @@ pub fn specs() -> Vec { spec!( "tool.scaleAnchor", "Scale anchor", - "{anchor?: tl|t|tr|l|c|r|bl|b|br} (the point of the selection that stays put when the Scale tool scales; omit to read it)", + "{anchor?: tl|t|tr|l|c|r|bl|b|br} (the origin of the Scale tool's factor field: the point of the selection that stays put; defaults to c, handle drags pivot on the opposite handle whatever it is; omit to read it)", false, |s, p| { if let Some(a) = string(p, "anchor") { diff --git a/crates/engine/src/dev/codegen.rs b/crates/engine/src/dev/codegen.rs index 428c3a711..28213e234 100644 --- a/crates/engine/src/dev/codegen.rs +++ b/crates/engine/src/dev/codegen.rs @@ -6,7 +6,7 @@ //! their iOS and Android code syntax in SwiftUI and Compose. The output is a starting point, not a //! pixel-exact translation. -use figcraft_color::{Color, PaintKind}; +use figcraft_color::{Color, Gradient, GradientKind, Paint, PaintKind}; use figcraft_doc::{ ContentAlign, CrossAlign, Document, EffectKind, LayoutMode, LetterSpacing, LineHeight, MainAlign, Node, NodeId, NodeKind, Shadow, Sizing, TextAlignH, TextCase, TextDecoration, Variable, @@ -345,6 +345,35 @@ fn first_fill(n: &Node) -> Option { }) } +/// A layer's visible fills with their place in the document. Document order is bottom first, as +/// the renderer paints them; the index tells a target which paint is the bottom one. +fn visible_fills(n: &Node) -> impl DoubleEndedIterator { + n.fills.iter().enumerate().filter(|(_, p)| p.visible) +} + +/// A gradient's sorted stops as (position, colour), the paint's opacity folded into each colour. +/// A lone stop is written twice (at 1 as well), since Android and Flutter need two colours. +fn gradient_stops(g: &Gradient, opacity: f32) -> Vec<(f64, Color)> { + let mut stops: Vec<(f64, Color)> = g.sorted_stops().iter().map(|s| (f64::from(s.position), s.color.with_alpha(s.color.a * opacity))).collect(); + if let [(_, only)] = stops[..] { + stops.push((1.0, only)); + } + stops +} + +/// A gradient's main axis in pixels on a `w` x `h` box. +fn gradient_axis(g: &Gradient, w: f64, h: f64) -> (f64, f64) { + ((g.to.0 - g.from.0) * w, (g.to.1 - g.from.1) * h) +} + +/// The kind a native target writes: a diamond reads as a radial gradient. +fn native_gradient_kind(g: &Gradient) -> GradientKind { + match g.kind { + GradientKind::Diamond => GradientKind::Radial, + k => k, + } +} + fn stroke_color(n: &Node) -> Option { if !n.has_visible_stroke() { return None; @@ -824,4 +853,188 @@ mod tests { } } } + + /// White, a 20% default linear gradient of black, then 50% black: bottom to top. + fn three_fills() -> Vec { + let mut gradient = figcraft_color::Paint::gradient(figcraft_color::Gradient::default_for(figcraft_color::GradientKind::Linear, Color::BLACK)); + gradient.opacity = 0.2; + let mut top = figcraft_color::Paint::solid(Color::BLACK); + top.opacity = 0.5; + vec![figcraft_color::Paint::solid(Color::WHITE), gradient, top] + } + + /// A 200 x `h` layer of `kind` (`frame`, `rectangle` or `ellipse`, a rectangle with corner + /// radius 8) with exactly `fills`. + fn fill_layer(s: &mut Session, kind: &str, h: f64, fills: Vec) -> NodeId { + let id = match kind { + "frame" => id_of(&s.execute("frame.create", &json!({"x": 0, "y": 0, "width": 200, "height": h})).unwrap()["id"]).unwrap(), + _ => id_of(&s.execute(&format!("shape.{kind}"), &json!({"x": 0, "y": 0, "width": 200, "height": h})).unwrap()["id"]).unwrap(), + }; + if kind == "rectangle" { + s.execute("node.set", &json!({"id": id, "props": {"cornerRadius": 8}})).unwrap(); + } + s.doc_mut().unwrap().get_mut(id).unwrap().fills = fills; + id + } + + fn one_gradient(s: &mut Session, g: figcraft_color::Gradient) -> NodeId { + fill_layer(s, "frame", 120.0, vec![figcraft_color::Paint::gradient(g)]) + } + + const SWIFT_WHITE: &str = "Color(red: 1, green: 1, blue: 1, opacity: 1)"; + const SWIFT_HALF: &str = "Color(red: 0, green: 0, blue: 0, opacity: 0.5)"; + const SWIFT_GRADIENT: &str = "LinearGradient(stops: [Gradient.Stop(color: Color(red: 0, green: 0, blue: 0, opacity: 0.2), location: 0), Gradient.Stop(color: Color(red: 0, green: 0, blue: 0, opacity: 0), location: 1)], startPoint: UnitPoint(x: 0.5, y: 0), endPoint: UnitPoint(x: 0.5, y: 1))"; + + #[test] + fn swiftui_writes_every_fill_top_first() { + let mut s = Session::new(); + let f = fill_layer(&mut s, "frame", 120.0, three_fills()); + let code = code_for(s.doc().unwrap(), f, CodeLang::SwiftUi); + let backgrounds: Vec<&str> = code.lines().map(str::trim).filter(|l| l.starts_with(".background(")).collect(); + let want = [format!(".background({SWIFT_HALF})"), format!(".background({SWIFT_GRADIENT})"), format!(".background({SWIFT_WHITE})")]; + assert_eq!(backgrounds, want.iter().map(String::as_str).collect::>(), "{code}"); + } + + #[test] + fn swiftui_shapes_fill_with_the_bottom_paint_and_overlay_the_rest() { + let mut s = Session::new(); + let r = fill_layer(&mut s, "rectangle", 120.0, three_fills()); + let code = code_for(s.doc().unwrap(), r, CodeLang::SwiftUi); + let mods: Vec<&str> = code.lines().map(str::trim).filter(|l| l.starts_with('.')).collect(); + let want = [ + format!(".fill({SWIFT_WHITE})"), + format!(".overlay(RoundedRectangle(cornerRadius: 8).fill({SWIFT_GRADIENT}))"), + format!(".overlay(RoundedRectangle(cornerRadius: 8).fill({SWIFT_HALF}))"), + ".frame(width: 200, height: 120)".to_string(), + ]; + assert_eq!(mods, want.iter().map(String::as_str).collect::>(), "{code}"); + assert!(!code.contains(".background("), "{code}"); + let mut half = figcraft_color::Paint::solid(Color::BLACK); + half.opacity = 0.5; + let e = fill_layer(&mut s, "ellipse", 120.0, vec![figcraft_color::Paint::solid(Color::WHITE), half]); + let code = code_for(s.doc().unwrap(), e, CodeLang::SwiftUi); + assert!(code.contains(&format!(".overlay(Ellipse().fill({SWIFT_HALF}))")), "{code}"); + } + + #[test] + fn compose_writes_every_fill_bottom_first() { + let mut s = Session::new(); + let f = fill_layer(&mut s, "frame", 120.0, three_fills()); + let code = code_for(s.doc().unwrap(), f, CodeLang::Compose); + let want = "Modifier.size(200.dp, 120.dp).background(Color(0xFFFFFFFF), RectangleShape).background(Brush.linearGradient(0f to Color(0x33000000), 1f to Color(0x00000000), start = Offset(0f, 0f), end = Offset(0f, Float.POSITIVE_INFINITY)), RectangleShape).background(Color(0x80000000), RectangleShape)"; + assert!(code.contains(want), "{code}"); + let r = fill_layer(&mut s, "rectangle", 120.0, three_fills()); + let code = code_for(s.doc().unwrap(), r, CodeLang::Compose); + assert_eq!(code.matches(".background(").count(), 3, "{code}"); + assert_eq!(code.matches(", RoundedCornerShape(8.dp))").count(), 3, "{code}"); + assert!(code.contains(".background(Color(0xFFFFFFFF), RoundedCornerShape(8.dp)).background(Brush."), "{code}"); + } + + #[test] + fn flutter_nests_a_box_per_fill_bottom_outermost() { + let mut s = Session::new(); + let f = fill_layer(&mut s, "frame", 120.0, three_fills()); + let code = code_for(s.doc().unwrap(), f, CodeLang::Flutter); + let want = "DecoratedBox( + decoration: BoxDecoration( + color: Color(0xFFFFFFFF), + ), + child: DecoratedBox( + decoration: BoxDecoration( + gradient: LinearGradient(begin: Alignment(0, -1), end: Alignment(0, 1), colors: [Color(0x33000000), Color(0x00000000)], stops: [0, 1]), + ), + child: Container( + width: 200, + height: 120, + decoration: BoxDecoration( + color: Color(0x80000000), + ), + ) + ) +)"; + assert_eq!(code, want); + } + + #[test] + fn flutter_keeps_the_shadow_under_every_fill() { + let mut s = Session::new(); + let f = fill_layer(&mut s, "frame", 120.0, three_fills()); + s.execute("effect.add", &json!({"ids": [f], "type": "dropShadow"})).unwrap(); + let code = code_for(s.doc().unwrap(), f, CodeLang::Flutter); + assert_eq!(code.matches("boxShadow:").count(), 1, "{code}"); + let (shadow, gradient) = (code.find("boxShadow:").unwrap(), code.find("gradient:").unwrap()); + assert!(shadow < gradient, "the shadow is on the outermost box: {code}"); + let r = fill_layer(&mut s, "rectangle", 120.0, three_fills()); + let code = code_for(s.doc().unwrap(), r, CodeLang::Flutter); + assert_eq!(code.matches("borderRadius: BorderRadius.circular(8)").count(), 3, "{code}"); + } + + #[test] + fn native_gradients_are_written_as_gradients() { + use figcraft_color::{Gradient, GradientKind}; + let mut s = Session::new(); + let radial = one_gradient(&mut s, Gradient::default_for(GradientKind::Radial, Color::BLACK)); + let doc = s.doc().unwrap(); + let sw = code_for(doc, radial, CodeLang::SwiftUi); + assert!(sw.contains("RadialGradient(stops: ["), "{sw}"); + assert!(sw.contains("center: UnitPoint(x: 0.5, y: 0.5), startRadius: 0, endRadius: 60)"), "{sw}"); + let kt = code_for(doc, radial, CodeLang::Compose); + assert!(kt.contains(".background(Brush.radialGradient(0f to Color(0xFF000000), 1f to Color(0x00000000)), RectangleShape)"), "{kt}"); + let dart = code_for(doc, radial, CodeLang::Flutter); + assert!( + dart.contains( + "gradient: RadialGradient(center: Alignment(0, 0), radius: 0.5, colors: [Color(0xFF000000), Color(0x00000000)], stops: [0, 1])" + ), + "{dart}" + ); + let angular = one_gradient(&mut s, Gradient::default_for(GradientKind::Angular, Color::BLACK)); + let doc = s.doc().unwrap(); + assert!(code_for(doc, angular, CodeLang::SwiftUi).contains("angle: .degrees(90))")); + assert!(code_for(doc, angular, CodeLang::Compose).contains("Brush.sweepGradient(")); + assert!(code_for(doc, angular, CodeLang::Flutter).contains("transform: GradientRotation(1.57))")); + // Compose snaps a linear gradient to one of eight directions. + let mut directed = |from: (f64, f64), to: (f64, f64)| { + let mut g = Gradient::default_for(GradientKind::Linear, Color::BLACK); + (g.from, g.to) = (from, to); + let id = one_gradient(&mut s, g); + code_for(s.doc().unwrap(), id, CodeLang::Compose) + }; + let up = directed((0.5, 1.0), (0.5, 0.0)); + assert!(up.contains("start = Offset(0f, Float.POSITIVE_INFINITY), end = Offset(0f, 0f)"), "{up}"); + let right = directed((0.0, 0.5), (1.0, 0.5)); + assert!(right.contains("end = Offset(Float.POSITIVE_INFINITY, 0f)"), "{right}"); + let corner = directed((0.0, 0.0), (1.0, 1.0)); + assert!(corner.contains("end = Offset(Float.POSITIVE_INFINITY, Float.POSITIVE_INFINITY)"), "{corner}"); + // A single stop is written twice, since a brush needs two colours. + let mut one = Gradient::default_for(GradientKind::Linear, Color::BLACK); + one.stops.truncate(1); + let id = one_gradient(&mut s, one); + let kt = code_for(s.doc().unwrap(), id, CodeLang::Compose); + assert_eq!(kt.matches(" to Color(").count(), 2, "{kt}"); + } + + #[test] + fn one_solid_fill_is_unchanged_in_native_code() { + let mut hidden = figcraft_color::Paint::solid(Color::BLACK); + hidden.visible = false; + let mut s = Session::new(); + for fills in [vec![figcraft_color::Paint::solid(Color::WHITE)], vec![figcraft_color::Paint::solid(Color::WHITE), hidden]] { + let f = fill_layer(&mut s, "frame", 100.0, fills); + let doc = s.doc().unwrap(); + let sw = code_for(doc, f, CodeLang::SwiftUi); + let backgrounds: Vec<&str> = sw.lines().map(str::trim).filter(|l| l.starts_with(".background(")).collect(); + assert_eq!(backgrounds, [format!(".background({SWIFT_WHITE})")], "{sw}"); + assert!(!sw.contains("Gradient"), "{sw}"); + let kt = code_for(doc, f, CodeLang::Compose); + assert!(kt.contains("Modifier.size(200.dp, 100.dp).background(Color(0xFFFFFFFF), RectangleShape))"), "{kt}"); + assert!(!kt.contains("Brush"), "{kt}"); + let dart = code_for(doc, f, CodeLang::Flutter); + assert!( + dart.starts_with("Container(\n width: 200,\n height: 100,\n decoration: BoxDecoration(\n color: Color(0xFFFFFFFF),\n ),\n)"), + "{dart}" + ); + assert!(!dart.contains("DecoratedBox"), "{dart}"); + assert!(code_for(doc, f, CodeLang::ArkUi).contains(".backgroundColor('#FFFFFF')")); + } + } } diff --git a/crates/engine/src/dev/codegen/compose.rs b/crates/engine/src/dev/codegen/compose.rs index c9cbf3ed1..799ba0882 100644 --- a/crates/engine/src/dev/codegen/compose.rs +++ b/crates/engine/src/dev/codegen/compose.rs @@ -1,6 +1,7 @@ use super::swift::one_line; use super::{ - CodeLang, Color, Ctx, LayoutMode, Node, NodeId, NodeKind, PADDING, drop_shadow, first_fill, indent, literal, named, num, radius, stroke_color, + CodeLang, Color, Ctx, GradientKind, LayoutMode, Node, NodeId, NodeKind, PADDING, Paint, PaintKind, drop_shadow, first_fill, gradient_axis, + gradient_stops, indent, literal, named, native_gradient_kind, num, radius, stroke_color, visible_fills, }; use figcraft_doc::Document; @@ -22,14 +23,66 @@ fn bound_dp(doc: &Document, n: &Node, fields: &[&str], value: f64) -> String { bound(doc, n, fields, format!("{}.dp", num(value))) } +/// One end of a linear brush's axis along one direction: `sign` is 0 for none, 1 for with the +/// axis and -1 against it. `Float.POSITIVE_INFINITY` stands for the far edge, which a modifier +/// can't know in pixels. +fn compose_edge(sign: i8) -> (&'static str, &'static str) { + match sign { + 0 => ("0f", "0f"), + s if s > 0 => ("0f", "Float.POSITIVE_INFINITY"), + _ => ("Float.POSITIVE_INFINITY", "0f"), + } +} + +/// A direction's sign: its component counts as none when it is at most tan 22.5 degrees of the other. +fn compose_sign(v: f64, other: f64) -> i8 { + if v.abs() <= 0.4142 * other.abs() { + 0 + } else if v > 0.0 { + 1 + } else { + -1 + } +} + +/// A gradient fill as a Compose `Brush` for a `w` x `h` layer. A linear gradient snaps to the +/// nearest of eight directions; radial and angular ones sit at the box's centre. +fn compose_gradient(g: &figcraft_color::Gradient, w: f64, h: f64, opacity: f32) -> String { + let stops = gradient_stops(g, opacity).into_iter().map(|(at, c)| format!("{}f to {}", num(at), kotlin_color(c))).collect::>().join(", "); + match native_gradient_kind(g) { + GradientKind::Linear => { + let (dx, dy) = gradient_axis(g, w, h); + let (sx, sy) = if dx == 0.0 && dy == 0.0 { (0, 1) } else { (compose_sign(dx, dy), compose_sign(dy, dx)) }; + let ((x0, x1), (y0, y1)) = (compose_edge(sx), compose_edge(sy)); + format!("Brush.linearGradient({stops}, start = Offset({x0}, {y0}), end = Offset({x1}, {y1}))") + } + GradientKind::Angular => format!("Brush.sweepGradient({stops})"), + _ => format!("Brush.radialGradient({stops})"), + } +} + +/// One paint (the one at document index `i`) as the first argument of `background`; `None` for an +/// image or pattern. Only a solid at index 0 takes the `fill` variable's name. +fn compose_paint(doc: &Document, n: &Node, i: usize, p: &Paint) -> Option { + match &p.kind { + PaintKind::Solid { .. } => { + let c = kotlin_color(p.solid_color()?); + Some(if i == 0 { bound(doc, n, &["fill"], c) } else { c }) + } + PaintKind::Gradient(g) => Some(compose_gradient(g, n.width, n.height, p.opacity)), + PaintKind::Image(_) | PaintKind::Pattern(_) => None, + } +} + /// The Modifier chain for a layer (size, shadow, background, border, alpha, padding). fn modifier(doc: &Document, n: &Node, shape: &str, padding: bool) -> String { let mut m = format!("Modifier.size({}, {})", bound_dp(doc, n, &["width"], n.width), bound_dp(doc, n, &["height"], n.height)); if let Some(s) = drop_shadow(n) { m.push_str(&format!(".shadow({}.dp, {shape})", num(s.radius / 2.0))); } - if let Some(c) = first_fill(n) { - m.push_str(&format!(".background({}, {shape})", bound(doc, n, &["fill"], kotlin_color(c)))); + // Each background draws and lets the rest of the chain draw over it: bottom fill first. + for b in visible_fills(n).filter_map(|(i, p)| compose_paint(doc, n, i, p)) { + m.push_str(&format!(".background({b}, {shape})")); } if let Some(c) = stroke_color(n) { m.push_str(&format!( diff --git a/crates/engine/src/dev/codegen/flutter.rs b/crates/engine/src/dev/codegen/flutter.rs index 7a144a147..4f2df194d 100644 --- a/crates/engine/src/dev/codegen/flutter.rs +++ b/crates/engine/src/dev/codegen/flutter.rs @@ -2,8 +2,9 @@ use figcraft_doc::AutoLayout; use super::swift::one_line; use super::{ - CodeLang, CrossAlign, Ctx, LayoutMode, LetterSpacing, LineHeight, MainAlign, Node, NodeId, NodeKind, Param, Sizing, TextAlignH, TextDecoration, - drop_shadow, first_fill, kotlin_color, literal, num, radius, stroke_color, + CodeLang, CrossAlign, Ctx, GradientKind, LayoutMode, LetterSpacing, LineHeight, MainAlign, Node, NodeId, NodeKind, Paint, PaintKind, Param, + Sizing, TextAlignH, TextDecoration, drop_shadow, first_fill, gradient_axis, gradient_stops, kotlin_color, literal, native_gradient_kind, num, + radius, stroke_color, visible_fills, }; // ------------------------------------------------------------------ Flutter (Dart) @@ -74,22 +75,72 @@ fn flutter_padding(n: &Node) -> Option { }) } +/// A gradient's colours and stops, the tail of every Flutter gradient constructor. +fn flutter_colors(g: &figcraft_color::Gradient, opacity: f32) -> String { + let stops = gradient_stops(g, opacity); + let colors = stops.iter().map(|(_, c)| kotlin_color(*c)).collect::>().join(", "); + let at = stops.iter().map(|(at, _)| num(*at)).collect::>().join(", "); + format!("colors: [{colors}], stops: [{at}]") +} + +/// A point of the unit box as Flutter's `Alignment`, which runs from -1 to 1. +fn flutter_alignment(p: (f64, f64)) -> String { + format!("Alignment({}, {})", num(2.0 * p.0 - 1.0), num(2.0 * p.1 - 1.0)) +} + +/// A gradient fill on a layer of `w` x `h` as a Flutter gradient. +fn flutter_gradient(g: &figcraft_color::Gradient, w: f64, h: f64, opacity: f32) -> String { + let (dx, dy) = gradient_axis(g, w, h); + let (tail, from) = (flutter_colors(g, opacity), flutter_alignment(g.from)); + match native_gradient_kind(g) { + GradientKind::Linear => format!("LinearGradient(begin: {from}, end: {}, {tail})", flutter_alignment(g.to)), + GradientKind::Angular => format!("SweepGradient(center: {from}, {tail}, transform: GradientRotation({}))", num(dy.atan2(dx))), + _ => { + // Flutter's radius is a fraction of the box's shorter side. + let (reach, side) = (dx.hypot(dy), w.min(h)); + let radius = if reach > 0.0 && side > 0.0 { reach / side } else { 0.5 }; + format!("RadialGradient(center: {from}, radius: {}, {tail})", num(radius)) + } + } +} + +/// One paint as a `BoxDecoration` part (`color: ...` or `gradient: ...`); `None` for an image or +/// pattern, which no native target writes yet. +fn flutter_paint(n: &Node, p: &Paint) -> Option { + match &p.kind { + PaintKind::Solid { .. } => Some(format!("color: {}", kotlin_color(p.solid_color()?))), + PaintKind::Gradient(g) => Some(format!("gradient: {}", flutter_gradient(g, n.width, n.height, p.opacity))), + PaintKind::Image(_) | PaintKind::Pattern(_) => None, + } +} + +/// Whether a layer is written as a `Container`: the layers with a box to paint. +fn paints_a_box(n: &Node) -> bool { + matches!(n.kind, NodeKind::Ellipse { .. } | NodeKind::Rectangle | NodeKind::Group) || n.kind.is_frame_like() +} + +/// A layer's fills as `BoxDecoration` parts, bottom first. +fn flutter_fill_parts(n: &Node) -> Vec { + visible_fills(n).filter_map(|(_, p)| flutter_paint(n, p)).collect() +} + /// A layer's fill, shape, corner radius, stroke and shadow as a `BoxDecoration`; `None` when it has -/// none of them. `pad` is the indentation of the constructor itself. -fn box_decoration(n: &Node, pad: &str) -> Option { +/// none of them. `pad` is the indentation of the constructor itself; `fill` is the one fill part +/// this decoration paints, and `stroke` and `shadow` say whether it carries those. +fn box_decoration(n: &Node, pad: &str, fill: Option<&str>, stroke: bool, shadow: bool) -> Option { let mut parts: Vec = Vec::new(); - if let Some(c) = first_fill(n) { - parts.push(format!("color: {}", kotlin_color(c))); + if let Some(f) = fill { + parts.push(f.to_string()); } if matches!(n.kind, NodeKind::Ellipse { .. }) { parts.push("shape: BoxShape.circle".into()); } else if radius(n) > 0.0 { parts.push(format!("borderRadius: BorderRadius.circular({})", num(radius(n)))); } - if let Some(c) = stroke_color(n) { + if let Some(c) = stroke_color(n).filter(|_| stroke) { parts.push(format!("border: Border.all(color: {}, width: {})", kotlin_color(c), num(n.stroke.weight))); } - if let Some(s) = drop_shadow(n) { + if let Some(s) = drop_shadow(n).filter(|_| shadow) { parts.push(format!( "boxShadow: [BoxShadow(color: {}, blurRadius: {}, offset: Offset({}, {}))]", kotlin_color(s.color), @@ -105,6 +156,42 @@ fn box_decoration(n: &Node, pad: &str) -> Option { Some(format!("BoxDecoration(\n{}{pad})", parts.iter().map(|p| format!("{inner}{p},\n")).collect::())) } +/// What a `Container` paints itself: its own fill (the top one), and whether it carries the shadow +/// (only when no `DecoratedBox` does). +struct Painted { + fill: Option, + shadow: bool, +} + +/// Opens a `DecoratedBox` for each fill under the top one, the bottom fill outermost, and returns +/// what is left for the `Container`. The outermost box carries the drop shadow: a decoration paints +/// its shadow first, so on the `Container` it would lie over the lower fills. +fn flutter_fill_boxes(n: &Node, depth: &mut usize, close: &mut Vec, out: &mut String) -> Painted { + let mut parts = flutter_fill_parts(n); + let top = parts.pop(); + let shadow = parts.is_empty(); + for (at, part) in parts.iter().enumerate() { + let (pad, inner) = (flutter_indent(*depth), flutter_indent(*depth + 1)); + if close.is_empty() { + out.push_str(&pad); + } + let deco = box_decoration(n, &inner, Some(part), false, at == 0).unwrap_or_default(); + out.push_str(&format!("DecoratedBox(\n{inner}decoration: {deco},\n{inner}child: ")); + close.push(format!("\n{pad})")); + *depth += 1; + } + Painted { fill: top, shadow } +} + +/// The call an instance below the root is (an instance swap parameter is a widget); `None` for +/// every other layer. +fn flutter_call(ctx: &Ctx, n: &Node, depth: usize) -> Option { + match ctx.param(n, "mainComponent").filter(|_| n.id != ctx.root) { + Some(p) => Some(p.ident.clone()), + None => ctx.call(n, CodeLang::Flutter, depth).map(|(code, _)| code), + } +} + /// Flutter for a layer and its subtree at `depth`. A layer a boolean parameter shows sits behind an /// `if (…)`: Dart's lists take conditions, so the element itself carries it. pub(crate) fn flutter(ctx: &Ctx, id: NodeId, depth: usize, out: &mut String, place: Place) { @@ -150,9 +237,13 @@ fn flutter_placed(ctx: &Ctx, n: &Node, depth: usize, out: &mut String, place: Pl close.push(format!("\n{pad})")); depth += 1; } + // An instance is a call, made once: it gets no fill boxes, so this is its final depth. + let call = flutter_call(ctx, n, depth); + let painted = + if call.is_none() && paints_a_box(n) { flutter_fill_boxes(n, &mut depth, &mut close, out) } else { Painted { fill: None, shadow: true } }; // A wrapper leaves its line open ("child: "), so the widget carries no indentation of its own. let mut body = String::new(); - flutter_widget(ctx, n, depth, &mut body); + flutter_widget(ctx, n, depth, call, &painted, &mut body); out.push_str(if close.is_empty() { body.as_str() } else { body.trim_start() }); for c in close.iter().rev() { out.push_str(c); @@ -161,13 +252,8 @@ fn flutter_placed(ctx: &Ctx, n: &Node, depth: usize, out: &mut String, place: Pl /// A layer's own look and its subtree as a Flutter widget at `depth`: a complete expression whose /// closing parenthesis sits at `depth`. -fn flutter_widget(ctx: &Ctx, n: &Node, depth: usize, out: &mut String) { +fn flutter_widget(ctx: &Ctx, n: &Node, depth: usize, call: Option, painted: &Painted, out: &mut String) { let (pad, inner) = (flutter_indent(depth), flutter_indent(depth + 1)); - // Nested instances are calls; an instance swap parameter is a widget. - let call = match ctx.param(n, "mainComponent").filter(|_| n.id != ctx.root) { - Some(p) => Some(p.ident.clone()), - None => ctx.call(n, CodeLang::Flutter, depth).map(|(code, _)| code), - }; if let Some(call) = call { out.push_str(call.trim_end_matches('\n')); return; @@ -216,7 +302,7 @@ fn flutter_widget(ctx: &Ctx, n: &Node, depth: usize, out: &mut String) { } NodeKind::Ellipse { .. } | NodeKind::Rectangle => { out.push_str(&format!("{pad}Container(\n{inner}width: {},\n{inner}height: {},\n", num(n.width), num(n.height))); - if let Some(d) = box_decoration(n, &inner) { + if let Some(d) = box_decoration(n, &inner, painted.fill.as_deref(), true, painted.shadow) { out.push_str(&format!("{inner}decoration: {d},\n")); } out.push_str(&format!("{pad})")); @@ -232,7 +318,7 @@ fn flutter_widget(ctx: &Ctx, n: &Node, depth: usize, out: &mut String) { if !padded_inside && let Some(p) = flutter_padding(n) { out.push_str(&format!("{inner}padding: {p},\n")); } - if let Some(d) = box_decoration(n, &inner) { + if let Some(d) = box_decoration(n, &inner, painted.fill.as_deref(), true, painted.shadow) { out.push_str(&format!("{inner}decoration: {d},\n")); } if children.is_empty() && slot.is_none() { diff --git a/crates/engine/src/dev/codegen/swift.rs b/crates/engine/src/dev/codegen/swift.rs index 99c065a0a..553f4f296 100644 --- a/crates/engine/src/dev/codegen/swift.rs +++ b/crates/engine/src/dev/codegen/swift.rs @@ -1,5 +1,6 @@ use super::{ - CodeLang, Color, Ctx, LayoutMode, Node, NodeId, NodeKind, PADDING, drop_shadow, first_fill, indent, literal, named, num, radius, stroke_color, + CodeLang, Color, Ctx, Document, GradientKind, LayoutMode, Node, NodeId, NodeKind, PADDING, Paint, PaintKind, drop_shadow, first_fill, + gradient_axis, gradient_stops, indent, literal, named, native_gradient_kind, num, radius, stroke_color, visible_fills, }; // ------------------------------------------------------------------ SwiftUI @@ -8,6 +9,47 @@ fn swift_color(c: Color) -> String { format!("Color(red: {}, green: {}, blue: {}, opacity: {})", num(f64::from(c.r)), num(f64::from(c.g)), num(f64::from(c.b)), num(f64::from(c.a))) } +fn swift_point(p: (f64, f64)) -> String { + format!("UnitPoint(x: {}, y: {})", num(p.0), num(p.1)) +} + +/// A gradient fill on a layer of `w` x `h` as a SwiftUI gradient. +fn swift_gradient(g: &figcraft_color::Gradient, w: f64, h: f64, opacity: f32) -> String { + let stops = gradient_stops(g, opacity) + .into_iter() + .map(|(at, c)| format!("Gradient.Stop(color: {}, location: {})", swift_color(c), num(at))) + .collect::>() + .join(", "); + let (dx, dy) = gradient_axis(g, w, h); + match native_gradient_kind(g) { + GradientKind::Linear => format!("LinearGradient(stops: [{stops}], startPoint: {}, endPoint: {})", swift_point(g.from), swift_point(g.to)), + GradientKind::Angular => { + format!("AngularGradient(stops: [{stops}], center: {}, angle: .degrees({}))", swift_point(g.from), num(dy.atan2(dx).to_degrees())) + } + _ => format!("RadialGradient(stops: [{stops}], center: {}, startRadius: 0, endRadius: {})", swift_point(g.from), num(dx.hypot(dy))), + } +} + +/// One paint (the one at document index `i`) as SwiftUI; `None` for an image or pattern, which no +/// native target writes yet. Only a solid at index 0 takes the `fill` variable's name. +fn swift_paint(doc: &Document, n: &Node, i: usize, p: &Paint) -> Option { + match &p.kind { + PaintKind::Solid { .. } => { + let c = swift_color(p.solid_color()?); + Some(if i == 0 { named(doc, n, "iOS", &["fill"], c) } else { c }) + } + PaintKind::Gradient(g) => Some(swift_gradient(g, n.width, n.height, p.opacity)), + PaintKind::Image(_) | PaintKind::Pattern(_) => None, + } +} + +/// The modifiers filling a rectangle or ellipse: the bottom paint fills the `shape`, and each paint +/// above it is a copy of the shape laid over it. +fn swift_shape_fills(doc: &Document, n: &Node, shape: &str) -> Vec { + let paints = visible_fills(n).filter_map(|(i, p)| swift_paint(doc, n, i, p)); + paints.enumerate().map(|(at, c)| if at == 0 { format!(".fill({c})") } else { format!(".overlay({shape}.fill({c}))") }).collect() +} + fn swift_weight(w: u16) -> &'static str { match w { 0..=150 => ".thin", @@ -84,16 +126,12 @@ fn swift_layer(ctx: &Ctx, n: &Node, depth: usize, out: &mut String, extra: &[Str } NodeKind::Ellipse { .. } => { out.push_str(&format!("{pad}Ellipse()\n")); - if let Some(c) = &fill { - mods.push(format!(".fill({c})")); - } + mods.extend(swift_shape_fills(doc, n, "Ellipse()")); mods.push(format!(".frame(width: {w}, height: {h})")); } NodeKind::Rectangle => { out.push_str(&format!("{pad}RoundedRectangle(cornerRadius: {corner})\n")); - if let Some(c) = &fill { - mods.push(format!(".fill({c})")); - } + mods.extend(swift_shape_fills(doc, n, &format!("RoundedRectangle(cornerRadius: {corner})"))); mods.push(format!(".frame(width: {w}, height: {h})")); } k if k.is_frame_like() || matches!(k, NodeKind::Group) => { @@ -142,9 +180,8 @@ fn swift_layer(ctx: &Ctx, n: &Node, depth: usize, out: &mut String, extra: &[Str } } mods.push(format!(".frame(width: {w}, height: {h}, alignment: .topLeading)")); - if let Some(c) = &fill { - mods.push(format!(".background({c})")); - } + // Each background goes behind the ones before it, so the top fill is written first. + mods.extend(visible_fills(n).rev().filter_map(|(i, p)| swift_paint(doc, n, i, p)).map(|c| format!(".background({c})"))); if radius(n) > 0.0 { mods.push(format!(".clipShape(RoundedRectangle(cornerRadius: {corner}))")); } diff --git a/crates/engine/src/error.rs b/crates/engine/src/error.rs index 7f26258f1..e3f4e79e9 100644 --- a/crates/engine/src/error.rs +++ b/crates/engine/src/error.rs @@ -14,6 +14,10 @@ pub enum EngineError { NoNode(NodeId), #[error("{0}")] Other(String), + /// A preview was asked for with no gesture open (something committed it under a held button). + /// Not for the user: the canvas drops it, as the drag it belonged to is over. + #[error("no gesture in progress")] + NoGesture, /// A command run in the background sent a request to a server and runs again with the answer /// ([`background`]); never returned to other callers. #[error("waiting for the server")] diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 39ead2e82..fc8ab8c4d 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -77,6 +77,7 @@ pub use selection::rename; pub use selection::selection_colors; pub use selection::selection_reorder; pub use selection::selection_spacing; +pub use selection::tidy; pub use sharing::agent; pub use sharing::background; pub use sharing::branches; @@ -609,6 +610,8 @@ mod textfit_tests; #[cfg(test)] mod theme_pages_tests; #[cfg(test)] +mod tidy_tests; +#[cfg(test)] mod tiff_tests; #[cfg(test)] mod transform_behaviour_tests; diff --git a/crates/engine/src/scale_tool_tests.rs b/crates/engine/src/scale_tool_tests.rs index f61eba934..eab7b7313 100644 --- a/crates/engine/src/scale_tool_tests.rs +++ b/crates/engine/src/scale_tool_tests.rs @@ -57,29 +57,54 @@ fn anchors_round_trip() { } #[test] -fn the_pivot_is_the_anchor_unless_it_is_on_the_dragged_side() { +fn the_pivot_is_the_opposite_handle_or_the_centre_with_alt() { let (w, h) = (100.0, 50.0); - let tl = (0, 0); - // Bottom-right corner from the top-left anchor: classic, by the axis that moved the most. - assert_eq!(scale_factor(Handle::Corner(2), Point::new(200.0, 60.0), w, h, tl, false), Some((2.0, Point::new(0.0, 0.0)))); - // Top-right corner: the anchor is on its top side, so the opposite corner stays put. - assert_eq!(scale_factor(Handle::Corner(1), Point::new(150.0, -25.0), w, h, tl, false), Some((1.5, Point::new(0.0, 50.0)))); - // Right edge: from the anchor; left edge: the anchor is on it, so from the right edge. - assert_eq!(scale_factor(Handle::Edge(1), Point::new(50.0, 999.0), w, h, tl, false), Some((0.5, Point::new(0.0, 0.0)))); - assert_eq!(scale_factor(Handle::Edge(3), Point::new(-100.0, 0.0), w, h, tl, false), Some((2.0, Point::new(100.0, 25.0)))); - // A centre anchor, or Alt, scales about the centre. - assert_eq!(scale_factor(Handle::Corner(2), Point::new(150.0, 75.0), w, h, (1, 1), false), Some((2.0, Point::new(50.0, 25.0)))); - assert_eq!(scale_factor(Handle::Edge(2), Point::new(0.0, 75.0), w, h, tl, true), Some((2.0, Point::new(50.0, 25.0)))); + // Bottom-right corner: the top-left corner stays put, by the axis that moved the most. + assert_eq!(scale_factor(Handle::Corner(2), Point::new(200.0, 60.0), w, h, false), Some((2.0, Point::new(0.0, 0.0)))); + // Top-right corner: the bottom-left corner stays put. + assert_eq!(scale_factor(Handle::Corner(1), Point::new(150.0, -25.0), w, h, false), Some((1.5, Point::new(0.0, 50.0)))); + // Right edge: the left edge's middle; left edge: the right edge's middle. + assert_eq!(scale_factor(Handle::Edge(1), Point::new(50.0, 999.0), w, h, false), Some((0.5, Point::new(0.0, 25.0)))); + assert_eq!(scale_factor(Handle::Edge(3), Point::new(-100.0, 0.0), w, h, false), Some((2.0, Point::new(100.0, 25.0)))); + // Alt scales about the centre. + assert_eq!(scale_factor(Handle::Edge(2), Point::new(0.0, 75.0), w, h, true), Some((2.0, Point::new(50.0, 25.0)))); // Past the pivot flips; it never collapses to nothing. - assert_eq!(scale_factor(Handle::Corner(2), Point::new(-100.0, -50.0), w, h, tl, false).map(|k| k.0), Some(-1.0)); - assert_eq!(scale_factor(Handle::Corner(2), Point::new(0.0, 0.0), w, h, tl, false).map(|k| k.0), Some(0.01)); + assert_eq!(scale_factor(Handle::Corner(2), Point::new(-100.0, -50.0), w, h, false).map(|k| k.0), Some(-1.0)); + assert_eq!(scale_factor(Handle::Corner(2), Point::new(0.0, 0.0), w, h, false).map(|k| k.0), Some(0.01)); // Lines (no height) scale along their length. - assert_eq!(scale_factor(Handle::Corner(1), Point::new(300.0, 7.0), 100.0, 0.0, tl, false).map(|k| k.0), Some(3.0)); + assert_eq!(scale_factor(Handle::Corner(1), Point::new(300.0, 7.0), 100.0, 0.0, false).map(|k| k.0), Some(3.0)); for bad in [f64::NAN, f64::INFINITY] { - assert_eq!(scale_factor(Handle::Corner(2), Point::new(bad, 0.0), w, h, tl, false), None); + assert_eq!(scale_factor(Handle::Corner(2), Point::new(bad, 0.0), w, h, false), None); } - assert_eq!(scale_factor(Handle::Rotate(0), Point::new(1.0, 1.0), w, h, tl, false), None); - assert_eq!(scale_factor(Handle::Corner(2), Point::new(5.0, 5.0), 0.0, 0.0, tl, false), None); + assert_eq!(scale_factor(Handle::Rotate(0), Point::new(1.0, 1.0), w, h, false), None); + assert_eq!(scale_factor(Handle::Corner(2), Point::new(5.0, 5.0), 0.0, 0.0, false), None); +} + +/// Measured in Figma's web app, 2026-11-09: a drag ignores the origin grid and pivots on the +/// opposite handle (a 100 x 100 layer at 9000, 5000: the bottom-right corner keeps the top left; +/// the right edge keeps the left edge's middle and scales both ways). +#[test] +fn a_scale_handle_drag_pivots_on_the_opposite_handle_whatever_the_origin() { + for origin in ["c", "tl"] { + let mut s = Session::new(); + let r = rect(&mut s, 9000.0, 5000.0, 100.0, 100.0); + ex(&mut s, "select.set", json!({"ids": [r]})); + ex(&mut s, "tool.scale", json!({})); + ex(&mut s, "tool.scaleAnchor", json!({"anchor": origin})); + drag(&mut s, (9100.0, 5100.0), (9144.0, 5144.0), false); + assert_rect(bounds(&s, r), [9000.0, 5000.0, 9144.0, 5144.0]); + s.undo().unwrap(); + // The right edge's middle: the left edge's middle stays, the layer scales evenly. + drag(&mut s, (9100.0, 5050.0), (9150.0, 5050.0), false); + assert_rect(bounds(&s, r), [9000.0, 4975.0, 9150.0, 5125.0]); + } +} + +#[test] +fn the_scale_origin_starts_at_the_centre() { + let mut s = Session::new(); + assert_eq!(ex(&mut s, "tool.scaleAnchor", json!({}))["anchor"], json!("c")); + assert_eq!(s.tool.scale_anchor, (1, 1)); } #[test] @@ -118,7 +143,7 @@ fn the_live_readout_shows_the_factor_and_pivot() { } #[test] -fn the_anchor_and_alt_choose_what_stays_put() { +fn the_anchor_is_read_back_and_alt_scales_from_the_centre() { let mut s = Session::new(); let r = rect(&mut s, 0.0, 0.0, 100.0, 50.0); ex(&mut s, "select.set", json!({"ids": [r]})); @@ -126,12 +151,13 @@ fn the_anchor_and_alt_choose_what_stays_put() { assert_eq!(ex(&mut s, "tool.scaleAnchor", json!({"anchor": "c"}))["anchor"], json!("c")); assert_eq!(ex(&mut s, "tool.scaleAnchor", json!({}))["anchor"], json!("c"), "reads it back"); assert!(s.execute("tool.scaleAnchor", &json!({"anchor": "nowhere"})).is_err()); + // A drag pivots on the opposite corner whatever the anchor. drag(&mut s, (100.0, 50.0), (150.0, 75.0), false); - assert_rect(bounds(&s, r), [-50.0, -25.0, 150.0, 75.0]); + assert_rect(bounds(&s, r), [0.0, 0.0, 150.0, 75.0]); // Alt scales from the centre whatever the anchor. ex(&mut s, "tool.scaleAnchor", json!({"anchor": "tl"})); drag(&mut s, (150.0, 75.0), (125.0, 62.5), true); - assert_rect(bounds(&s, r), [-25.0, -12.5, 125.0, 62.5]); + assert_rect(bounds(&s, r), [25.0, 12.5, 125.0, 62.5]); } #[test] diff --git a/crates/engine/src/selection.rs b/crates/engine/src/selection.rs index 08ab6456f..fa901b563 100644 --- a/crates/engine/src/selection.rs +++ b/crates/engine/src/selection.rs @@ -2,3 +2,4 @@ pub mod rename; pub mod selection_colors; pub mod selection_reorder; pub mod selection_spacing; +pub mod tidy; diff --git a/crates/engine/src/selection/tidy.rs b/crates/engine/src/selection/tidy.rs new file mode 100644 index 000000000..4a940e940 --- /dev/null +++ b/crates/engine/src/selection/tidy.rs @@ -0,0 +1,271 @@ +//! Tidy up: the moves that even a selection's gaps the way Figma's web app does. +//! +//! Measured in Figma's web app on 2026-11-12 (top-level rectangles): a row, a column, a 2 x 3 grid +//! and its transpose, and many runs on the gap. Figma keeps the order and the sizes of every layer +//! and keeps the first layer where it is. Rows are the groups of layers whose Y ranges overlap +//! (transitively), columns the groups whose X ranges overlap. A row is one row group of layers +//! side by side: its horizontal gaps are evened and every Y kept; a column is the mirror image. +//! Layers of a row may overlap along X, also in a chain: a negative gap counts in the mean. The one gap is the most +//! common existing gap (the smaller of two equally common ones), else the mean rounded to a whole +//! number, half up. A grid (two or more rows and two or more columns, one layer in every cell) is +//! packed along the axis that has more groups: for 2 rows by 3 columns each column is as wide as +//! its widest layer, centred where its layers were, the columns are evened, every layer is +//! centred in its column and every column is stacked from the selection's top; 3 rows by 2 +//! columns is the mirror image. Tidy up is unavailable for fewer than three layers, for layers all +//! in one row and one column (overlapping each other), for a diagonal and for an irregular layout. +//! +//! Not measured, FigCraft's choices: a 2 x 2 grid packed as columns; layers in an auto layout flow +//! making it unavailable (the frame places them, and the measurement could not tell this from an +//! irregular layout); the 2,000 layer cap; rotated layers counting by their box; gaps a pixel +//! apart being different gaps; an explicit `spacing` taking two layers; no rounding in a grid with +//! Snap to pixel grid off. + +use std::collections::BTreeSet; + +use figcraft_doc::{Document, NodeId}; +use figcraft_geom::Rect; + +use crate::cmd::edit::roots; + +const EPS: f64 = 0.01; +const MAX_LAYERS: usize = 2000; + +type Item = (NodeId, Rect); +type Move = (NodeId, f64, f64); + +/// What a selection is: a row or a column (`vertical`), or a grid packed in units along an axis +/// (`vertical`: the units are rows). +#[derive(Clone, Copy)] +enum Shape { + Line { vertical: bool }, + Grid { vertical: bool }, +} + +/// Whether Tidy up is offered for `ids`: three to 2,000 layers with boxes, none in an auto layout +/// flow, forming a row, a column or a grid. +pub fn can_tidy(doc: &Document, ids: &[NodeId]) -> bool { + available(doc, ids, 3).is_some() +} + +/// The page-space moves that tidy `ids` (empty when unavailable or when nothing would move). +/// `spacing` sets the gap and lets two layers through; `snap` rounds a grid's positions across its +/// packing axis to whole pixels. +pub(crate) fn tidy_moves(doc: &Document, ids: &[NodeId], spacing: Option, snap: bool) -> Vec { + let min = if spacing.is_some() { 2 } else { 3 }; + let Some((items, shape)) = available(doc, ids, min) else { return Vec::new() }; + let moves = match shape { + Shape::Line { vertical } => line_moves(&items, vertical, spacing), + Shape::Grid { vertical } => grid_moves(&groups(&items, vertical), vertical, spacing, snap), + }; + moves.into_iter().filter(|(_, dx, dy)| !(dx.is_finite() && dy.is_finite()) || dx.abs() > 1e-9 || dy.abs() > 1e-9).collect() +} + +fn available(doc: &Document, ids: &[NodeId], min: usize) -> Option<(Vec, Shape)> { + let mut seen = BTreeSet::new(); + let ids: Vec = roots(doc, ids).into_iter().filter(|i| seen.insert(*i)).collect(); + if ids.len() < min || ids.len() > MAX_LAYERS { + return None; + } + let mut items = Vec::with_capacity(ids.len()); + for id in ids { + let n = doc.node(id)?; + if n.parent.and_then(|p| doc.node(p)).is_some_and(|p| p.layout.is_some() && !n.child_layout.absolute) { + return None; + } + let b = doc.world_bounds(id)?; + if ![b.x0, b.y0, b.x1, b.y1].into_iter().all(f64::is_finite) { + return None; + } + items.push((id, b)); + } + let shape = classify(&items)?; + Some((items, shape)) +} + +/// A row: one row group over two or more column groups (layers sharing a column group overlap). +/// A column: the mirror image. A grid: two or +/// more of each, one layer in every cell, packed along the axis with more groups (columns on a tie). +fn classify(items: &[Item]) -> Option { + let cols = groups(items, false); + let rows = groups(items, true); + match (cols.len(), rows.len()) { + (c, 1) if c >= 2 && cols.iter().all(|g| overlapping(g, false)) => Some(Shape::Line { vertical: false }), + (1, r) if r >= 2 && rows.iter().all(|g| overlapping(g, true)) => Some(Shape::Line { vertical: true }), + (c, r) if c >= 2 && r >= 2 && one_per_cell(&cols, &rows) => Some(Shape::Grid { vertical: r > c }), + _ => None, + } +} + +/// Layers that share a group along a row's (`vertical` false) or column's own axis must overlap +/// each other pairwise on the OTHER axis, not merely sit in the same band: a header above two +/// layers side by side is irregular (a row's column group of the header and one of the pair has Y +/// ranges that don't overlap for the pair). The own axis is already covered by `groups`, which +/// chains transitively, so 50 px squares at X 0, 40, 80, 150 are a row although the first and +/// third don't touch. +fn overlapping(group: &[Item], vertical: bool) -> bool { + let across = |a: Rect, b: Rect| { + let (a, b) = (span(a, !vertical), span(b, !vertical)); + a.1.min(b.1) - a.0.max(b.0) > EPS + }; + group.iter().enumerate().all(|(i, a)| group.iter().skip(i + 1).all(|b| across(a.1, b.1))) +} + +fn span(b: Rect, vertical: bool) -> (f64, f64) { + if vertical { (b.y0, b.y1) } else { (b.x0, b.x1) } +} + +/// Columns (`vertical` false) or rows: the layers whose ranges on the axis overlap, transitively, +/// in order along the axis. +fn groups(items: &[Item], vertical: bool) -> Vec> { + let mut sorted = items.to_vec(); + sorted.sort_by(|a, b| span(a.1, vertical).0.total_cmp(&span(b.1, vertical).0)); + let mut out: Vec> = Vec::new(); + let mut end = f64::MIN; + for it in sorted { + let (lo, hi) = span(it.1, vertical); + match out.last_mut() { + Some(group) if lo < end - EPS => { + group.push(it); + end = end.max(hi); + } + _ => { + out.push(vec![it]); + end = hi; + } + } + } + out +} + +/// Every (column, row) cell holds exactly one layer. +fn one_per_cell(cols: &[Vec], rows: &[Vec]) -> bool { + cols.iter().all(|c| rows.iter().all(|r| c.iter().filter(|a| r.iter().any(|b| b.0 == a.0)).count() == 1)) +} + +/// The one gap an axis is evened to: `spacing`, a single gap, the most common gap (the smaller of +/// two equally common ones), else the mean rounded to a whole number, half up. +fn even_gap(gaps: &[f64], spacing: Option) -> f64 { + if let Some(s) = spacing { + return s; + } + if let [only] = gaps { + return *only; + } + let count = |g: f64| gaps.iter().filter(|o| (**o - g).abs() <= EPS).count(); + let best = gaps.iter().copied().map(|g| (count(g), g)).reduce(|a, b| if b.0 > a.0 || (b.0 == a.0 && b.1 < a.1) { b } else { a }); + match best { + Some((n, g)) if n >= 2 => g, + _ if gaps.is_empty() => 0.0, + _ => (gaps.iter().sum::() / gaps.len() as f64 + 0.5 + 1e-9).floor(), + } +} + +/// The even gap of a line of three or more layers, from its derived gap `gap`: raised so that +/// every layer starts strictly after the end of the layer two places before it. With one gap `g`, +/// layer `i + 2` starts at `end(i) + w(i + 1) + 2g`, so `g > -w(i + 1) / 2` for every interior +/// layer, in whole pixels `floor(-w_min / 2) + 1` for the narrowest interior size `w_min`. Measured +/// in Figma's web app on 2026-11-13: interior widths of 10, 20 and 30 among 100s gave -4, -9 and +/// -14, and widths of 100 left the most common gap, -40, alone. Only those three widths were +/// measured; other widths follow the same formula. +/// +/// The first layer has no layer two places before it, but the second must still start after it: +/// `g > -w(0)`, in whole pixels `floor(-w(0)) + 1`. Figma kept the order in every run; a narrow +/// first layer was not measured, so this bound keeps that order rather than following a reading. +fn raise_negative_gap(gap: f64, widths: &[f64]) -> f64 { + let interior = widths.get(1..widths.len().saturating_sub(1)).unwrap_or(&[]); + let w_min = interior.iter().copied().fold(f64::INFINITY, f64::min); + let Some(first) = widths.first().copied() else { return gap }; + if widths.len() < 3 || !w_min.is_finite() || !first.is_finite() { + return gap; + } + gap.max((-w_min / 2.0).floor() + 1.0).max((-first).floor() + 1.0) +} + +/// A row (`vertical` false) or a column: the first layer stays, each next one follows the last at +/// the even gap, the other axis is untouched. +fn line_moves(items: &[Item], vertical: bool, spacing: Option) -> Vec { + let mut line = items.to_vec(); + line.sort_by(|a, b| span(a.1, vertical).0.total_cmp(&span(b.1, vertical).0)); + let gaps: Vec = line + .windows(2) + .filter_map(|w| match w { + [a, b] => Some(span(b.1, vertical).0 - span(a.1, vertical).1), + _ => None, + }) + .collect(); + let widths: Vec = line.iter().map(|i| span(i.1, vertical).1 - span(i.1, vertical).0).collect(); + let gap = match spacing { + Some(s) => s, + None => raise_negative_gap(even_gap(&gaps, None), &widths), + }; + let mut pos = line.first().map_or(0.0, |i| span(i.1, vertical).0); + let mut out = Vec::with_capacity(line.len()); + for (id, b) in line { + let (lo, hi) = span(b, vertical); + let d = pos - lo; + pos += (hi - lo) + gap; + out.push(if vertical { (id, 0.0, d) } else { (id, d, 0.0) }); + } + out +} + +fn snap_to(v: f64, snap: bool) -> f64 { + if snap { (v + 0.5).floor() } else { v } +} + +/// A unit's box on the packing axis: where it starts and how wide it is (its widest layer, around +/// the middle of the unit's range). +fn unit_box(unit: &[Item], vertical: bool) -> (f64, f64) { + let lo = unit.iter().map(|i| span(i.1, vertical).0).fold(f64::MAX, f64::min); + let hi = unit.iter().map(|i| span(i.1, vertical).1).fold(f64::MIN, f64::max); + let w = unit.iter().map(|i| span(i.1, vertical).1 - span(i.1, vertical).0).fold(0.0, f64::max); + ((lo + hi) / 2.0 - w / 2.0, w) +} + +/// The gaps inside every unit along the other axis, pooled. +fn unit_gaps(units: &[Vec], vertical: bool) -> Vec { + let mut out = Vec::new(); + for unit in units { + let mut u = unit.clone(); + u.sort_by(|a, b| span(a.1, !vertical).0.total_cmp(&span(b.1, !vertical).0)); + out.extend(u.windows(2).filter_map(|w| match w { + [a, b] => Some(span(b.1, !vertical).0 - span(a.1, !vertical).1), + _ => None, + })); + } + out +} + +/// A grid packed in `units` (columns, or rows when `vertical`): the units are evened around where +/// they were, every layer is centred in its unit and each unit is laid out from the selection's +/// start on the other axis. +fn grid_moves(units: &[Vec], vertical: bool, spacing: Option, snap: bool) -> Vec { + let boxes: Vec<(f64, f64)> = units.iter().map(|u| unit_box(u, vertical)).collect(); + let across: Vec = boxes + .windows(2) + .filter_map(|w| match w { + [a, b] => Some(b.0 - (a.0 + a.1)), + _ => None, + }) + .collect(); + let g_units = even_gap(&across, spacing); + let g_within = even_gap(&unit_gaps(units, vertical), spacing); + let start = units.iter().flatten().map(|i| span(i.1, !vertical).0).fold(f64::MAX, f64::min); + let mut at = boxes.first().map_or(0.0, |b| snap_to(b.0, snap)); + let mut out = Vec::new(); + for (unit, (_, w)) in units.iter().zip(&boxes) { + let mut u = unit.clone(); + u.sort_by(|a, b| span(a.1, !vertical).0.total_cmp(&span(b.1, !vertical).0)); + let mut pos = start; + for (id, b) in u { + let (lo, hi) = span(b, vertical); + let (lo2, hi2) = span(b, !vertical); + let d_main = snap_to(at + (w - (hi - lo)) / 2.0, snap) - lo; + let d_cross = pos - lo2; + pos += (hi2 - lo2) + g_within; + out.push(if vertical { (id, d_cross, d_main) } else { (id, d_main, d_cross) }); + } + at += w + g_units; + } + out +} diff --git a/crates/engine/src/selection_depth_tests.rs b/crates/engine/src/selection_depth_tests.rs index a754e7343..8e04a5a66 100644 --- a/crates/engine/src/selection_depth_tests.rs +++ b/crates/engine/src/selection_depth_tests.rs @@ -118,8 +118,33 @@ fn layers_at_a_point_list_the_stack_front_most_first() { let got: Vec<(NodeId, u64)> = out["layers"].as_array().unwrap().iter().map(|l| (id_of(&l["id"]).unwrap(), l["depth"].as_u64().unwrap())).collect(); assert_eq!(got, vec![(f, 0), (over, 1), (g, 1), (a, 2)]); + assert!(out["layers"].as_array().unwrap().iter().all(|l| l["locked"] == json!(false)), "none is locked"); assert_eq!(out["layers"][0]["type"], json!("FRAME")); // Nothing under empty canvas; junk is refused. assert_eq!(ex(&mut s, "select.layersAt", json!({"x": 2000, "y": 2000}))["layers"], json!([])); assert!(s.execute("select.layersAt", &json!({"x": "left"})).is_err()); } + +/// Measured in Figma's web app, 2026-11-10 (Select layer lists a locked layer, and picking it selects it). +#[test] +fn layers_at_a_point_list_locked_layers_with_a_flag_and_select_set_takes_them() { + let mut s = Session::new(); + let (f, g, [a, ..], _) = scene(&mut s); + let over = rect_in(&mut s, 10.0, 10.0, Some(f)); + let lk = rect_in(&mut s, 10.0, 10.0, Some(f)); + ex(&mut s, "object.toggleLock", json!({"ids": [lk], "locked": true})); + let out = ex(&mut s, "select.layersAt", json!({"x": 30, "y": 30})); + let got: Vec<(NodeId, u64, bool)> = out["layers"] + .as_array() + .unwrap() + .iter() + .map(|l| (id_of(&l["id"]).unwrap(), l["depth"].as_u64().unwrap(), l["locked"].as_bool().unwrap())) + .collect(); + assert_eq!(got, vec![(f, 0, false), (lk, 1, true), (over, 1, false), (g, 1, false), (a, 2, false)]); + ex(&mut s, "select.set", json!({"ids": [lk]})); + assert_eq!(s.selection(), vec![lk]); + ex(&mut s, "select.none", json!({})); + s.pointer(&ev(PointerKind::Down, 30.0, 30.0, false, false)).unwrap(); + s.pointer(&ev(PointerKind::Up, 30.0, 30.0, false, false)).unwrap(); + assert_eq!(s.selection(), vec![over], "a click still skips the locked layer"); +} diff --git a/crates/engine/src/session/new.rs b/crates/engine/src/session/new.rs index f3b75b630..1ed6d820b 100644 --- a/crates/engine/src/session/new.rs +++ b/crates/engine/src/session/new.rs @@ -17,7 +17,7 @@ impl Session { default_props: Default::default(), prefs: Prefs::default(), prefs_unsaved: false, - tool: tools::ToolState::default(), + tool: tools::ToolState { scale_anchor: (1, 1), ..tools::ToolState::default() }, ui_requests: Vec::new(), ui_dark: None, journal: Vec::new(), diff --git a/crates/engine/src/session/undo.rs b/crates/engine/src/session/undo.rs index 14fdfe5b9..7c234ec76 100644 --- a/crates/engine/src/session/undo.rs +++ b/crates/engine/src/session/undo.rs @@ -65,7 +65,7 @@ impl Session { /// Replace the document with `f(snapshot)` for a live preview during a gesture. pub fn preview(&mut self, f: impl FnOnce(&mut Document, &mut Vec) -> Result<()>) -> Result<()> { let ds = self.ds_mut()?; - let Some(it) = ds.interaction.clone() else { return Err(EngineError::Other("no gesture in progress".into())) }; + let Some(it) = ds.interaction.clone() else { return Err(EngineError::NoGesture) }; let mut doc = (*it.doc).clone(); let mut sel = it.selection.clone(); // What the gesture changes on the selected layers is an explicit edit. diff --git a/crates/engine/src/shape_handles_tests.rs b/crates/engine/src/shape_handles_tests.rs index 73647f4d6..0e3a2f211 100644 --- a/crates/engine/src/shape_handles_tests.rs +++ b/crates/engine/src/shape_handles_tests.rs @@ -3,6 +3,7 @@ use figcraft_doc::{NodeId, NodeKind}; use figcraft_geom::Point; use serde_json::{Value, json}; +use std::f64::consts::TAU; use crate::Session; use crate::params::id_of; @@ -63,7 +64,11 @@ fn polygon_and_star_handles() { let doc = s.doc().unwrap().clone(); let hs = handles(&doc, &[star], 1.0); let kinds: Vec = hs.iter().map(|h| h.0).collect(); - assert_eq!(kinds, vec![ShapeHandle::Radius { corner: 0 }, ShapeHandle::Ratio], "a star has a radius and a ratio handle"); + assert_eq!( + kinds, + vec![ShapeHandle::Radius { corner: 0 }, ShapeHandle::Ratio, ShapeHandle::Count], + "a star has a radius, a ratio and a count handle" + ); // The ratio handle sits on the first inner point; dragging it to the centre's side shrinks it. let ratio_at = hs[1].1; let inner = figcraft_geom::star_points(200.0, 200.0, 5, 0.38)[1]; @@ -78,7 +83,7 @@ fn polygon_and_star_handles() { assert!(radii(&s, star)[0] > 1.0, "the star's points round"); let mut s = Session::new(); let poly = create(&mut s, "shape.polygon", json!({"x": 0, "y": 0, "width": 200, "height": 200})); - assert_eq!(handles(s.doc().unwrap(), &[poly], 1.0).len(), 1, "a polygon has one radius handle"); + assert_eq!(handles(s.doc().unwrap(), &[poly], 1.0).len(), 2, "a polygon has a radius and a count handle"); } #[test] @@ -100,3 +105,100 @@ fn handles_show_only_where_they_can_be_used() { s.execute("vector.edit.begin", &json!({"id": r})).unwrap(); assert!(s.shape_handles().is_empty(), "none while editing points"); } + +fn count_of(s: &Session, id: NodeId) -> u32 { + match s.doc().unwrap().node(id).unwrap().kind { + NodeKind::Polygon { count } | NodeKind::Star { count, .. } => count, + _ => panic!("a polygon or star"), + } +} + +fn count_handle(s: &Session, id: NodeId) -> [f64; 2] { + handles(s.doc().unwrap(), &[id], 1.0).into_iter().find(|h| h.0 == ShapeHandle::Count).expect("a count handle").1 +} + +/// The page point at `deg` degrees clockwise from the shape's own top, `r` from its centre (200 x 200 box). +fn at_angle(s: &Session, id: NodeId, deg: f64, r: f64) -> (f64, f64) { + let a = deg.to_radians(); + let p = s.doc().unwrap().world_transform(id) * Point::new(100.0 + r * a.sin(), 100.0 - r * a.cos()); + (p.x, p.y) +} + +fn count_drag(s: &mut Session, id: NodeId, deg: f64) { + let h = count_handle(s, id); + let to = at_angle(s, id, deg, 80.0); + drag(s, (h[0], h[1]), to, false); +} + +#[test] +fn a_polygon_has_a_count_handle_on_its_first_vertex_clockwise_from_the_top() { + let mut s = Session::new(); + let poly = create(&mut s, "shape.polygon", json!({"x": 0, "y": 0, "width": 200, "height": 200})); + s.execute("node.set", &json!({"ids": [poly], "props": {"pointCount": 5}})).unwrap(); + let h = count_handle(&s, poly); + let v1 = figcraft_geom::polygon_points(200.0, 200.0, 5)[1]; + assert!((Point::new(h[0], h[1]) - v1).hypot() < 1e-6, "on vertex 1, not inset: {h:?} vs {v1:?}"); + assert!((h[0] - (100.0 + 100.0 * (TAU / 5.0).sin())).abs() < 1e-6, "72 degrees from the top"); + // Hovering it finds it, not the radius handle. + assert_eq!(hit(s.doc().unwrap(), &[poly], Point::new(h[0], h[1]), 1.0).map(|x| x.1), Some(ShapeHandle::Count)); +} + +#[test] +fn dragging_the_count_handle_sets_the_count_by_the_angle_about_the_centre() { + let mut s = Session::new(); + let poly = create(&mut s, "shape.polygon", json!({"x": 0, "y": 0, "width": 200, "height": 200})); + s.execute("node.set", &json!({"ids": [poly], "props": {"pointCount": 5}})).unwrap(); + for (deg, want) in [(90.0, 4), (45.0, 8), (120.0, 3), (0.5, 60), (0.0, 60), (200.0, 3)] { + count_drag(&mut s, poly, deg); + assert_eq!(count_of(&s, poly), want, "{deg} degrees"); + } + // The radius from the centre doesn't matter. + let h = count_handle(&s, poly); + let to = at_angle(&s, poly, 90.0, 30.0); + drag(&mut s, (h[0], h[1]), to, false); + assert_eq!(count_of(&s, poly), 4, "90 degrees near the centre"); + // The readout is the count. + let doc = s.doc().unwrap(); + assert_eq!(crate::shape_handles::value(doc, poly, ShapeHandle::Count), Some(4.0)); + // A pointer on the centre has no direction: it gives the most points. + let h = count_handle(&s, poly); + drag(&mut s, (h[0], h[1]), (100.0, 100.0), false); + assert_eq!(count_of(&s, poly), 60, "a pointer on the centre"); +} + +#[test] +fn dragging_a_stars_count_handle_sets_its_points() { + let mut s = Session::new(); + let star = create(&mut s, "shape.star", json!({"x": 0, "y": 0, "width": 200, "height": 200})); + let h = count_handle(&s, star); + let outer = figcraft_geom::star_points(200.0, 200.0, 5, 0.38)[2]; + assert!((Point::new(h[0], h[1]) - outer).hypot() < 1e-6, "on its first outer point clockwise from the top"); + for (deg, want) in [(90.0, 4), (45.0, 8), (130.0, 3), (1.0, 60)] { + count_drag(&mut s, star, deg); + assert_eq!(count_of(&s, star), want, "{deg} degrees"); + } + let NodeKind::Star { inner_ratio, .. } = s.doc().unwrap().node(star).unwrap().kind else { panic!("star") }; + assert!((inner_ratio - 0.38).abs() < 0.02, "the ratio stays through count drags: {inner_ratio}"); +} + +#[test] +fn a_count_drag_is_one_undo_step() { + let mut s = Session::new(); + let poly = create(&mut s, "shape.polygon", json!({"x": 0, "y": 0, "width": 200, "height": 200})); + s.execute("node.set", &json!({"ids": [poly], "props": {"pointCount": 5}})).unwrap(); + count_drag(&mut s, poly, 45.0); + assert_eq!(count_of(&s, poly), 8); + s.undo().unwrap(); + assert_eq!(count_of(&s, poly), 5, "one Ctrl+Z takes the drag back"); +} + +#[test] +fn a_rotated_polygons_count_angle_is_measured_in_its_own_frame() { + let mut s = Session::new(); + let poly = create(&mut s, "shape.polygon", json!({"x": 0, "y": 0, "width": 200, "height": 200})); + s.execute("node.set", &json!({"ids": [poly], "props": {"pointCount": 5, "rotation": 30}})).unwrap(); + for (deg, want) in [(90.0, 4), (45.0, 8)] { + count_drag(&mut s, poly, deg); + assert_eq!(count_of(&s, poly), want, "{deg} degrees in the shape's frame"); + } +} diff --git a/crates/engine/src/tidy_tests.rs b/crates/engine/src/tidy_tests.rs new file mode 100644 index 000000000..6f6034b78 --- /dev/null +++ b/crates/engine/src/tidy_tests.rs @@ -0,0 +1,373 @@ +//! Tidy up (`arrange.tidy`) against what was measured in Figma's web app on 2026-11-12: a row, a +//! column and a 2 x 3 grid of unequal sizes, eight runs on the gap, and the cases where the menu +//! row is greyed out. Figma keeps the order and sizes, evens one gap per axis and keeps the first +//! layer where it is. Tests whose message says "not measured in Figma" pin FigCraft's own choice. + +use crate::Session; +use figcraft_doc::NodeId; +use serde_json::json; + +fn make(s: &mut Session, x: f64, y: f64, w: f64, h: f64) -> NodeId { + NodeId(s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": w, "height": h})).unwrap()["id"].as_u64().unwrap()) +} +fn xy(s: &Session, id: NodeId) -> (f64, f64) { + let b = s.doc().unwrap().world_bounds(id).unwrap(); + (b.x0, b.y0) +} +fn size(s: &Session, id: NodeId) -> (f64, f64) { + let n = s.doc().unwrap().node(id).unwrap(); + (n.width, n.height) +} +fn tidy(s: &mut Session, ids: &[NodeId]) { + s.execute("arrange.tidy", &json!({"ids": ids})).unwrap(); +} +fn can(s: &Session, ids: &[NodeId]) -> bool { + crate::tidy::can_tidy(s.doc().unwrap(), ids) +} +fn all_xy(s: &Session, ids: &[NodeId]) -> Vec<(f64, f64)> { + ids.iter().map(|i| xy(s, *i)).collect() +} +/// Squares of 50 at Y 0 with the given X values. +fn squares(s: &mut Session, xs: &[f64]) -> Vec { + xs.iter().map(|x| make(s, *x, 0.0, 50.0, 50.0)).collect() +} +fn xs_of(s: &Session, ids: &[NodeId]) -> Vec { + ids.iter().map(|i| xy(s, *i).0).collect() +} + +fn row(s: &mut Session, xs: [f64; 4]) -> Vec { + vec![make(s, xs[0], 0., 50., 30.), make(s, xs[1], 10., 70., 50.), make(s, xs[2], -5., 40., 40.), make(s, xs[3], 8., 60., 20.)] +} +fn grid(s: &mut Session) -> Vec { + vec![ + make(s, 0., 0., 50., 30.), + make(s, 80., 5., 70., 50.), + make(s, 190., -3., 40., 40.), + make(s, 2., 90., 60., 20.), + make(s, 85., 95., 40., 50.), + make(s, 200., 92., 55., 35.), + ] +} + +#[test] +fn a_row_keeps_its_order_sizes_and_y_and_evens_the_gaps() { + let mut s = Session::new(); + let ids = row(&mut s, [0., 80., 190., 260.]); + let before = s.undo_depth(); + tidy(&mut s, &ids); + assert_eq!(all_xy(&s, &ids), vec![(0., 0.), (80., 10.), (180., -5.), (250., 8.)]); + assert_eq!(size(&s, ids[1]), (70., 50.)); + assert_eq!(size(&s, ids[3]), (60., 20.)); + assert_eq!(s.undo_depth().0, before.0 + 1); + s.undo().unwrap(); + assert_eq!(xy(&s, ids[3]), (260., 8.)); +} + +#[test] +fn gaps_that_all_differ_take_their_mean_taken_down() { + let mut s = Session::new(); + let ids = row(&mut s, [0., 130., 220., 305.]); + tidy(&mut s, &ids); + assert_eq!(all_xy(&s, &ids), vec![(0., 0.), (98., 10.), (216., -5.), (304., 8.)]); + // Gaps 30, 40, 21 (the third layer 49 wide, 50 tall). + let mut s = Session::new(); + let ids = + vec![make(&mut s, 0., 0., 50., 30.), make(&mut s, 80., 10., 70., 50.), make(&mut s, 190., -5., 49., 50.), make(&mut s, 260., 8., 60., 20.)]; + tidy(&mut s, &ids); + assert_eq!(xs_of(&s, &ids), vec![0., 80., 180., 259.]); +} + +#[test] +fn a_column_keeps_x_and_evens_the_vertical_gaps() { + let mut s = Session::new(); + let ids = + vec![make(&mut s, 0., 0., 50., 30.), make(&mut s, 8., 60., 70., 50.), make(&mut s, -5., 150., 40., 40.), make(&mut s, 6., 220., 60., 20.)]; + tidy(&mut s, &ids); + assert_eq!(all_xy(&s, &ids), vec![(0., 0.), (8., 60.), (-5., 140.), (6., 210.)]); +} + +#[test] +fn the_gap_is_the_most_common_one_else_the_mean() { + // (X before, widths, X after): cases 1, 2, 3, 4, 5, 7 and 8 of the second run. + let cases: [(&[f64], &[f64], &[f64]); 7] = [ + (&[0., 60., 160.], &[50., 50., 50.], &[0., 80., 160.]), + (&[0., 100., 160.], &[50., 50., 50.], &[0., 80., 160.]), + (&[0., 70., 140.], &[50., 50., 50.], &[0., 70., 140.]), + (&[0., 50., 160.], &[50., 50., 50.], &[0., 80., 160.]), + (&[0., 60., 120., 240.], &[50., 50., 50., 50.], &[0., 60., 120., 180.]), + (&[0., 70., 210.], &[50., 100., 30.], &[0., 80., 210.]), + (&[0., 60., 120., 220., 360.], &[50., 50., 50., 50., 50.], &[0., 60., 120., 180., 240.]), + ]; + for (n, (before, widths, after)) in cases.iter().enumerate() { + let mut s = Session::new(); + let ids: Vec = before.iter().zip(widths.iter()).map(|(x, w)| make(&mut s, *x, 0., *w, 50.)).collect(); + tidy(&mut s, &ids); + assert_eq!(xs_of(&s, &ids), after.to_vec(), "case {n}"); + assert!(xy(&s, ids[0]).1 == 0.0 && xy(&s, ids[1]).1 == 0.0, "case {n}: Y kept"); + } +} + +/// Within a pixel: Figma read 52 for the vertical gap in one column and 51 in two (the mean of 60, +/// 40, 55 is 51.67), probably from pixel snapping, so a layer's place along a stack may differ by one. +fn near(got: &[(f64, f64)], want: &[(f64, f64)]) { + assert_eq!(got.len(), want.len()); + for (g, w) in got.iter().zip(want) { + assert!((g.0 - w.0).abs() <= 1.0 && (g.1 - w.1).abs() <= 1.0, "{got:?} vs {want:?}"); + } +} + +#[test] +fn a_grid_is_tidied_by_columns() { + let mut s = Session::new(); + let ids = grid(&mut s); + tidy(&mut s, &ids); + near(&all_xy(&s, &ids), &[(6., -3.), (93., -3.), (203., -3.), (1., 79.), (108., 98.), (195., 88.)]); + assert_eq!(size(&s, ids[4]), (40., 50.)); +} + +#[test] +fn a_transposed_grid_is_tidied_by_rows() { + let mut s = Session::new(); + let ids = vec![ + make(&mut s, 0., 0., 30., 50.), + make(&mut s, 5., 80., 50., 70.), + make(&mut s, -3., 190., 40., 40.), + make(&mut s, 90., 2., 20., 60.), + make(&mut s, 95., 85., 50., 40.), + make(&mut s, 92., 200., 35., 55.), + ]; + tidy(&mut s, &ids); + near(&all_xy(&s, &ids), &[(-3., 6.), (-3., 93.), (-3., 203.), (78., 1.), (98., 108.), (88., 195.)]); +} + +#[test] +fn two_layers_and_a_selection_in_one_cell_are_left_alone() { + let mut s = Session::new(); + let two = squares(&mut s, &[0., 87.]); + let before = (all_xy(&s, &two), s.undo_depth()); + tidy(&mut s, &two); + assert_eq!((all_xy(&s, &two), s.undo_depth()), before, "two layers"); + assert!(!can(&s, &two)); + + let mut s = Session::new(); + let tri = vec![make(&mut s, 100., 460., 50., 30.), make(&mut s, 140., 430., 80., 60.), make(&mut s, 130., 400., 30., 90.)]; + let before = (all_xy(&s, &tri), s.undo_depth()); + tidy(&mut s, &tri); + assert_eq!((all_xy(&s, &tri), s.undo_depth()), before, "overlapping triple"); + assert!(!can(&s, &tri)); +} + +#[test] +fn a_tidy_that_moves_nothing_adds_no_undo_step() { + let mut s = Session::new(); + let ids = squares(&mut s, &[0., 70., 140.]); + let before = s.undo_depth(); + tidy(&mut s, &ids); + assert_eq!(s.undo_depth(), before); + assert_eq!(xs_of(&s, &ids), vec![0., 70., 140.]); + assert!(can(&s, &ids)); +} + +#[test] +fn two_equally_common_gaps_give_the_smaller() { + let mut s = Session::new(); + let ids = squares(&mut s, &[0., 60., 120., 220., 320.]); + tidy(&mut s, &ids); + assert_eq!(xs_of(&s, &ids), vec![0., 60., 120., 180., 240.]); +} + +#[test] +fn a_mean_is_rounded_half_up() { + let mut s = Session::new(); + let ids = squares(&mut s, &[0., 60., 135.]); + tidy(&mut s, &ids); + assert_eq!(xs_of(&s, &ids), vec![0., 68., 136.], "a mean of 17.5 goes up"); + let mut s = Session::new(); + let ids = squares(&mut s, &[0., 60., 135., 215.]); + tidy(&mut s, &ids); + assert_eq!(xs_of(&s, &ids), vec![0., 72., 144., 216.], "a mean of 21.67 goes to 22"); +} + +#[test] +fn layers_on_a_diagonal_are_unavailable() { + let mut s = Session::new(); + let ids = vec![make(&mut s, 0., 0., 50., 50.), make(&mut s, 60., 70., 50., 50.), make(&mut s, 140., 150., 50., 50.)]; + let before = (all_xy(&s, &ids), s.undo_depth()); + tidy(&mut s, &ids); + assert_eq!((all_xy(&s, &ids), s.undo_depth()), before); + assert!(!can(&s, &ids)); +} + +#[test] +fn a_grid_with_an_empty_place_is_unavailable() { + let mut s = Session::new(); + let ids = vec![ + make(&mut s, 0., 0., 50., 50.), + make(&mut s, 70., 0., 50., 50.), + make(&mut s, 150., 0., 50., 50.), + make(&mut s, 0., 80., 50., 50.), + make(&mut s, 72., 90., 50., 50.), + ]; + let before = (all_xy(&s, &ids), s.undo_depth()); + tidy(&mut s, &ids); + assert_eq!((all_xy(&s, &ids), s.undo_depth()), before, "not measured in Figma: an empty place in a grid"); + assert!(!can(&s, &ids), "not measured in Figma: an empty place in a grid"); +} + +#[test] +fn an_overlapping_pair_in_a_row_is_tidied_and_its_negative_gap_counts() { + let mut s = Session::new(); + let ids = squares(&mut s, &[0., 60., 105., 170.]); + assert!(can(&s, &ids)); + tidy(&mut s, &ids); + assert_eq!(xs_of(&s, &ids), vec![0., 57., 114., 171.], "gaps 10, -5, 15 have the mean 6.67, which gives 7"); +} + +#[test] +fn layers_in_an_auto_layout_flow_are_left_alone() { + let mut s = Session::new(); + let f = NodeId( + s.execute("frame.create", &json!({"x": 0, "y": 0, "width": 400, "height": 100, "props": {"layout": "horizontal"}})).unwrap()["id"] + .as_u64() + .unwrap(), + ); + let ids: Vec = (0..3) + .map(|_| NodeId(s.execute("shape.rectangle", &json!({"width": 50, "height": 50, "parent": f})).unwrap()["id"].as_u64().unwrap())) + .collect(); + let before = (all_xy(&s, &ids), s.undo_depth()); + tidy(&mut s, &ids); + assert_eq!((all_xy(&s, &ids), s.undo_depth()), before, "not measured in Figma: auto layout flow children"); + assert!(!can(&s, &ids), "not measured in Figma: auto layout flow children"); + for id in &ids { + s.execute("node.set", &json!({"id": id, "props": {"absolute": true}})).unwrap(); + } + for (id, x) in ids.iter().zip([0., 60., 160.]) { + s.execute("node.set", &json!({"id": id, "props": {"x": x, "y": 0}})).unwrap(); + } + assert_eq!(xs_of(&s, &ids), vec![0., 60., 160.]); + assert!(can(&s, &ids)); + tidy(&mut s, &ids); + assert_eq!(xs_of(&s, &ids), vec![0., 80., 160.]); +} + +#[test] +fn an_irregular_selection_is_unavailable() { + let mut s = Session::new(); + let ids = vec![make(&mut s, 0., 0., 200., 30.), make(&mut s, 0., 50., 90., 50.), make(&mut s, 110., 50., 90., 50.)]; + let before = (all_xy(&s, &ids), s.undo_depth()); + tidy(&mut s, &ids); + assert_eq!((all_xy(&s, &ids), s.undo_depth()), before); + assert!(!can(&s, &ids)); +} + +#[test] +fn spacing_sets_the_gap_and_takes_two_layers() { + let mut s = Session::new(); + let ids = squares(&mut s, &[0., 60., 160.]); + s.execute("arrange.tidy", &json!({"ids": ids, "spacing": 12})).unwrap(); + assert_eq!(xs_of(&s, &ids), vec![0., 62., 124.]); + let mut s = Session::new(); + let two = squares(&mut s, &[0., 87.]); + s.execute("arrange.tidy", &json!({"ids": two, "spacing": 12})).unwrap(); + assert_eq!(xs_of(&s, &two), vec![0., 62.]); + assert!(!can(&s, &two)); +} + +#[test] +fn without_pixel_snapping_a_centred_layer_keeps_its_half_pixel() { + let mut s = Session::new(); + s.execute("view.snapPixel", &json!({"on": false})).unwrap(); + let ids = grid(&mut s); + tidy(&mut s, &ids); + let got = all_xy(&s, &ids); + assert_eq!(got.get(2).map(|p| p.0), Some(202.5), "not measured in Figma: no rounding with Snap to pixel grid off"); + near(&got, &[(6., -3.), (93., -3.), (202.5, -3.), (1., 79.), (108., 98.), (195., 88.)]); +} + +#[test] +fn a_rotated_layer_is_tidied_by_its_box() { + let mut s = Session::new(); + let a = make(&mut s, 0., 0., 50., 50.); + let m = make(&mut s, 80., 0., 40., 40.); + let c = make(&mut s, 200., 0., 50., 50.); + s.execute("node.set", &json!({"id": m, "props": {"rotation": 30}})).unwrap(); + let boxes = |s: &Session| -> Vec { [a, m, c].iter().map(|i| s.doc().unwrap().world_bounds(*i).unwrap()).collect() }; + let b = boxes(&s); + let (g1, g2) = (b[1].x0 - b[0].x1, b[2].x0 - b[1].x1); + let want = ((g1 + g2) / 2.0 + 0.5).floor(); + let rot = figcraft_geom::rotation_degrees(s.doc().unwrap().node(m).unwrap().transform); + tidy(&mut s, &[a, m, c]); + let b = boxes(&s); + assert_eq!(b[0].x0, 0.0); + assert!(((b[1].x0 - b[0].x1) - want).abs() < 1e-6); + assert!(((b[2].x0 - b[1].x1) - want).abs() < 1e-6); + let after = figcraft_geom::rotation_degrees(s.doc().unwrap().node(m).unwrap().transform); + assert!((rot - after).abs() < 1e-9, "rotation unchanged"); +} + +/// Rectangles at Y 0, H 50 with the given (X, W) pairs. +fn bars(s: &mut Session, xw: &[(f64, f64)]) -> Vec { + xw.iter().map(|(x, w)| make(s, *x, 0.0, *w, 50.0)).collect() +} + +#[test] +fn a_row_whose_layers_overlap_in_a_chain_is_tidied_at_its_most_common_gap() { + // Measured in Figma's web app on 2026-11-13: gaps -10, -10, 20 give X 0, 40, 80, 120. + let mut s = Session::new(); + let ids = squares(&mut s, &[0., 40., 80., 150.]); + assert!(can(&s, &ids), "the first and third layers don't overlap, the chain still counts as a row"); + tidy(&mut s, &ids); + assert_eq!(xs_of(&s, &ids), vec![0., 40., 80., 120.]); +} + +#[test] +fn a_negative_gap_is_raised_so_no_layer_reaches_the_one_two_before() { + // Measured in Figma's web app on 2026-11-13, X before 0, 80, 200, 260, 400, 460. + let cases: [([f64; 6], [f64; 6]); 4] = [ + ([100., 10., 100., 100., 100., 100.], [0., 96., 102., 198., 294., 390.]), + ([100., 20., 100., 100., 100., 100.], [0., 91., 102., 193., 284., 375.]), + ([100., 30., 100., 100., 100., 100.], [0., 86., 102., 188., 274., 360.]), + ([100., 100., 100., 10., 100., 100.], [0., 96., 192., 288., 294., 390.]), + ]; + for (widths, want) in cases { + let mut s = Session::new(); + let xs = [0., 80., 200., 260., 400., 460.]; + let pairs: Vec<(f64, f64)> = xs.iter().copied().zip(widths).collect(); + let ids = bars(&mut s, &pairs); + tidy(&mut s, &ids); + assert_eq!(xs_of(&s, &ids), want.to_vec(), "widths {widths:?}"); + } +} + +#[test] +fn a_narrow_first_layer_still_keeps_the_second_after_it() { + // Not measured in Figma (it kept the order in every run): the modal gap -40 would start the + // second layer at -30, before a 10 wide first layer, so the gap is raised to -9. + let mut s = Session::new(); + let xs = [0., 80., 200., 260., 400., 460.]; + let widths = [10., 100., 100., 100., 100., 100.]; + let pairs: Vec<(f64, f64)> = xs.iter().copied().zip(widths).collect(); + let ids = bars(&mut s, &pairs); + tidy(&mut s, &ids); + assert_eq!(xs_of(&s, &ids), vec![0., 1., 92., 183., 274., 365.]); +} + +#[test] +fn a_negative_gap_between_equal_widths_is_the_most_common_gap() { + let mut s = Session::new(); + let xs = [0., 80., 200., 260., 400., 460.]; + let pairs: Vec<(f64, f64)> = xs.iter().map(|x| (*x, 100.)).collect(); + let ids = bars(&mut s, &pairs); + tidy(&mut s, &ids); + assert_eq!(xs_of(&s, &ids), vec![0., 60., 120., 180., 240., 300.]); +} + +#[test] +fn an_explicit_spacing_is_not_raised() { + // Not measured in Figma: the Spacing field stays as typed. + let mut s = Session::new(); + let pairs: Vec<(f64, f64)> = [(0., 100.), (80., 10.), (200., 100.)].to_vec(); + let ids = bars(&mut s, &pairs); + s.execute("arrange.tidy", &json!({"ids": ids, "spacing": -40})).unwrap(); + assert_eq!(xs_of(&s, &ids), vec![0., 60., 30.]); +} diff --git a/crates/format/src/fig/export/shape.rs b/crates/format/src/fig/export/shape.rs index 9ef7b2077..b25bbb5d6 100644 --- a/crates/format/src/fig/export/shape.rs +++ b/crates/format/src/fig/export/shape.rs @@ -181,8 +181,8 @@ impl<'d> Exporter<'d> { /// The editable network (with per-point corner radii, handle mirroring and end caps) and, /// when it has filled areas, their outline. pub(super) fn vector(&mut self, n: &Node, net: &VectorNetwork, f: &mut Fields) { - if net.regions.iter().any(|region| region.fills.is_some() || region.paint_space.is_some()) { - self.warn("vector region paints were left out of the .fig export"); + if net.regions.iter().any(|region| region.paint_space.is_some()) { + self.warn("vector region paint frames were left out (their gradients and images follow the layer's box)"); } let entries: usize = net.regions.iter().flat_map(|r| &r.loops).map(Vec::len).sum(); if net.vertices.len() + net.segments.len() + entries > MAX_NETWORK { @@ -260,11 +260,19 @@ impl<'d> Exporter<'d> { tb: (finite(sg.tb.0), finite(sg.tb.1)), }) .collect(); - let regions = net - .regions - .iter() - .map(|r| network::Region { style: 0, non_zero: r.winding == WindingRule::NonZero, loops: r.loops.clone() }) - .collect(); + // A region with paints of its own (an empty list included) names a style entry that + // holds them; one without writes style 0 and shows the layer's fills. + let mut regions = Vec::with_capacity(net.regions.len()); + for r in &net.regions { + let style = match &r.fills { + Some(paints) => { + let list = self.paints(paints, true, &Bound::default()); + style_of(vec![("fillPaints", list)]) + } + None => 0, + }; + regions.push(network::Region { style, non_zero: r.winding == WindingRule::NonZero, loops: r.loops.clone() }); + } let blob = network::encode(&network::Network { vertices, segments, regions }); let table = styles.into_iter().zip(1u32..).map(|(mut st, id)| { st.insert(0, ("styleID", u(id))); diff --git a/crates/format/src/fig/export_tests.rs b/crates/format/src/fig/export_tests.rs index 221cd7cd9..9cb417078 100644 --- a/crates/format/src/fig/export_tests.rs +++ b/crates/format/src/fig/export_tests.rs @@ -843,21 +843,38 @@ fn round_trip_keeps_the_details() { } #[test] -fn fig_export_warns_when_region_paints_are_left_out() { - let mut doc = generate(3); - let Some(id) = doc.nodes().find_map(|node| match &node.kind { - NodeKind::Vector { network } if !network.regions.is_empty() => Some(node.id), - _ => None, - }) else { - panic!("generated document has no filled vector"); - }; - let node = doc.node_mut(id).unwrap(); - let NodeKind::Vector { network } = &mut node.kind else { panic!("expected vector fixture") }; - let region = network.regions.first_mut().unwrap(); - region.fills = Some(Vec::new()); +fn vector_region_paints_round_trip() { + let square = [(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)].map(|(x, y)| Point::new(x, y)); + let mut doc = Document::new("regions"); + let page = doc.first_page().unwrap(); + let mut two = VectorNetwork::from_points(&square, true); + let again = two.regions[0].clone(); + two.regions.push(again); + let mut half = Paint::solid(Color { r: 0.25, g: 0.5, b: 0.75, a: 1.0 }); + half.opacity = 0.5; + let gradient = Paint::gradient(Gradient::default_for(GradientKind::Linear, Color { r: 1.0, g: 0.0, b: 0.0, a: 1.0 })); + two.regions[0].fills = Some(vec![half, gradient]); + two.regions[1].fills = Some(Vec::new()); + let id = doc.create(page, NodeKind::Vector { network: two }, "Painted", 0.0, 0.0, 100.0, 100.0).unwrap(); + doc.node_mut(id).unwrap().fills = vec![Paint::solid(Color::BLACK)]; + let inherit = VectorNetwork::from_points(&square, true); + let id2 = doc.create(page, NodeKind::Vector { network: inherit }, "Inherits", 0.0, 0.0, 100.0, 100.0).unwrap(); + doc.node_mut(id2).unwrap().fills = vec![Paint::solid(Color::BLACK)]; - let (_, warnings) = export(&doc, None).unwrap(); - assert!(warnings.iter().any(|warning| warning == "vector region paints were left out of the .fig export"), "{warnings:?}"); + let (back, warnings) = round_trip(&doc, "region paints"); + assert!(!warnings.iter().any(|w| w.contains("region")), "{warnings:?}"); + let regions_of = |d: &Document, name: &str| match d.nodes().find(|n| n.name == name).map(|n| &n.kind) { + Some(NodeKind::Vector { network }) => network.regions.clone(), + k => panic!("{name}: {k:?}"), + }; + let painted = regions_of(&back, "Painted"); + assert_eq!(painted.len(), 2); + let fills = painted[0].fills.as_ref().expect("the first region keeps its paints"); + assert_eq!(fills.len(), 2); + assert!(matches!(&fills[0].kind, PaintKind::Solid { .. }) && (fills[0].opacity - 0.5).abs() < 1e-6); + assert!(matches!(&fills[1].kind, PaintKind::Gradient(_))); + assert_eq!(painted[1].fills, Some(Vec::new()), "an unfilled region stays unfilled"); + assert_eq!(regions_of(&back, "Inherits")[0].fills, None, "a region with no paints of its own still shows the layer's"); } #[test] @@ -875,16 +892,18 @@ fn fig_export_warns_when_inherited_region_paints_have_a_paint_frame() { let region = network.regions.first_mut().unwrap(); region.fills = None; region.paint_space = Some(RegionPaintSpace { width: 20.0, height: 10.0, transform: Affine::translate((4.0, 8.0)) }); + let text = "vector region paint frames were left out (their gradients and images follow the layer's box)"; let (_, warnings) = export(&doc, None).unwrap(); - assert!(warnings.iter().any(|warning| warning == "vector region paints were left out of the .fig export"), "{warnings:?}"); + assert!(warnings.iter().any(|warning| warning == text), "{warnings:?}"); let mut plain = doc; let node = plain.node_mut(id).unwrap(); let NodeKind::Vector { network } = &mut node.kind else { panic!("expected vector fixture") }; network.regions[0].paint_space = None; + network.regions[0].fills = Some(vec![Paint::solid(Color::BLACK)]); let (_, warnings) = export(&plain, None).unwrap(); - assert!(!warnings.iter().any(|warning| warning == "vector region paints were left out of the .fig export"), "{warnings:?}"); + assert!(!warnings.iter().any(|warning| warning.contains("region paint")), "{warnings:?}"); } #[test] diff --git a/crates/format/src/fig/tail_tests.rs b/crates/format/src/fig/tail_tests.rs index 663d6002b..264216bcc 100644 --- a/crates/format/src/fig/tail_tests.rs +++ b/crates/format/src/fig/tail_tests.rs @@ -359,6 +359,28 @@ fn vector_region_missing_and_empty_paints_remain_distinct() { assert_eq!(network_of(&empty, "Wave").regions[0].fills, Some(Vec::new())); } +#[test] +fn vector_region_fills_survive_a_fig_export() { + let solid = o(vec![("type", e("SOLID")), ("color", o(vec![("r", f(0.2)), ("g", f(0.4)), ("b", f(0.8)), ("a", f(1.0))])), ("opacity", f(0.5))]); + let gradient = o(vec![ + ("type", e("GRADIENT_LINEAR")), + ( + "stops", + arr(vec![ + o(vec![("position", f(0.0)), ("color", o(vec![("r", f(1.0)), ("g", f(0.0)), ("b", f(0.0)), ("a", f(1.0))]))]), + o(vec![("position", f(1.0)), ("color", o(vec![("r", f(0.0)), ("g", f(0.0)), ("b", f(1.0)), ("a", f(1.0))]))]), + ]), + ), + ]); + let (doc, _) = import(®ion_canvas(Some(vec![solid, gradient]), 1), "Region fills").unwrap(); + let first = network_of(&doc, "Wave").regions[0].fills.clone(); + assert!(first.as_ref().is_some_and(|fills| fills.len() == 2), "{first:?}"); + let (bytes, warnings) = crate::fig::export::export(&doc, None).unwrap(); + assert!(!warnings.iter().any(|warning| warning.contains("region")), "{warnings:?}"); + let (back, _) = import(&bytes, "Again").unwrap(); + assert_eq!(network_of(&back, "Wave").regions[0].fills, first); +} + #[test] fn vector_region_linked_fill_uses_style_paints_without_recording_definition() { let linked = solid(0.9, 0.1, 0.2); diff --git a/crates/ui-egui/locales/en.toml b/crates/ui-egui/locales/en.toml index 90356839d..769ac7a1d 100644 --- a/crates/ui-egui/locales/en.toml +++ b/crates/ui-egui/locales/en.toml @@ -21,6 +21,7 @@ name = "English" "A collection of this file with these modes and variables: override their values per mode and add variables of its own" = "A collection of this file with these modes and variables: override their values per mode and add variables of its own" "A .figcraft file with this name already exists. Choose its full name to confirm replacement." = "A .figcraft file with this name already exists. Choose its full name to confirm replacement." "A later vote" = "A later vote" +"A layer in an auto layout frame is placed by its frame" = "A layer in an auto layout frame is placed by its frame" "A layer on its own aligns to its frame: select more layers, or one in a frame" = "A layer on its own aligns to its frame: select more layers, or one in a frame" "A responsive product page: hero, features, figures, a quote and a footer" = "A responsive product page: hero, features, figures, a quote and a footer" "A spring plays until it settles: its mass, stiffness and damping set how long" = "A spring plays until it settles: its mass, stiffness and damping set how long" @@ -1628,6 +1629,7 @@ name = "English" "This version can't be read." = "This version can't be read." "This version doesn't have it: all of it is new." = "This version doesn't have it: all of it is new." "Tidy up" = "Tidy up" +"Select a row, a column or a full grid of three or more layers, outside an auto layout flow" = "Select a row, a column or a full grid of three or more layers, outside an auto layout flow" "Tile" = "Tile" "Tile type" = "Tile type" "Timer" = "Timer" diff --git a/crates/ui-egui/src/a11y.rs b/crates/ui-egui/src/a11y.rs index d0e34d6fe..d09cb5165 100644 --- a/crates/ui-egui/src/a11y.rs +++ b/crates/ui-egui/src/a11y.rs @@ -995,6 +995,18 @@ pub fn disabled(resp: &Response) { node(resp, "", |n| n.set_disabled()); } +/// `resp`'s node also says `text` (a menu row's state, e.g. "locked"), after any description +/// already set (joined with ", "). +pub fn describe(resp: &Response, text: &str) { + node(resp, "", |n| { + let d = match n.description() { + Some(old) if !old.is_empty() => format!("{old}, {text}"), + _ => text.to_string(), + }; + n.set_description(d); + }); +} + /// What a layer row says besides its name. pub struct RowInfo<'a> { /// The layer's type ("Frame", "Text"). diff --git a/crates/ui-egui/src/canvas/handles.rs b/crates/ui-egui/src/canvas/handles.rs index 491189eda..39019140d 100644 --- a/crates/ui-egui/src/canvas/handles.rs +++ b/crates/ui-egui/src/canvas/handles.rs @@ -206,6 +206,13 @@ pub fn gradient_dragging(ctx: &egui::Context) -> bool { matches!(ctx.data(|d| d.get_temp::(drag_id())), Some(Drag::Gradient { .. })) } +/// Whether the open image fill's crop (its handles, or a drag on the image) is being dragged, the +/// press that starts it included: the open colour picker holds that paint in Crop mode, so the +/// press is its own control, not one outside it that would close it and commit the drag (#2307). +pub fn crop_dragging(ctx: &egui::Context) -> bool { + matches!(ctx.data(|d| d.get_temp::(drag_id())), Some(Drag::Crop { .. })) +} + /// Whether the document has a gesture open: a handle drag edits only inside its own. fn gesture_open(app: &FigApp) -> bool { app.session.ds().is_ok_and(|d| d.interaction.is_some()) diff --git a/crates/ui-egui/src/canvas/input.rs b/crates/ui-egui/src/canvas/input.rs index b4cff10aa..e02aa0cb3 100644 --- a/crates/ui-egui/src/canvas/input.rs +++ b/crates/ui-egui/src/canvas/input.rs @@ -398,7 +398,11 @@ fn send(app: &mut FigApp, kind: PointerKind, pos: Pos2, m: &egui::Modifiers) { app.canvas.pressure = None; } app.canvas.last_pointer = Some(Point::new(ev.x, ev.y)); - if let Err(e) = app.session.pointer(&ev) { + // A gesture something else committed under the held button (a colour picker closing on this + // press) leaves the rest of its drag with nothing to edit: that is not worth saying. + if let Err(e) = app.session.pointer(&ev) + && !matches!(e, figcraft_engine::EngineError::NoGesture) + { app.toast(e.to_string()); } app.canvas.last_hover = hover.then(|| HoverKey::of(app, ev)); diff --git a/crates/ui-egui/src/canvas/overlays.rs b/crates/ui-egui/src/canvas/overlays.rs index 3e15693f9..b285d8792 100644 --- a/crates/ui-egui/src/canvas/overlays.rs +++ b/crates/ui-egui/src/canvas/overlays.rs @@ -701,6 +701,7 @@ fn shape_overlay(app: &FigApp, painter: &egui::Painter, col: Color32) { let text = match hint.handle { ShapeHandle::Radius { .. } => format!("{} {}", tr("Radius"), hint.value), ShapeHandle::Ratio => format!("{} {}%", tr("Ratio"), hint.value), + ShapeHandle::Count => format!("{} {}", tr("Count"), hint.value), }; pill(painter, c + vec2(12.0, 12.0), Align2::LEFT_TOP, text, col); } diff --git a/crates/ui-egui/src/canvas/selection_cache_tests.rs b/crates/ui-egui/src/canvas/selection_cache_tests.rs index 061fe5b59..3166e3014 100644 --- a/crates/ui-egui/src/canvas/selection_cache_tests.rs +++ b/crates/ui-egui/src/canvas/selection_cache_tests.rs @@ -237,3 +237,18 @@ fn the_gesture_start_stands_in_only_while_the_selection_is_only_moved() { app.session.ds_mut().unwrap().selection.pop(); assert!(crate::selection_cache::moved(app.session.ds().unwrap()).is_none()); } + +#[test] +fn the_align_buttons_are_off_for_a_layer_in_an_auto_layout_flow() { + let mut s = Session::new(); + let f = id(s.execute("frame.create", &json!({"x": 0, "y": 0, "width": 200, "height": 100})).unwrap()); + let kid = id(s.execute("shape.rectangle", &json!({"parent": f, "x": 0, "y": 0, "width": 20, "height": 20})).unwrap()); + s.execute("node.set", &json!({"id": f, "props": {"layout": "horizontal", "padding": 0, "gap": 0}})).unwrap(); + s.execute("select.set", &json!({"ids": [kid]})).unwrap(); + let app = FigApp::new(s, Box::new(NoServices)); + let ctx = Context::default(); + let ds = app.session.ds().unwrap(); + let pv = crate::right::position_values(&ctx, &ds.doc.clone(), &ds.selection.clone()); + assert!(!pv.can_align, "Align is greyed out"); + assert!(pv.align_blocked, "and the tip says the frame places the layer"); +} diff --git a/crates/ui-egui/src/context_menu_tests.rs b/crates/ui-egui/src/context_menu_tests.rs index 41c2e0be3..ab480e225 100644 --- a/crates/ui-egui/src/context_menu_tests.rs +++ b/crates/ui-egui/src/context_menu_tests.rs @@ -127,3 +127,102 @@ fn copying_a_link_from_a_frames_name_label_links_that_frame() { crate::menus::invoke(&mut u.app, "edit.copyLink"); assert_eq!(copied.lock().unwrap().last().cloned(), Some(format!("figcraft://node/{}", a.0))); } + +/// Two overlapping rectangles, the upper one locked; the menu opens on the overlap with nothing +/// selected. Returns the app's UI and the ids (lower, locked). +fn overlap_ui() -> (Ui, figcraft_doc::NodeId, figcraft_doc::NodeId) { + let mut s = Session::new(); + let lower = id(&s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 80, "height": 80, "name": "Lower"})).unwrap()); + let upper = id(&s.execute("shape.rectangle", &json!({"x": 120, "y": 120, "width": 80, "height": 80, "name": "Upper"})).unwrap()); + s.execute("object.toggleLock", &json!({"ids": [upper], "locked": true})).unwrap(); + let mut u = Ui::new(s); + u.frame(vec![]); + (u, lower, upper) +} + +/// Measured in Figma's web app, 2026-11-10 (Lock and unlock layers: locked layers are listed in Select layer). +#[test] +fn select_layer_marks_locked_layers_with_a_padlock_and_picks_them() { + let (mut u, lower, upper) = overlap_ui(); + let at = u.app.to_screen(150.0, 150.0); + crate::canvas::open_context_menu(&mut u.app, at, false); + u.app.session.set_selection(vec![]); + crate::menus::open_select_layer(&u.ctx, true); + u.frame(vec![]); + let shapes = flat(&u.frame_output(vec![]).shapes); + // The Layers panel lists the same names; the menu's rows are the right-most copies. + let menu_row = |name: &str| { + let (_, pos, size) = crate::live_tests::texts(&shapes) + .into_iter() + .filter(|(t, _, _)| t == name) + .max_by(|a, b| a.1.x.total_cmp(&b.1.x)) + .unwrap_or_else(|| panic!("no row {name:?}")); + (pos, size) + }; + let (lower_at, upper_at) = (menu_row("Lower"), menu_row("Upper")); + assert!(lower_at.0.x > 300.0 && upper_at.0.x > 300.0, "both layers are listed in the menu"); + let in_leading = |(pos, size): (Pos2, egui::Vec2)| { + let c = pos + size / 2.0; + shapes + .iter() + .filter(|s| !matches!(s, egui::Shape::Text(_))) + .filter(|s| { + let r = s.visual_bounding_rect(); + r.is_positive() + && (r.center().y - c.y).abs() < 8.0 + && r.max.x < c.x - size.x / 2.0 - 4.0 + && r.min.x > c.x - size.x / 2.0 - 40.0 + && r.width() < 20.0 + }) + .count() + }; + assert!(in_leading(upper_at) > 0, "the locked row has a padlock in its leading column"); + assert_eq!(in_leading(lower_at), 0, "the other row has nothing there"); + let p = upper_at.0 + upper_at.1 / 2.0; + for pressed in [true, false] { + u.frame(vec![ + egui::Event::PointerMoved(p), + egui::Event::PointerButton { pos: p, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }, + ]); + } + assert_eq!(u.app.session.selection(), vec![upper], "picking the locked row selects it"); + let _ = lower; +} + +/// The padlock is only paint: the locked row says "locked" to assistive technology too. +#[test] +fn select_layer_locked_row_is_described_as_locked() { + let (mut u, _, _) = overlap_ui(); + let at = u.app.to_screen(150.0, 150.0); + crate::canvas::open_context_menu(&mut u.app, at, false); + u.app.session.set_selection(vec![]); + crate::menus::open_select_layer(&u.ctx, true); + u.ctx.enable_accesskit(); + u.frame(vec![]); + let nodes: Vec = + u.frame_output(vec![]).platform_output.accesskit_update.expect("an AccessKit update").nodes.into_iter().map(|(_, n)| n).collect(); + let row = |name: &str| { + nodes + .iter() + .find(|n| n.role() == egui::accesskit::Role::MenuItem && n.label() == Some(name)) + .unwrap_or_else(|| panic!("no menu row {name:?}")) + }; + assert!(row("Upper").description().is_some_and(|d| d.contains("locked")), "the locked row says locked"); + assert!(!row("Lower").description().is_some_and(|d| d.contains("locked")), "the other row doesn't"); +} + +/// Measured on a single locked layer only (Figma's web app, 2026-11-10): the least certain rule. +#[test] +fn select_layer_needs_more_than_one_layer_under_the_pointer() { + let (mut u, _, _) = overlap_ui(); + let one = u.app.to_screen(105.0, 105.0); + crate::canvas::open_context_menu(&mut u.app, one, false); + u.frame(vec![]); + let shapes = flat(&u.frame_output(vec![]).shapes); + assert!(!has_text(&shapes, "Select layer"), "one layer under the pointer: no Select layer"); + let two = u.app.to_screen(150.0, 150.0); + crate::canvas::open_context_menu(&mut u.app, two, false); + u.frame(vec![]); + let shapes = flat(&u.frame_output(vec![]).shapes); + assert!(has_text(&shapes, "Select layer"), "two layers: it shows"); +} diff --git a/crates/ui-egui/src/crop_image_tests.rs b/crates/ui-egui/src/crop_image_tests.rs index 68ed04a81..05435d856 100644 --- a/crates/ui-egui/src/crop_image_tests.rs +++ b/crates/ui-egui/src/crop_image_tests.rs @@ -194,6 +194,56 @@ fn crop_chosen_in_the_colour_picker_enters_crop_mode() { assert!((scaled[0] - after[0] * 5.0 / 6.0).abs() < 1e-6 && (scaled[3] - after[3] * 5.0 / 6.0).abs() < 1e-6, "{after:?} -> {scaled:?}"); } +/// The reporter's sequence (#2307): the colour picker open on an image fill held in Crop mode +/// (Crop chosen in its mode dropdown, or reopened on a fill that already is), then a press on the +/// layer and a drag. The drag moves the picture inside the layer (its crop), not the layer, the +/// press doesn't close the picker under it, and no internal gesture message reaches the user. +#[test] +fn crop_from_the_colour_picker_then_a_drag_on_the_image_moves_the_crop_not_the_layer() { + let (mut u, layer, _) = setup(); + u.app.ui.picker = Some(crate::colorpicker::PickerTarget::Paint { fills: true, index: 0, ids: vec![layer] }); + for _ in 0..4 { + u.frame(vec![]); + } + choose_mode(&mut u, "Fill", "Crop"); + // Crop mode on the canvas ended (a click away from the image); the picker opens on the Crop fill. + u.app.ui.crop = None; + u.app.ui.picker = Some(crate::colorpicker::PickerTarget::Paint { fills: true, index: 0, ids: vec![layer] }); + for _ in 0..4 { + u.frame(vec![]); + } + let (_, Some(before)) = mode(&u, layer) else { panic!("a crop") }; + let at = u.app.session.doc().unwrap().node(layer).unwrap().transform.as_coeffs(); + let from = u.app.to_screen(100.0, 50.0); + u.drag_to(from, from + vec2(30.0, 10.0)); + u.frame(vec![]); + u.button(from + vec2(30.0, 10.0), false); + let n = u.app.session.doc().unwrap().node(layer).unwrap().clone(); + assert_eq!(n.transform.as_coeffs(), at, "the layer stays where it is"); + assert_eq!((n.width, n.height), (200.0, 100.0), "and keeps its size"); + let (m, Some(after)) = mode(&u, layer) else { panic!("a crop") }; + assert_eq!(m, ImageScaleMode::Crop); + assert_ne!(after, before, "the drag moved the picture inside the layer"); + assert_eq!(u.app.session.selection(), vec![layer]); + assert!(u.app.ui.toast.as_ref().is_none_or(|(t, _)| !t.contains("gesture")), "no internal gesture message: {:?}", u.app.ui.toast); +} + +/// A drag the colour picker's close committed under the held button (a press on a layer closing +/// the picker) leaves the rest of its drag with no gesture: that says nothing to the user. +#[test] +fn a_drag_whose_gesture_was_committed_under_the_button_shows_no_message() { + let (mut u, layer, _) = setup(); + u.app.run("select.set", json!({"ids": [layer]})); + let from = u.app.to_screen(100.0, 50.0); + u.button(from, true); + u.app.session.commit_interaction().unwrap(); + for k in 1..=10 { + u.frame(vec![Event::PointerMoved(from + vec2(3.0, 1.0) * k as f32)]); + } + u.button(from + vec2(30.0, 10.0), false); + assert!(u.app.ui.toast.is_none(), "no message: {:?}", u.app.ui.toast); +} + /// The first paint, an image, of `id`'s fills (`fills`) or strokes, or of region `region` of a vector. fn image_at(u: &Ui, id: NodeId, fills: bool, region: Option) -> figcraft_color::ImagePaint { let n = u.app.session.doc().unwrap().node(id).unwrap(); diff --git a/crates/ui-egui/src/field_tests.rs b/crates/ui-egui/src/field_tests.rs index 483acd444..4d8b5cf62 100644 --- a/crates/ui-egui/src/field_tests.rs +++ b/crates/ui-egui/src/field_tests.rs @@ -941,7 +941,7 @@ fn enter_in_another_field_after_tab_keeps_the_scale_tool() { assert_eq!(u.app.session.tool.tool, figcraft_engine::ToolId::Scale); } -/// K, 2, Enter: 100 x 100 becomes 200 x 200 about the panel's origin, the tool is Move, one undo step. +/// K, 2, Enter: 100 x 100 becomes 200 x 200 about the panel's origin (the centre), the tool is Move, one undo step. #[test] fn k_two_enter_scales_the_selection_by_two() { let (mut u, r) = scale_setup(); @@ -951,8 +951,8 @@ fn k_two_enter_scales_the_selection_by_two() { u.frame(vec![Event::Text("2".to_string())]); key(&mut u, Key::Enter, Modifiers::NONE); u.frame(vec![]); - // About the panel's origin, FigCraft's top-left default (Figma's grid starts at the centre). - assert_eq!(geom(&u, r), (0.0, 0.0, 200.0, 200.0)); + // About the panel's origin, which starts at the centre as Figma's grid does. + assert_eq!(geom(&u, r), (-50.0, -50.0, 200.0, 200.0)); assert!(!scale_field_focused(&u), "the field let go of the keyboard"); assert_eq!(u.app.session.tool.tool, figcraft_engine::ToolId::Move); assert_eq!(u.app.session.ds().unwrap().selection, vec![r]); @@ -971,7 +971,8 @@ fn the_scale_field_takes_2x_and_1_5() { u.frame(vec![Event::Text(text.to_string())]); key(&mut u, Key::Enter, Modifiers::NONE); u.frame(vec![]); - assert_eq!(geom(&u, r), (0.0, 0.0, size, size), "{text}"); + let at = 50.0 - size / 2.0; + assert_eq!(geom(&u, r), (at, at, size, size), "{text}"); } } diff --git a/crates/ui-egui/src/layers_behaviour_tests.rs b/crates/ui-egui/src/layers_behaviour_tests.rs index c56adecdf..93a80d9bd 100644 --- a/crates/ui-egui/src/layers_behaviour_tests.rs +++ b/crates/ui-egui/src/layers_behaviour_tests.rs @@ -841,3 +841,100 @@ fn search_fields_keep_their_text_in_the_middle() { let off = off_centre(&mut u, "Search assets"); assert!(off < 1.0, "Search assets is {off} points off the middle"); } + +/// The centre of `id`'s icon, a top-level row: the row's left edge is the first point from the +/// left at which the pointer is over it, and the icon's centre is 8 (margin) + 4 + 22 points +/// further right. +fn icon_of(u: &mut Ui, id: NodeId) -> Pos2 { + let y = u.row_at(id).y; + let mut left = None; + for x in 0..150 { + let p = Pos2::new(x as f32, y); + u.app.session.ds_mut().unwrap().hover = None; + u.frame(vec![Event::PointerMoved(p)]); + if u.app.session.ds().unwrap().hover == Some(id) { + left = Some(x as f32); + break; + } + } + Pos2::new(left.expect("the row has a left edge") + 34.0, y) +} + +/// Measured in Figma's web app, 2026-11-12: a double-click on a layer's icon zooms the canvas to +/// the layer and starts no rename (a double-click on the name renames, as before). +#[test] +fn a_double_click_on_a_layers_icon_zooms_to_it_instead_of_renaming() { + let mut s = Session::new(); + rect(&mut s, "near", 0.0, None); + let far = rect(&mut s, "far", 3000.0, None); + s.execute("select.none", &json!({})).unwrap(); + let mut u = Ui::new(s); + u.frame(vec![]); + let icon = icon_of(&mut u, far); + let view = |u: &Ui| { + let v = &u.app.session.ds().unwrap().view; + (v.cx, v.cy, v.zoom) + }; + let before = view(&u); + for _ in 0..2 { + u.button(icon, true); + u.button(icon, false); + } + u.frame(vec![]); + assert_eq!(u.app.ui.rename, None, "a double-click on the icon renames nothing"); + assert_eq!(u.app.session.selection(), vec![far], "the layer is selected"); + let after = view(&u); + assert_ne!(after, before, "the view moved"); + u.app.session.execute("view.set", &json!({"cx": before.0, "cy": before.1, "zoom": before.2})).unwrap(); + u.app.session.execute("view.zoomSelection", &json!({})).unwrap(); + assert_eq!(after, view(&u), "the view frames the layer, as view.zoomSelection does"); +} + +/// A double-click's release is also a click on the row; with Ctrl held it must not toggle the layer +/// back out of the selection the zoom just made, nor can Shift restore a range. +#[test] +fn an_icon_double_click_keeps_its_selection_when_a_modifier_is_held() { + let mut s = Session::new(); + rect(&mut s, "near", 0.0, None); + let far = rect(&mut s, "far", 3000.0, None); + s.execute("select.none", &json!({})).unwrap(); + let mut u = Ui::new(s); + u.frame(vec![]); + let icon = icon_of(&mut u, far); + let before = (u.app.session.ds().unwrap().view.cx, u.app.session.ds().unwrap().view.zoom); + for _ in 0..2 { + for pressed in [true, false] { + let e = Event::PointerButton { pos: icon, button: egui::PointerButton::Primary, pressed, modifiers: CMD }; + u.frame_with(vec![Event::PointerMoved(icon), e], CMD); + } + } + u.frame(vec![]); + assert_eq!(u.app.session.selection(), vec![far], "the layer stays selected"); + assert_eq!(u.app.ui.rename, None); + let v = &u.app.session.ds().unwrap().view; + assert_ne!((v.cx, v.zoom), before, "the view frames the layer"); +} + +/// A Shift-double-click on an icon leaves just that layer selected, and it becomes the anchor: the +/// next Shift-click selects the range from it, not a toggle. +#[test] +fn an_icon_double_click_becomes_the_range_anchor() { + let (mut u, [a, b, c, d]) = four(); + u.frame(vec![]); + let a_row = u.row_at(a); + click(&mut u, a_row, Modifiers::NONE); + let icon = icon_of(&mut u, b); + for _ in 0..2 { + for pressed in [true, false] { + let e = Event::PointerButton { pos: icon, button: egui::PointerButton::Primary, pressed, modifiers: SHIFT }; + u.frame_with(vec![Event::PointerMoved(icon), e], SHIFT); + } + } + for _ in 0..30 { + u.frame(vec![]); + } + assert_eq!(u.app.session.selection(), vec![b], "the icon's layer is all that is selected"); + let d_row = u.row_at(d); + click(&mut u, d_row, SHIFT); + assert_eq!(sorted(u.app.session.selection()), sorted(vec![b, c, d]), "the range from the icon's layer"); +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 19cb52397..4a0b38768 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -278,6 +278,8 @@ mod text_link_tests; #[cfg(test)] mod text_mixed_fill_tests; #[cfg(test)] +mod tidy_tests; +#[cfg(test)] mod titlebar_tests; #[cfg(test)] mod ui_params_tests; diff --git a/crates/ui-egui/src/menus/select_layer.rs b/crates/ui-egui/src/menus/select_layer.rs index 73571f38e..0628dfa3b 100644 --- a/crates/ui-egui/src/menus/select_layer.rs +++ b/crates/ui-egui/src/menus/select_layer.rs @@ -15,7 +15,8 @@ pub fn open_select_layer(ctx: &egui::Context, open: bool) { } /// The context menu's "Select layer" submenu (right-click on the canvas): every layer under the -/// click, nested ones indented, the selected ones checked. Returns whether one was picked. +/// click (locked ones with a padlock), nested ones indented, the selected ones checked; shown +/// only with more than one layer under the pointer. Returns whether one was picked. pub(super) fn select_layer_menu(app: &mut FigApp, ui: &mut Ui, pos: egui::Pos2, t: &Tokens) -> bool { if !app.canvas.rect.contains(pos) { return false; @@ -23,15 +24,21 @@ pub(super) fn select_layer_menu(app: &mut FigApp, ui: &mut Ui, pos: egui::Pos2, let p = app.to_page(pos); let Ok(ds) = app.session.ds() else { return false }; let tol = 2.0 / ds.view.zoom.max(1e-6); - let layers: Vec<(figcraft_doc::NodeId, usize, String)> = - figcraft_doc::geometry::layers_at(&ds.doc, ds.page, p, tol, Some(&figcraft_engine::booleans::result_outline(&ds.doc, &ds.selection))) + let opts = figcraft_doc::geometry::HitOpts { locked: true }; + let layers: Vec<(figcraft_doc::NodeId, usize, String, bool)> = { + let result = figcraft_engine::booleans::result_outline(&ds.doc, &ds.selection); + figcraft_doc::geometry::layers_at_opts(&ds.doc, ds.page, p, tol, Some(&result), opts) .into_iter() .take(40) .filter_map(|(id, depth)| { - ds.doc.node(id).map(|n| (id, depth, if n.name.is_empty() { n.kind.type_name().to_lowercase() } else { n.name.clone() })) + ds.doc.node(id).map(|n| { + let name = if n.name.is_empty() { n.kind.type_name().to_lowercase() } else { n.name.clone() }; + (id, depth, name, figcraft_engine::tools::locked_in(&ds.doc, id)) + }) }) - .collect(); - if layers.is_empty() { + .collect() + }; + if layers.len() < 2 { return false; } let sel = ds.selection.clone(); @@ -40,8 +47,8 @@ pub(super) fn select_layer_menu(app: &mut FigApp, ui: &mut Ui, pos: egui::Pos2, SubmenuOptions { area: Id::unique("ctx_select_layer"), key: SELECT_LAYER, label: tr("Select layer"), gap: 4.0, constrain: true, tokens: t }, |ui| { let mut picked = None; - for (id, depth, name) in &layers { - if indented_item(ui, name, "", true, sel.contains(id), 12.0 * (*depth).min(8) as f32, t) { + for (id, depth, name, locked) in &layers { + if indented_item(ui, name, "", true, sel.contains(id), *locked, 12.0 * (*depth).min(8) as f32, t) { picked = Some(*id); } } diff --git a/crates/ui-egui/src/menus/tree.rs b/crates/ui-egui/src/menus/tree.rs index ac4e7059d..7443ffc57 100644 --- a/crates/ui-egui/src/menus/tree.rs +++ b/crates/ui-egui/src/menus/tree.rs @@ -395,17 +395,22 @@ fn need_width(ui: &Ui, w: f32) { } pub(crate) fn item(ui: &mut Ui, label: &str, shortcut: &str, enabled: bool, checked: bool, t: &Tokens) -> bool { - indented_item(ui, label, shortcut, enabled, checked, 0.0, t) + indented_item(ui, label, shortcut, enabled, checked, false, 0.0, t) } -/// A menu row whose label starts `indent` pixels further in (nested layers). -pub(super) fn indented_item(ui: &mut Ui, label: &str, shortcut: &str, enabled: bool, checked: bool, indent: f32, t: &Tokens) -> bool { +/// A menu row whose label starts `indent` pixels further in (nested layers); `locked` paints a +/// padlock in the leading column (a checked row shows the check instead). +#[allow(clippy::too_many_arguments)] +pub(super) fn indented_item(ui: &mut Ui, label: &str, shortcut: &str, enabled: bool, checked: bool, locked: bool, indent: f32, t: &Tokens) -> bool { let w = ui.available_width(); let (r, resp) = ui.allocate_exact_size(vec2(w, 28.0), Sense::click()); a11y::menu_item(&resp, label, shortcut, checked.then_some(true)); if !enabled { a11y::disabled(&resp); } + if locked { + a11y::describe(&resp, i18n::tr("locked")); + } // The keyboard's item is highlighted like the hovered one. a11y::own_focus(&resp); let hov = plain_row_hover(ui, &resp) && enabled; @@ -415,6 +420,8 @@ pub(super) fn indented_item(ui: &mut Ui, label: &str, shortcut: &str, enabled: b let col = if enabled { t.menu_text } else { t.menu_dim }; if checked { icons::paint(ui.painter(), Rect::from_center_size(pos2(r.min.x + 12.0, r.center().y), vec2(12.0, 12.0)), Icon::Check, col); + } else if locked { + icons::paint(ui.painter(), Rect::from_center_size(pos2(r.min.x + 12.0, r.center().y), vec2(12.0, 12.0)), Icon::Lock, col); } let galley = ui.painter().layout_no_wrap(label.to_string(), regular(12.0), col); let keys = (!shortcut.is_empty()) diff --git a/crates/ui-egui/src/panels/layers.rs b/crates/ui-egui/src/panels/layers.rs index 7179012b5..138e3ec6f 100644 --- a/crates/ui-egui/src/panels/layers.rs +++ b/crates/ui-egui/src/panels/layers.rs @@ -1241,7 +1241,8 @@ fn layers(app: &mut FigApp, ui: &mut Ui) { let icon = node_icon(&doc, row.id); let shown = n.visible && !row.dimmed; let icon_col = row_color(&t, is_comp || icon == Icon::Slot, shown, t.icon, t.text_tertiary); - icons::paint(ui.painter(), Rect::from_center_size(pos2(x0 + 22.0, r.center().y), vec2(14.0, 14.0)), icon, icon_col); + let icon_rect = Rect::from_center_size(pos2(x0 + 22.0, r.center().y), vec2(14.0, 14.0)); + icons::paint(ui.painter(), icon_rect, icon, icon_col); let name_x = x0 + 36.0; if app.ui.rename.is_some_and(|rn| rn.id == row.id) { if let Some(new) = rename_field(app, ui, row.id, row.depth, &n.name, r) { @@ -1262,8 +1263,21 @@ fn layers(app: &mut FigApp, ui: &mut Ui) { if resp.clicked() { clicked = Some((row.id, ui.input(|i| i.modifiers))); } - if resp.double_clicked() && !crate::menus::dev_mode_refuses(app, "object.rename") { - app.ui.rename = Some(Rename { id: row.id, start: true }); + if resp.double_clicked() { + // On the icon it zooms to the layer and renames nothing (measured in Figma's web + // app, 2026-11-12); elsewhere on the row it renames. + if resp.interact_pointer_pos().is_some_and(|p| icon_rect.contains(p)) { + if sel.as_slice() != [row.id] { + app.run("select.set", json!({"ids": [row.id]})); + } + app.run("view.zoomSelection", json!({})); + // The release is also a click: it must not toggle or extend the selection. + clicked = None; + // The layer is the anchor of the next Shift-click's range. + app.ui.layer_anchor = Some(row.id); + } else if !crate::menus::dev_mode_refuses(app, "object.rename") { + app.ui.rename = Some(Rename { id: row.id, start: true }); + } } if resp.secondary_clicked() { if !sel.contains(&row.id) { diff --git a/crates/ui-egui/src/panels/right.rs b/crates/ui-egui/src/panels/right.rs index 75aa10e0e..9446279fe 100644 --- a/crates/ui-egui/src/panels/right.rs +++ b/crates/ui-egui/src/panels/right.rs @@ -614,6 +614,8 @@ fn position(app: &mut FigApp, ui: &mut Ui, doc: &Arc, shown: &Arc, pub y: Option, pub rot: Option, @@ -644,6 +646,7 @@ pub(crate) fn position_values(ctx: &egui::Context, doc: &Arc, sel: &[N let parent = |n: &Node| n.parent.and_then(|p| doc.node(p)); crate::selection_cache::cached(ctx, "position", doc, sel, &[], || PositionValues { can_align: figcraft_engine::cmd::arrange::can_align(doc, sel), + align_blocked: figcraft_engine::cmd::arrange::align_blocked_by_auto_layout(doc, sel), x: common(doc, sel, |n| x_of(doc, n)), y: common(doc, sel, |n| y_of(doc, n)), rot: common(doc, sel, |n| rot_of(doc, n)), @@ -657,12 +660,18 @@ pub(crate) fn position_values(ctx: &egui::Context, doc: &Arc, sel: &[N }) } +/// Whether the Design panel offers Tidy up for `sel`: three or more layers forming a row, a column +/// or a full grid, none in an auto layout flow (`can_tidy`). +pub(crate) fn tidy_available(ctx: &egui::Context, doc: &Arc, sel: &[NodeId]) -> bool { + crate::selection_cache::cached(ctx, "tidy", doc, sel, &[], || figcraft_engine::tidy::can_tidy(doc, sel)) +} + /// Draw alignment and distribution, X/Y and rotation with flip/rotate controls, the /// absolute-position toggle and frame constraints. fn position_fields(app: &mut FigApp, ui: &mut Ui, doc: &Arc, sel: &[NodeId]) { let pv = position_values(ui.ctx(), doc, sel); let col = widgets::col_width(ui.available_width()); - align_row(app, ui, sel, pv.can_align, col); + align_row(app, ui, sel, pv.can_align, pv.align_blocked, col); position_row(app, ui, doc, sel, &pv, col); rotation_row(app, ui, doc, sel, pv.rot, col); if pv.in_frame { @@ -671,7 +680,7 @@ fn position_fields(app: &mut FigApp, ui: &mut Ui, doc: &Arc, sel: &[No } /// Alignment, and distribution and tidy up for three or more layers. -fn align_row(app: &mut FigApp, ui: &mut Ui, sel: &[NodeId], can_align: bool, col: f32) { +fn align_row(app: &mut FigApp, ui: &mut Ui, sel: &[NodeId], can_align: bool, blocked: bool, col: f32) { let ids = sel.to_vec(); widgets::sublabels(ui, tr("Alignment"), None); row(ui, 32.0, |ui| { @@ -691,19 +700,30 @@ fn align_row(app: &mut FigApp, ui: &mut Ui, sel: &[NodeId], can_align: bool, col let v = widgets::segmented(ui, &items[3..], None, w).map(|i| i + 3); h.or(v) }); - picked.response.on_disabled_hover_text(tr("A layer on its own aligns to its frame: select more layers, or one in a frame")); + let why = if blocked { + tr("A layer in an auto layout frame is placed by its frame") + } else { + tr("A layer on its own aligns to its frame: select more layers, or one in a frame") + }; + picked.response.on_disabled_hover_text(why); if let Some(i) = picked.inner { app.run(cmds[i], json!({"ids": ids})); } if sel.len() > 2 { let more = icons::button(ui, Icon::DistributeH, 24.0, false, tr("Distribute and tidy")); menu_popup(&more).show(|ui| { - for (l, c) in [ - (tr("Distribute horizontal spacing"), "distribute.horizontal"), - (tr("Distribute vertical spacing"), "distribute.vertical"), - (tr("Tidy up"), "arrange.tidy"), + let can_tidy = app.session.ds().is_ok_and(|ds| tidy_available(ui.ctx(), &ds.doc, &ids)); + for (l, c, on) in [ + (tr("Distribute horizontal spacing"), "distribute.horizontal", true), + (tr("Distribute vertical spacing"), "distribute.vertical", true), + (tr("Tidy up"), "arrange.tidy", can_tidy), ] { - if menu_item(ui, l, crate::shortcuts::shortcut(c).unwrap_or("")) { + let item = ui.add_enabled_ui(on, |ui| menu_item(ui, l, crate::shortcuts::shortcut(c).unwrap_or(""))); + if !on { + item.response + .on_disabled_hover_text(tr("Select a row, a column or a full grid of three or more layers, outside an auto layout flow")); + } + if item.inner { app.run(c, json!({"ids": ids})); ui.close(); } diff --git a/crates/ui-egui/src/tidy_tests.rs b/crates/ui-egui/src/tidy_tests.rs new file mode 100644 index 000000000..26d0d2146 --- /dev/null +++ b/crates/ui-egui/src/tidy_tests.rs @@ -0,0 +1,30 @@ +//! The Design panel's Tidy up row follows the engine's rule (measured in Figma's web app on +//! 2026-11-12): offered for three or more layers forming a row, a column or a full grid, greyed out otherwise. + +use egui::Context; +use figcraft_doc::NodeId; +use figcraft_engine::Session; +use serde_json::json; + +use crate::{FigApp, NoServices}; + +fn rect(s: &mut Session, x: f64, y: f64, w: f64, h: f64) -> NodeId { + NodeId(s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": w, "height": h})).unwrap()["id"].as_u64().unwrap()) +} + +fn available(layers: &[(f64, f64, f64, f64)]) -> bool { + let mut s = Session::new(); + let ids: Vec = layers.iter().map(|(x, y, w, h)| rect(&mut s, *x, *y, *w, *h)).collect(); + s.execute("select.set", &json!({"ids": ids})).unwrap(); + let app = FigApp::new(s, Box::new(NoServices)); + let ctx = Context::default(); + let doc = app.session.ds().unwrap().doc.clone(); + crate::right::tidy_available(&ctx, &doc, &ids) +} + +#[test] +fn tidy_up_is_off_in_the_panel_for_overlapping_layers() { + assert!(available(&[(0., 0., 50., 50.), (80., 0., 50., 50.), (160., 0., 50., 50.)]), "three squares in a row"); + assert!(!available(&[(100., 460., 50., 30.), (140., 430., 80., 60.), (130., 400., 30., 90.)]), "the overlapping triple"); + assert!(!available(&[(0., 0., 50., 50.), (87., 0., 50., 50.)]), "two squares"); +} diff --git a/crates/ui-egui/src/widgets/colorpicker.rs b/crates/ui-egui/src/widgets/colorpicker.rs index 6aa0c4915..662e4ba24 100644 --- a/crates/ui-egui/src/widgets/colorpicker.rs +++ b/crates/ui-egui/src/widgets/colorpicker.rs @@ -1041,7 +1041,8 @@ pub fn show(app: &mut FigApp, ctx: &egui::Context) { let picking = app.session.tool.pick_only || app.session.tool.picked.is_some(); // Nor may a press on the open gradient's handles or stops on the canvas: they are this picker's // controls, and the canvas took the press before the picker drew (#1852). - let own = picking || crate::handles::gradient_dragging(ctx); + // Nor may one on the crop of an image paint held in Crop mode (#2307). + let own = picking || crate::handles::gradient_dragging(ctx) || crate::handles::crop_dragging(ctx); pop = pop.close_on_outside(!own); // Only the opening control is held out: any other sidebar or canvas press dismisses it. let mut held: Vec = app.ui.picker_button.into_iter().collect(); diff --git a/docs/dev-mode-parity.md b/docs/dev-mode-parity.md index 07e618495..d77dce75f 100644 --- a/docs/dev-mode-parity.md +++ b/docs/dev-mode-parity.md @@ -1,6 +1,6 @@ # Dev Mode parity -> **Last reviewed:** 2026-10-24 · **Last updated:** 2026-11-12 · **Change:** patch (CSS code export writes several fills as one layered `background`, top first, as the incumbent does (#2271): a solid above another fill becomes a one-colour gradient, the bottom solid stays a plain colour, Tailwind gets one `[background:...]` class; the Annotation tool (Shift+T, `tool.annotation {id?}`): with a layer selected (or an `id`) it asks the UI for that layer's note at once, and in the tool a press on a layer selects it and asks for its note, a press on empty canvas does nothing; the Inspect tab then opens (never toggles away) with the caret in that layer's new-note field, and the engine never writes the note itself (#1840); the handoff mode reads Developer Mode in the interface, its ids and saved fields unchanged; class names transliterate non-ASCII layer names (#1235); measurements kept on the canvas; a read-only layers panel in Dev Mode; earlier: import lines in generated layer trees; compare with any saved version; Dev Mode behaviour suite: an inspect-only canvas, Changed in the ready list, statuses only on frames and sections; plugin panels from the Inspect tab) · **Target:** Figma Design Dev Mode (desktop app 126.10.7) +> **Last reviewed:** 2026-10-24 · **Last updated:** 2026-11-12 · **Change:** patch (SwiftUI, Compose and Flutter code write every visible colour and gradient fill of a frame, group, rectangle or ellipse in paint order, gradients as gradients, instead of one colour per layer (chained `.background` in SwiftUI, chained `Modifier.background` in Compose, a `DecoratedBox` for each fill under the top one in Flutter); CSS code export writes several fills as one layered `background`, top first, as the incumbent does (#2271): a solid above another fill becomes a one-colour gradient, the bottom solid stays a plain colour, Tailwind gets one `[background:...]` class; the Annotation tool (Shift+T, `tool.annotation {id?}`): with a layer selected (or an `id`) it asks the UI for that layer's note at once, and in the tool a press on a layer selects it and asks for its note, a press on empty canvas does nothing; the Inspect tab then opens (never toggles away) with the caret in that layer's new-note field, and the engine never writes the note itself (#1840); the handoff mode reads Developer Mode in the interface, its ids and saved fields unchanged; class names transliterate non-ASCII layer names (#1235); measurements kept on the canvas; a read-only layers panel in Dev Mode; earlier: import lines in generated layer trees; compare with any saved version; Dev Mode behaviour suite: an inspect-only canvas, Changed in the ready list, statuses only on frames and sections; plugin panels from the Inspect tab) · **Target:** Figma Design Dev Mode (desktop app 126.10.7) **Breadth ~98%, ready ~78% (estimated).** The inspect surface is broad, components connect to the code components of a repository (with their imports, also inside generated layer trees), @@ -10,10 +10,12 @@ repository, third-party integrations. Remaining: 1–2 h. | Feature | Status | Notes | |---|---|---| +| 2026-11-12 | patch | SwiftUI, Compose and Flutter code export kept one colour per layer (the bottom visible solid, or a gradient's first stop) and dropped every other fill (#2271). Now each writes every visible solid and gradient fill of a frame, group, rectangle or ellipse, in paint order, and a gradient as a gradient. SwiftUI chains `.background(...)` with the top fill first, since each one goes behind the ones before it (a rectangle or ellipse fills with the bottom paint and lays a copy of the shape over it for each paint above). Compose chains `Modifier.background(...)` with the bottom fill first, since each one draws over the ones before it (a linear gradient snaps to eight directions, radial and angular ones sit at the box's centre). Flutter keeps the top fill in the `Container` and wraps each fill under it in a `DecoratedBox`, the bottom fill outermost and the drop shadow on the outermost box. A layer with one solid fill gives the same code as before; a lone gradient is now a gradient, not its first stop's colour. Still not written: image and pattern fills in the native targets, ArkUI (one background and one gradient per component, so a stack needs extra nodes) and text with several fills. The incumbent's iOS and Android output wasn't measured: the order follows how each platform paints. Percentages and hours unchanged | | 2026-11-07 | patch | Naming: the handoff mode is called Developer Mode in the interface, its shortcut row, its toasts, the control channel's refusal, the board refusal, the measurement parameter doc, the `.fig` export note, the CLI help and every catalog (24 languages, translations awaiting native review), since Figma holds a US registration for Dev Mode (7574348); command ids (`view.devMode`, `devMode.*`), preference keys and saved-document fields are unchanged, and the Actions palette still finds the command by the old name | | Dev Mode toggle (Shift+D), Inspect panel | done | the canvas only inspects: presses select, pan and comment but never move, resize, draw or edit text and vectors; menus and shortcuts refuse design edits with a note (Dev Mode's annotations, statuses, dev resources, measurements, code connections and comments still work); a drawing tool chosen in the toolbar goes back to the design. The layers panel only selects and expands (no renaming, reordering, hiding or locking; a double click says why), and the Pages list only opens pages (no adding, renaming, reordering, duplicating or deleting). Files dropped on the canvas aren't imported (a dropped document still opens as a file of its own), and the Assets panel places, swaps and applies nothing, doesn't change Hide when publishing, and doesn't accept library updates or add, remove or swap libraries; each says why | | Properties with their styles and variables; redlines on hover | done | positions from the frame around the layer (groups aren't frames), rotation, radius (CSS corner order), opacity, blend; colours in hex, RGB, CSS, HSL or HSB (`inspect.properties {colorFormat}`, the Inspect tab's Color format) | | Code: CSS, iOS (SwiftUI), Android (Compose), Flutter | done | plus HTML, React, Vue and Leptos (ours; Leptos: `#[component]` functions with `#[prop]` defaults, variant enums and `view!` markup; Flutter is ours too: a `StatelessWidget` for a component, a widget tree for a layer); components take properties as parameters, instances are calls; CSS in px or rem (`inspect.code {unit, rootFontSize}`), with rotation, blend modes, several fills as one layered `background` (top first), gradient directions and kinds (linear, radial, conic), text alignment, case and decoration; class names from layer names transliterate non-ASCII scripts into readable ASCII (로그인 화면 → `rogeuin-hwamyeon`, кнопка → `knopka`, über → `uber`; symbols-only names take the node's kind, `.text`), and the 40-character cut lands on a word boundary (#1235) | +| Code: CSS, iOS (SwiftUI), Android (Compose), Flutter | done | plus HTML, React, Vue and Leptos (ours; Leptos: `#[component]` functions with `#[prop]` defaults, variant enums and `view!` markup; Flutter is ours too: a `StatelessWidget` for a component, a widget tree for a layer); components take properties as parameters, instances are calls; CSS in px or rem (`inspect.code {unit, rootFontSize}`), with rotation, blend modes, gradient directions and kinds (linear, radial, conic), text alignment, case and decoration; class names from layer names transliterate non-ASCII scripts into readable ASCII (로그인 화면 → `rogeuin-hwamyeon`, кнопка → `knopka`, über → `uber`; symbols-only names take the node's kind, `.text`), and the 40-character cut lands on a word boundary (#1235); SwiftUI, Compose and Flutter write every colour and gradient fill of a layer in paint order, gradients as gradients (chained `.background` in SwiftUI, top fill first; chained `Modifier.background` in Compose, bottom fill first, a linear gradient snapped to eight directions and radial and angular ones at the box's centre; in Flutter a `DecoratedBox` for each fill under the top one); the native targets don't write image or pattern fills yet, and ArkUI and text still take one colour (#2271) | | Assets list with export | done | layers with export settings, icons (small, vector shapes only: SVG) and images (PNG); the icon rule is ours | | Annotations: pinned properties, categories, coloured callouts, filter | done | the Annotation tool (Shift+T, `tool.annotation`) picks a layer by a click or from the selection and opens its note field in the Inspect tab. Figma's placement, cursor and whether the tool stays selected are unmeasured (Developer Mode is paywalled in the web app); staying selected until V or Escape, like the Comment tool, is inferred, and there is no toolbar button or icon yet | | Ready for dev list, statuses, "Changed" after edits | done | the list filters Ready for dev, Changed, Completed or any, and badges changed ones (`inspect.readyForDev {status: changed}`, `changed` per item); only sections and frames at the top of a page or section take a status (others are refused) | diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index f61a28db8..feeac9e05 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,6 +1,6 @@ # File format parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-13 · **Change:** minor (`.fig` export writes text on a path (#2323); `.jam` import: shapes with text come in as native board shapes (#1808); `.fig` export writes image adjustments (#2297); `.fig` import: a numbered list keeps its start only where it starts counting (#2273); `.fig` export writes a page's prototype background (#2326); `.fig` export writes list spacing, hanging punctuation and lists, and vertical trim (#2305); `.fig` import and export read and write a boolean group's corner radius and smoothing (#2222); `.jam` import: stickies come in as native board stickies (#1808); `.fig` import scales per-point vector corner radii with the row that supplies their network and keeps different instance scales separate in the network cache (#2097); `.fig` export preserves scaled-instance lengths reset to their unscaled main values, including nested linked-style overrides (#2097); `.fig` import: the layers of an instance scaled with the Scale tool draw at its scale factor, not at their main's lengths (#2091); a color profile per PNG, JPG and WebP export setting (Same as file, sRGB or Display P3), the pixels converted; a `.jam` connector end with an `AUTO` or `CENTER` magnet leaves the side facing the other end, not the side its stale saved point named (#1909); a FigJam elbow connector saved with its path (`connectorControlPoints`) keeps it on import, as a board connector reshaped by hand does, instead of being routed again (#1910); JPG exports take a quality, 1 to 100 with 90 the default, and embed the file's colour profile when it is sRGB too (#2004); a FigJam connector without a saved snapshot took no stroke and was invisible; its line's paint, weight, cap and dashes now come from the file's generated line record (#1807); a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); imported and pasted text finds an installed family under the other names its fonts give it, and with other case and spacing (#1292); `.fig` export writes colour calculations as the colour they show in each mode and leaves out, with a warning, one that resolves to nothing (#1280); `.fig` import budgets four decoded values per compressed byte instead of one, still within 20M–128M, so dense files within that budget open instead of being refused as having too many values (#574); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); every file a command reads whole by path is a regular file within a cap that fits it: documents 16 GiB, placed images 256 MiB, CLI scripts 1 GiB; folders, devices and pipes are refused before anything is read (#1114); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); a FigJam `.jam` file opens as a board (#1342); FigJam `.jam` files open like `.fig` files: File ▸ Open, drag and drop, `file.import` and the command line (#1342); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); SVG import draws each pattern tile once per scale, within the layer budget (#1080); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); offline Penpot 2.x import/export (#1143); `.sketch` import checked against Sketch's renders: master backgrounds, symbol clipping, tints before Sketch 64, mask opacity, bitmap fills, image overrides on shapes, stretching stacks, blur radii, colour adjustments, OKLab gradients, text growth, shape group borders (#1389); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); image member names are checked on read, and REST image placeholders get archive-safe keys (#1086); Android Vector Drawable (XML) export; `.fig` export: files the incumbent imports, with component set properties, and grid track sizes at its field ids; Save and auto-save don't replace changes another app made to the open file (#1330); `.sketch` import, best effort, Sketch 48 and newer; the PNG row names ignore overlapping layers and where include bounding box is offered; the Fonts table's missing-font row describes the Missing fonts window; `.figcraft` carries the file kind (boards); `.fig` import: resized instances and variable modes by asset key; atomic saves; auto-save; SVG export clip of nested frames; SVG/PDF export depth refusal (#208); `.fig` export: instance sizes, variables with modes, shared styles, variable-width strokes; `.fig` export: written files checked by opening them in other software; experimental `.fig` export; export and inspect behaviour suite and fixes; .fig import: editable vector networks and more layer kinds; embedded image colour profiles; `.fig` import, best effort; animated GIF fills and TIFF images; last major: created, formats from the installed Figma's Info.plist and help center, ours from source; REST import keeps slot layers and instances' slot content (#792); REST import reads grid track sizes (#465); `.fig` import fidelity from the community batches, budgets for large files, the import report, a `.fig` copy from Save as, paste from another design app; instance layers' size and resizing and Hug on import (#731, #732)) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-13 · **Change:** minor (`.fig` export writes vector region paints (#2302); `.fig` export writes text on a path (#2323); `.jam` import: shapes with text come in as native board shapes (#1808); `.fig` export writes image adjustments (#2297); `.fig` import: a numbered list keeps its start only where it starts counting (#2273); `.fig` export writes a page's prototype background (#2326); `.fig` export writes list spacing, hanging punctuation and lists, and vertical trim (#2305); `.fig` import and export read and write a boolean group's corner radius and smoothing (#2222); `.jam` import: stickies come in as native board stickies (#1808); `.fig` import scales per-point vector corner radii with the row that supplies their network and keeps different instance scales separate in the network cache (#2097); `.fig` export preserves scaled-instance lengths reset to their unscaled main values, including nested linked-style overrides (#2097); `.fig` import: the layers of an instance scaled with the Scale tool draw at its scale factor, not at their main's lengths (#2091); a color profile per PNG, JPG and WebP export setting (Same as file, sRGB or Display P3), the pixels converted; a `.jam` connector end with an `AUTO` or `CENTER` magnet leaves the side facing the other end, not the side its stale saved point named (#1909); a FigJam elbow connector saved with its path (`connectorControlPoints`) keeps it on import, as a board connector reshaped by hand does, instead of being routed again (#1910); JPG exports take a quality, 1 to 100 with 90 the default, and embed the file's colour profile when it is sRGB too (#2004); a FigJam connector without a saved snapshot took no stroke and was invisible; its line's paint, weight, cap and dashes now come from the file's generated line record (#1807); a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); imported and pasted text finds an installed family under the other names its fonts give it, and with other case and spacing (#1292); `.fig` export writes colour calculations as the colour they show in each mode and leaves out, with a warning, one that resolves to nothing (#1280); `.fig` import budgets four decoded values per compressed byte instead of one, still within 20M–128M, so dense files within that budget open instead of being refused as having too many values (#574); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); every file a command reads whole by path is a regular file within a cap that fits it: documents 16 GiB, placed images 256 MiB, CLI scripts 1 GiB; folders, devices and pipes are refused before anything is read (#1114); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); a FigJam `.jam` file opens as a board (#1342); FigJam `.jam` files open like `.fig` files: File ▸ Open, drag and drop, `file.import` and the command line (#1342); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); SVG import draws each pattern tile once per scale, within the layer budget (#1080); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); offline Penpot 2.x import/export (#1143); `.sketch` import checked against Sketch's renders: master backgrounds, symbol clipping, tints before Sketch 64, mask opacity, bitmap fills, image overrides on shapes, stretching stacks, blur radii, colour adjustments, OKLab gradients, text growth, shape group borders (#1389); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); image member names are checked on read, and REST image placeholders get archive-safe keys (#1086); Android Vector Drawable (XML) export; `.fig` export: files the incumbent imports, with component set properties, and grid track sizes at its field ids; Save and auto-save don't replace changes another app made to the open file (#1330); `.sketch` import, best effort, Sketch 48 and newer; the PNG row names ignore overlapping layers and where include bounding box is offered; the Fonts table's missing-font row describes the Missing fonts window; `.figcraft` carries the file kind (boards); `.fig` import: resized instances and variable modes by asset key; atomic saves; auto-save; SVG export clip of nested frames; SVG/PDF export depth refusal (#208); `.fig` export: instance sizes, variables with modes, shared styles, variable-width strokes; `.fig` export: written files checked by opening them in other software; experimental `.fig` export; export and inspect behaviour suite and fixes; .fig import: editable vector networks and more layer kinds; embedded image colour profiles; `.fig` import, best effort; animated GIF fills and TIFF images; last major: created, formats from the installed Figma's Info.plist and help center, ours from source; REST import keeps slot layers and instances' slot content (#792); REST import reads grid track sizes (#465); `.fig` import fidelity from the community batches, budgets for large files, the import report, a `.fig` copy from Save as, paste from another design app; instance layers' size and resizing and Hug on import (#731, #732)) · **Target:** Figma Design (desktop app 126.10.7) Every format Figma reads or writes, with FigCraft's support. Sources: `Info.plist` of `/Applications/Figma.app` (document types only; nothing inside the bundle's code was read), Figma's @@ -81,8 +81,9 @@ visible and opaque (a page also its background opacity): a reader takes what is draws nothing below a hidden page. The message lists one node change per layer, parents first, each with its GUID, its parent and a position string that orders it among its siblings; vector networks and outlines go in blobs, written once -each. `.fig` export warns and drops vector region paint stacks; import and editing preserve their -source paint coordinates. +each. `.fig` export writes a vector's region paint stacks (each filled area's own paints as an entry of the +network's style table, named by the area's style id); a region's kept paint frame is left out with a +warning; import and editing preserve their source paint coordinates. Scaled instances retain an explicit override when a length is reset to the unscaled main's value, rather than losing it to the field diff. This covers corners, strokes, layout and grid lengths, @@ -93,6 +94,8 @@ scales and empty-style clears; they have not been checked in other software. - **Written:** pages (name, background, prototype background as an opaque colour, for every page); frames, groups, sections, rectangles (as rounded rectangles, with their four radii), ellipses (arcs), polygons, stars, lines, vectors (editable + network blobs with per-point corner radius, handle mirroring, caps and joins, each filled area's own paints, plus the outline of + their filled areas), text, boolean groups, slices; the fill outline of frames and shapes and the network blobs with per-point corner radius, handle mirroring, caps and joins, plus the outline of their filled areas), text, text on a path (the first part of its path, where the text starts and its side), boolean groups, slices; the fill outline of frames and shapes and the stroke outline of plain strokes (a ring around boxes and whole ellipses, the widened path of other @@ -133,7 +136,7 @@ scales and empty-style clears; they have not been checked in other software. - **Left out, with a warning each:** colour calculations that resolve to nothing (an operand missing, or more than 32 variables to read), variable bindings the format has no field for (component properties, arc fields, font weight: written as the values they give), text styles on part of a - text (written as values), variables' publishing, code syntax and inheritance settings, extended + text (written as values), the paint frames of vector regions, variables' publishing, code syntax and inheritance settings, extended collections (written as collections of their own), comments, Developer Mode annotations, statuses, resources, measurements and code links, plugin data, ruler guides, a page's prototype device settings (device, rotation, colour, custom size, responsive), the opacity of a page's prototype background (written opaque), slot properties and slot content, brush @@ -195,6 +198,7 @@ scales and empty-style clears; they have not been checked in other software. | Date | Change | Summary | |---|---|---| +| 2026-11-12 | minor | M6, #2302: the `.fig` export writes the paints of a vector's own regions: each region with paints of its own (an empty list means unfilled) names an entry of the network's style table (`styleOverrideTable[].fillPaints`), equal lists share one entry, and a region without paints writes style 0. The fill outline is still one path with style 0. A region's kept paint frame is still left out, with a narrower warning. The importer already read this; not checked in other software | | 2026-11-12 | minor | M6, #2323: the `.fig` export writes text on a path as the format's own layer kind (`TEXT_PATH`): the first part of its path as a vector network of one open or closed chain with the segment the text starts on marked, the start as that segment's own parameter (`textPathStart.tValue`, found by inverse arc length) and the side as `forward`. Vertical alignment is written as top, which is how text on a path draws. The importer already read all of it; a closed path comes back starting at the marked segment, the same curve and start point. Text with more than one line and paths the format can't hold stay plain text, the parts of a path after the first are left out, and text on a path in an instance but not in its main component (or the other way round) is written as the main has it, each with its own warning. The field numbers come from the schema of a synthetic file saved from Figma's web app. Checked through the importer only, not in other software | | 2026-11-12 | minor | M6, #2297: the `.fig` exporter writes an image paint's adjustments as `paintFilter` (seven fields: exposure, contrast, vibrance from saturation, temperature, tint, highlights, shadows; the tint's sign is flipped, as the importer reads it), and no longer warns about them; the importer already read them. Not checked in other software | | 2026-11-12 | patch | M6, #2273: `.fig` import: a numbered list keeps its start only on the item where it starts counting. Figma writes the start on every line of the list (measured in Figma's web app, 2026-11-12, from a saved .fig: a list started at 5 has `listStartOffset` 4 on all its lines, and after Backspace takes a middle item out of the list, the item after it starts a new list and is written with 0), so reading every line's value restarted the items after a split at the old start. The export is unchanged and a re-import now equals what went in; REST `listStartOffsets` read the same way | diff --git a/docs/gaps.md b/docs/gaps.md index e7cbdb76a..66ac5bb9f 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Where FigCraft falls short of Figma -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-10 · **Change:** minor (gap 13: a boolean group's corner radius (#2222); gap 24: mind maps, first step: a first node with three children on curved branches, laid out again after every edit (`board.mindMap`, `board.mindMapAdd`, #2226); gap 10: library analytics list how many layers and files use each style and variable; the Controller menu names each button as PlayStation and Switch controllers do; gap 6: widgets draw lines and SVG pictures (plugin API 6); gap 7: text reads only the fallback fonts it draws with; a board connector's path can be reshaped by dragging its path handles (#1710); gap 10: library analytics count insertions and show insertions and detachments over time; gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; gap 14: a collection of this file extends, following its edits at once; colour picker review fixes for text undo, fitted sidebars, moving controls and gradient variables; gap 6: plugin widgets have hover styles; gap 7: the browser draws a zoom's full render a band at a time; `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); Arabic draft catalog; gap 7: the browser refines a zoom's preview once the zoom has paused; gap 17: branches in live sessions, branch history entries, the list-merge rows brought up to date; gap 6: plugin widgets take text input and a property menu (plugin API 4); gap 24: board templates and tables; gap 24: a shared timer and voting sessions; gap 24: the board dot grid, connector ends dragged to re-attach, curved connectors; egui/eframe 0.37 verified for gap 18; known gaps from the #1311 review in gaps 4, 14, 15 and 16; gap 16: measurements kept on the canvas, a read-only layers panel in Dev Mode; gap 24: boards and their tail; Dev Mode tail: import lines in layer trees, compare with versions, an inspect-only canvas; gap 5: reviewed Turkish, Czech and Indonesian drafts, the Japanese draft completed; reviewed Russian catalog and integer plurals; `.fig` export: instance sizes, variables with modes, shared styles, variable-width strokes; sharing with a join code; text box sizes measured against documents re-saved by other software; live sessions per document; .fig export checked by opening written files in other software; experimental .fig export; keyboard shortcut parity suite and bindings; Simplified Chinese draft catalog; Latin American Spanish overlay; prototyping tail: gamepad triggers, widgets in prototypes, mode lookups; plugin directory on figcraft-server; Japanese and Korean draft catalogs and CJK UI fonts; plugin widgets and the plugin panel tail; French, German and Brazilian Portuguese draft catalogs; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and edit tail; dev resources links; extended collections tail; branch version history and finer list merges; comments and version history behaviour suite and fixes; canvas navigation, guides and grids behaviour suite and fixes; `.fig` import: editable vector networks, more layer kinds, variable prototype actions; `.fig` import, best effort: gap 1 down to its tail; Windows QA pass: everyday workflows on Windows 11, eight fixes incl. unsaved work kept after a crash or a forced quit; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; localization layer with a draft Spanish catalog; hosting figcraft-server: wss in the desktop app, server releases, deployment guide; plugin panels and settings; canvas fixes: boolean hit testing on the result, group drags, frame outlines and slices; code connect; stretch and scatter brushes, pen pressure; text on a path and pattern fills; team libraries on the server and swap library; branches: create, update from main, review and merge; animated GIF fills and TIFF images; Open recent, outlines for the selection and mask outlines: menu breadth 100%; extended collections, variables import/export, gradient stop and variant bindings: gap 14 down to its tail; the 2026-10-17 landings: `.fig` import fidelity, budgets for large files, the import report, a `.fig` copy from Save as and paste from another design app (gap 1); menus, the Actions palette, editor fixes, Selection colors and smart-selection spacing (gap 4); catalog counts re-measured (gap 5); bounded canvas pan overscan) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-12 · **Change:** minor (gap 1: the `.fig` export writes vector region paints (#2302); gap 13: a boolean group's corner radius (#2222); gap 24: mind maps, first step: a first node with three children on curved branches, laid out again after every edit (`board.mindMap`, `board.mindMapAdd`, #2226); gap 10: library analytics list how many layers and files use each style and variable; the Controller menu names each button as PlayStation and Switch controllers do; gap 6: widgets draw lines and SVG pictures (plugin API 6); gap 7: text reads only the fallback fonts it draws with; a board connector's path can be reshaped by dragging its path handles (#1710); gap 10: library analytics count insertions and show insertions and detachments over time; gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; gap 14: a collection of this file extends, following its edits at once; colour picker review fixes for text undo, fitted sidebars, moving controls and gradient variables; gap 6: plugin widgets have hover styles; gap 7: the browser draws a zoom's full render a band at a time; `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); Arabic draft catalog; gap 7: the browser refines a zoom's preview once the zoom has paused; gap 17: branches in live sessions, branch history entries, the list-merge rows brought up to date; gap 6: plugin widgets take text input and a property menu (plugin API 4); gap 24: board templates and tables; gap 24: a shared timer and voting sessions; gap 24: the board dot grid, connector ends dragged to re-attach, curved connectors; egui/eframe 0.37 verified for gap 18; known gaps from the #1311 review in gaps 4, 14, 15 and 16; gap 16: measurements kept on the canvas, a read-only layers panel in Dev Mode; gap 24: boards and their tail; Dev Mode tail: import lines in layer trees, compare with versions, an inspect-only canvas; gap 5: reviewed Turkish, Czech and Indonesian drafts, the Japanese draft completed; reviewed Russian catalog and integer plurals; `.fig` export: instance sizes, variables with modes, shared styles, variable-width strokes; sharing with a join code; text box sizes measured against documents re-saved by other software; live sessions per document; .fig export checked by opening written files in other software; experimental .fig export; keyboard shortcut parity suite and bindings; Simplified Chinese draft catalog; Latin American Spanish overlay; prototyping tail: gamepad triggers, widgets in prototypes, mode lookups; plugin directory on figcraft-server; Japanese and Korean draft catalogs and CJK UI fonts; plugin widgets and the plugin panel tail; French, German and Brazilian Portuguese draft catalogs; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and edit tail; dev resources links; extended collections tail; branch version history and finer list merges; comments and version history behaviour suite and fixes; canvas navigation, guides and grids behaviour suite and fixes; `.fig` import: editable vector networks, more layer kinds, variable prototype actions; `.fig` import, best effort: gap 1 down to its tail; Windows QA pass: everyday workflows on Windows 11, eight fixes incl. unsaved work kept after a crash or a forced quit; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; localization layer with a draft Spanish catalog; hosting figcraft-server: wss in the desktop app, server releases, deployment guide; plugin panels and settings; canvas fixes: boolean hit testing on the result, group drags, frame outlines and slices; code connect; stretch and scatter brushes, pen pressure; text on a path and pattern fills; team libraries on the server and swap library; branches: create, update from main, review and merge; animated GIF fills and TIFF images; Open recent, outlines for the selection and mask outlines: menu breadth 100%; extended collections, variables import/export, gradient stop and variant bindings: gap 14 down to its tail; the 2026-10-17 landings: `.fig` import fidelity, budgets for large files, the import report, a `.fig` copy from Save as and paste from another design app (gap 1); menus, the Actions palette, editor fixes, Selection colors and smart-selection spacing (gap 4); catalog counts re-measured (gap 5); bounded canvas pan overscan) · **Target:** Figma Design (desktop app 126.10.7) Every known shortfall against Figma, one entry each, ranked by how much it stops a Figma user from doing real work in FigCraft. Agents: pick work from the top unless the owner says otherwise. The @@ -87,8 +87,8 @@ No alpha blockers: the alpha gate in [`roadmap.md`](roadmap.md#alpha-gate) passe layer budgets; the issue sample was checked locally only. Native board metadata and direct `.jam` opening (#1342) remain separate work. - **Landed (2026-10-26):** `.fig` import reads vector-region fill stacks; vector editing and path - operations retain them with their source paint coordinates. `.fig` export still warns and drops - region fills. Evidence: `crates/format/src/fig/tail_tests.rs`, `crates/engine/src/shapebuilder_region_paints_tests.rs`. + operations retain them with their source paint coordinates. `.fig` export writes them since + 2026-11-12 (#2302); a region's kept paint frame is left out, with a warning. Evidence: `crates/format/src/fig/tail_tests.rs`, `crates/engine/src/shapebuilder_region_paints_tests.rs`. - **Fixed (2026-10-29, #1236):** imported text keeps the line breaks the file saved with it (`derivedTextData`), so a font whose advances differ slightly from the file's (another build of the family, a stand-in) no longer wraps a word early or splits one in a narrow box. The @@ -595,6 +595,7 @@ No alpha blockers: the alpha gate in [`roadmap.md`](roadmap.md#alpha-gate) passe | Date | Change | Summary | |---|---|---| +| 2026-11-12 | minor | Gap 1: the `.fig` export writes vector region paints (#2302); the 2026-10-26 "Landed" bullet no longer says the export drops them | | 2026-11-10 | minor | Gap 13: a boolean group's corner radius rounds every sharp corner of its result (#2222); the boolean clause leaves the 2026-10-12 "Left" list | | 2026-11-10 | minor | Gap 24: mind maps, first step (`board.mindMap`, `board.mindMapAdd`; the map lays itself out again after every edit, #2226); the toolbar entry, shortcuts, drag to re-parent and `.jam` import are what is missing of them. | | 2026-11-03 | minor | Traditional Chinese (Taiwan) (`zh-Hant`) draft catalog: 1,975 UI strings, 641 command labels and 31 menu wordings, clean-room from the English source; zh-TW, zh-HK, zh-MO and zh-Hant read it, explicit Hans stays Simplified; Noto Sans CJK TC then Taiwan system faces; no bundled font; native review pending. Numbers unchanged | diff --git a/docs/mcp.md b/docs/mcp.md index 8d03540ba..9b44a0c55 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2084,8 +2084,8 @@ turned off 0°. `node.set {pointCount}` keeps stars to 3–60 points; `miterAngle` (degrees, the Design panel's Miter angle) sets the miter limit (`limit = 1 / sin(angle / 2)`); `get_node` reports a join other than miter (`strokeJoin`) or a miter angle other than the default ~28.96° (`miterAngle`). -- **Select**: `select.layersAt {x, y}` lists every layer under a page point, front-most first with its - depth (the context menu's Select layer); `select.set`, `select.children` / `select.parent` (Enter +- **Select**: `select.layersAt {x, y}` lists every layer under a page point, locked ones too, front-most first with its + depth and a `locked` flag (true when the layer or an ancestor is locked; the context menu's Select layer); `select.set`, `select.children` / `select.parent` (Enter / Shift+Enter), `select.next` / `select.previous` (Tab / Shift+Tab). With `pointer`, `cmd: true` clicks select the nested layer, `cmd` drags from empty canvas select the nested layers they touch, and `shift` drags toggle what they touch. A press on the background of a top-level frame with diff --git a/docs/ui-parity.md b/docs/ui-parity.md index dc1ab7a80..51a2cca4d 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI and interaction parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-10 · **Change:** minor (Zoom to selection leaves a 40 pt margin and clears the bottom toolbar, measured in Figma's web app; M1: Paste over selection puts the pasted layers just above the selected layer; drag modifiers compared in Figma's web app (2026-11-08): Shift locks a move to the dominant axis, Alt copies, Shift keeps a resize's ratio, Alt keeps its centre, all read afresh on every move, and FigCraft matches (Ctrl/Cmd not measurable); a mirror mode (angle, or angle and length) on a sharp point turns it smooth, as in Figma (#2110); M8: Tab while renaming the last layer wraps to the first row, measured in Figma's web app on 2026-11-12; the text caret takes the text's solid fill colour (#2156); the Rotation field shows and sets the rotation on the page, in frames and groups, through node.set absoluteRotation (#2196); the eyedropper picks a magnified image's pixel under the pointer, not a blend with its neighbours (#2189); Selection colors shows from one distinct colour when a selected layer has children, and from two otherwise, measured in Figma's web app on 2026-11-09 on a frame, a group and plain rectangles; the crosshair of the shape and Text tools is drawn dark with a white edge, so it shows on a white frame whatever the system's pointer style (#2198); a boolean group takes a corner radius (and smoothing) that rounds every sharp corner of its result (#2222); the Point section's X and Y in vector edit mode show Mixed and set every selected point of the layer being edited, as in Figma; Preferences ▸ Invert zoom direction reverses wheel zoom, pinch unchanged (#2145); Shift while rotating lands on absolute multiples of 15°, measured in Figma; Flatten bakes a vector's point corner radius into its path (#2195); a click on a fill, stroke or effect row's grip or background highlights it, Cmd/Ctrl+C copies that paint or effect and Cmd/Ctrl+V pastes it onto the selected layers, as the help center's Copy and paste properties between layers says (#1494); wrap style per paragraph and in text styles (#1827); the Annotation tool (Shift+T, `tool.annotation {id?}`): with a layer selected (or an `id`) it asks the UI for that layer's note at once, and in the tool a press on a layer selects it and asks for its note, a press on empty canvas does nothing; the marquee follows Figma's measured rules: a partly covered frame or section gives the layers in it the marquee touches, a rotated shape is touched by its outline, a drag from inside a frame selects that frame only when the marquee also takes another top-level frame (then whole) (`marquee_behaviour_tests`); copy, cut and paste in vector edit mode act on the selected points and segments (#1875); M8, #2146: K focuses the Scale tool's factor field with its text selected, so K, 2, Enter scales the selection by two about the panel's origin (FigCraft's starts at the top left; Figma's grid starts at the centre, left for a follow-up because the origin also sets where a handle drag pivots, which is not measured) in one undo step, after which the tool returns to Move with the selection kept; Escape in the field closes it with the tool back on Move and nothing changed (measured in Figma's web app, 2026-11-09; `pressing_k_focuses_the_scale_field_with_its_text_selected`, `k_two_enter_scales_the_selection_by_two`, `escape_in_the_scale_field_closes_it_and_changes_nothing`); the main menu and its submenus stay inside the window, moving up to fit and scrolling when taller (#2217); locked layers ignore the arrow keys and a locked parent's children can't be locked on their own (#1560); the left rail's and tab strip's icons are larger, 20 pt (#553); pick select: Tab while the keyboard selection box shows (or the chord again) puts a pink outline on a layer and the keys walk the layer tree from it, as Accessibility at Figma says (#1836); scrubbing a field faster or slower by the pointer's height, with a notice of the speed, as the help center's Scrub fields says (#1837); component rows in the Layers panel at AA contrast in the theme's component tint, with the rows inside a selected component in a tone of its row (#1903); Cmd/Ctrl-click on a padding field sets all four sides with the value typed, a documented auto layout shortcut; a fill per region of a vector: with regions selected in edit mode, the Fill section and the fill commands edit those regions' own fills, as Edit vector layers says (#1875); the Fill section of a text whose characters were coloured differently while editing shows mixed content, characters that all share fills the layer doesn't have show those, and a layer-level fill edit reaches every character (#1856); a number field scrubs when dragged with Alt held, as the help center's scrub section says, not only by its label; reuse visible layer selection roots (M8); ; with a shape or frame tool chosen and nothing selected, the arrows show a placement crosshair in the middle of the view and move it, and Enter places there, as Accessibility at Figma says (#1839); text direction per paragraph: Text ▸ Text direction forces a paragraph left to right or right to left, as Add right-to-left text says (#1830), with `text.direction`, `node.set textDirection`, the Type settings control once a right-to-left script is in the text, inspect, the CSS `direction` and the `.fig` lines' `sourceDirectionality`; the boolean operation menu in the Design panel leads each entry with an original icon drawn in code, a filled preview of the result (#2003); a press on the open gradient's handles or stops on the canvas keeps the colour picker open through the drag, as its own control (#1852); a click with the Bend tool on a sharp point curves it, its handles along the line between its neighbours, as Edit vector layers says (#1875); wrap style: Auto, Balance and Pretty on a text layer decide where its lines break, as Explore text properties says (#1827), with the Type settings control, `text.wrapStyle`, `node.set wrapStyle`, inspect and the CSS `text-wrap`; Backspace or Delete at the start of a list item keeps the item's indentation level, as the lists article says; max lines on auto-width text keep it auto width, hugging that many lines, as the text properties article says; superscript and subscript are synthesised where the font has no glyphs for them, from the standard glyphs shrunk and shifted by the font's OS/2 metrics, and a run mixing available and unavailable glyphs is synthesised whole, as Explore text properties says (#1828); Alt+Enter while editing text opens the link at the caret, as the accessibility page documents; Minimize, by its shortcut or the button by the file name, collapses the navigation bar and both sidebars as the help center says, with the right sidebar back while something is selected (#1835); the interface size keys of the help center's accessibility page: Cmd/Ctrl+Shift+Alt with =, - and 0 step the interface through the Preferences sizes and back to the system's size; Cmd/Ctrl+Alt+arrows rotate the selection a degree at a time, 15 with Shift, as the help center's accessibility page says; they resized before; the Layers panel answers Ctrl+1 as well as Alt+1 on Windows and Linux, the two keys the help center gives it; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the keyboard's Menu key opens the context menu, as Shift+F10 does; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; sidebar number and text fields keep their text vertically centered when focused, including typography spacing; with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); colour picker review fixes for text undo, fitted sidebars, moving controls and gradient variables; Corner smoothing: an original icon and the shared number-field drag gesture, preserving fractional baselines; guides snap to layers when dragged; Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); the Design panel's sections on one grid — 16 / 8 margins, 88 + 8 + 88 + 8 + 24 columns, 24 pt rows, 4 pt between a row's buttons (#858); the toolbar on one 32 pt grid, without its Resources button (#1210); colour picker LCH and OKLCH models; an XML (Android Vector Drawable) export format; Context menus: the Menu key reaches egui 0.37 but is unbound (row done → partial); the Text on a path tool; board tool keys pinned; community fixes: the text box by dragging, the font picker keys, the pen path on leaving Design, a still canvas in vector edit mode, a scrolling pages list, colour emoji, readable new text in frames, system theme on first run; the Small caps sample in Type settings drawn from capitals; recent files as cards; vector edit mode: hovering, hatching, selecting and dragging filled regions; home screen: Templates tab, first-run templates and Getting started tips; number fields: scrub rates, arrow steps, arithmetic with brackets, relative edits of mixed values; outline mode's hidden layers and object bounds; Hide when publishing; cursors per tool and modifier; panel widths; dark pages for files made in the dark theme; drag threshold and double-clicks into text in groups; rotation origin on Alt+R and placing with Enter: no documented shortcut missing; keyboard shortcut parity suite and bindings; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and the vector edit tail; canvas navigation, guides and grids behaviour suite and fixes; shapes and vector behaviour suite and fixes; paint and effects behaviour suite and fixes; frames, groups, sections and masks behaviour suite and fixes; layers panel keyboard: F2 rename, Shift+F10 context menu, F8 box selection; selection and transform behaviour suite and fixes; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; boolean hit testing on the result, group drags, frame outlines and slices; outlines for the selection, mask outlines; arc fields, live boolean editing, shape builder on strokes, one-sided widths; fields select their text on focus; Typography spacing icons support scrubbing (#373); CSS colour names in hex fields; a rename selects the whole name, so typing replaces it; Escape or Enter after a pen path stays on the same vector (#760); IME composition kept on through idle frames of a text edit, candidates at the caret (#747); Selection colors for mixed selections and smart-selection spacing (#753); submenus with a hover delay and a safe triangle; the Actions palette's tabs, ranked search, highlight and recents; menu items that ask for a value; editor fixes from the community batches) · **Target:** Figma Design UI3 (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-10 · **Change:** minor (M8: a double-click on a layer's icon zooms to it instead of renaming, measured in Figma's web app on 2026-11-12; Tidy up keeps the order and sizes and evens the gaps, as measured in Figma's web app on 2026-11-12, rounds the gap half up, tidies overlapping rows and packs a grid along its longer axis, and is greyed out for fewer than three layers, a diagonal and an irregular layout (M8); after Crop is chosen in the image fill's colour picker, a drag on the image crops it instead of moving the layer, and no internal gesture message shows (#2307); Align is disabled for a layer in an auto layout frame's flow, as measured in Figma's web app on 2026-11-12, with a tip saying the frame places it; Select layer lists locked layers with a padlock and selects them, and shows only with more than one layer under the pointer (#1560); M8: Scale tool handle drags pivot on the opposite handle whatever the origin, and the origin starts at the centre (measured in Figma's web app, 2026-11-09); M8: a selected polygon or star has a Count handle on the canvas, on its first point clockwise from the top; Zoom to selection leaves a 40 pt margin and clears the bottom toolbar, measured in Figma's web app; M1: Paste over selection puts the pasted layers just above the selected layer; drag modifiers compared in Figma's web app (2026-11-08): Shift locks a move to the dominant axis, Alt copies, Shift keeps a resize's ratio, Alt keeps its centre, all read afresh on every move, and FigCraft matches (Ctrl/Cmd not measurable); a mirror mode (angle, or angle and length) on a sharp point turns it smooth, as in Figma (#2110); M8: Tab while renaming the last layer wraps to the first row, measured in Figma's web app on 2026-11-12; the text caret takes the text's solid fill colour (#2156); the Rotation field shows and sets the rotation on the page, in frames and groups, through node.set absoluteRotation (#2196); the eyedropper picks a magnified image's pixel under the pointer, not a blend with its neighbours (#2189); Selection colors shows from one distinct colour when a selected layer has children, and from two otherwise, measured in Figma's web app on 2026-11-09 on a frame, a group and plain rectangles; the crosshair of the shape and Text tools is drawn dark with a white edge, so it shows on a white frame whatever the system's pointer style (#2198); a boolean group takes a corner radius (and smoothing) that rounds every sharp corner of its result (#2222); the Point section's X and Y in vector edit mode show Mixed and set every selected point of the layer being edited, as in Figma; Preferences ▸ Invert zoom direction reverses wheel zoom, pinch unchanged (#2145); Shift while rotating lands on absolute multiples of 15°, measured in Figma; Flatten bakes a vector's point corner radius into its path (#2195); a click on a fill, stroke or effect row's grip or background highlights it, Cmd/Ctrl+C copies that paint or effect and Cmd/Ctrl+V pastes it onto the selected layers, as the help center's Copy and paste properties between layers says (#1494); wrap style per paragraph and in text styles (#1827); the Annotation tool (Shift+T, `tool.annotation {id?}`): with a layer selected (or an `id`) it asks the UI for that layer's note at once, and in the tool a press on a layer selects it and asks for its note, a press on empty canvas does nothing; the marquee follows Figma's measured rules: a partly covered frame or section gives the layers in it the marquee touches, a rotated shape is touched by its outline, a drag from inside a frame selects that frame only when the marquee also takes another top-level frame (then whole) (`marquee_behaviour_tests`); copy, cut and paste in vector edit mode act on the selected points and segments (#1875); M8, #2146: K focuses the Scale tool's factor field with its text selected, so K, 2, Enter scales the selection by two about the panel's origin (FigCraft's starts at the top left; Figma's grid starts at the centre, left for a follow-up because the origin also sets where a handle drag pivots, which is not measured) in one undo step, after which the tool returns to Move with the selection kept; Escape in the field closes it with the tool back on Move and nothing changed (measured in Figma's web app, 2026-11-09; `pressing_k_focuses_the_scale_field_with_its_text_selected`, `k_two_enter_scales_the_selection_by_two`, `escape_in_the_scale_field_closes_it_and_changes_nothing`); the main menu and its submenus stay inside the window, moving up to fit and scrolling when taller (#2217); locked layers ignore the arrow keys and a locked parent's children can't be locked on their own (#1560); the left rail's and tab strip's icons are larger, 20 pt (#553); pick select: Tab while the keyboard selection box shows (or the chord again) puts a pink outline on a layer and the keys walk the layer tree from it, as Accessibility at Figma says (#1836); scrubbing a field faster or slower by the pointer's height, with a notice of the speed, as the help center's Scrub fields says (#1837); component rows in the Layers panel at AA contrast in the theme's component tint, with the rows inside a selected component in a tone of its row (#1903); Cmd/Ctrl-click on a padding field sets all four sides with the value typed, a documented auto layout shortcut; a fill per region of a vector: with regions selected in edit mode, the Fill section and the fill commands edit those regions' own fills, as Edit vector layers says (#1875); the Fill section of a text whose characters were coloured differently while editing shows mixed content, characters that all share fills the layer doesn't have show those, and a layer-level fill edit reaches every character (#1856); a number field scrubs when dragged with Alt held, as the help center's scrub section says, not only by its label; reuse visible layer selection roots (M8); ; with a shape or frame tool chosen and nothing selected, the arrows show a placement crosshair in the middle of the view and move it, and Enter places there, as Accessibility at Figma says (#1839); text direction per paragraph: Text ▸ Text direction forces a paragraph left to right or right to left, as Add right-to-left text says (#1830), with `text.direction`, `node.set textDirection`, the Type settings control once a right-to-left script is in the text, inspect, the CSS `direction` and the `.fig` lines' `sourceDirectionality`; the boolean operation menu in the Design panel leads each entry with an original icon drawn in code, a filled preview of the result (#2003); a press on the open gradient's handles or stops on the canvas keeps the colour picker open through the drag, as its own control (#1852); a click with the Bend tool on a sharp point curves it, its handles along the line between its neighbours, as Edit vector layers says (#1875); wrap style: Auto, Balance and Pretty on a text layer decide where its lines break, as Explore text properties says (#1827), with the Type settings control, `text.wrapStyle`, `node.set wrapStyle`, inspect and the CSS `text-wrap`; Backspace or Delete at the start of a list item keeps the item's indentation level, as the lists article says; max lines on auto-width text keep it auto width, hugging that many lines, as the text properties article says; superscript and subscript are synthesised where the font has no glyphs for them, from the standard glyphs shrunk and shifted by the font's OS/2 metrics, and a run mixing available and unavailable glyphs is synthesised whole, as Explore text properties says (#1828); Alt+Enter while editing text opens the link at the caret, as the accessibility page documents; Minimize, by its shortcut or the button by the file name, collapses the navigation bar and both sidebars as the help center says, with the right sidebar back while something is selected (#1835); the interface size keys of the help center's accessibility page: Cmd/Ctrl+Shift+Alt with =, - and 0 step the interface through the Preferences sizes and back to the system's size; Cmd/Ctrl+Alt+arrows rotate the selection a degree at a time, 15 with Shift, as the help center's accessibility page says; they resized before; the Layers panel answers Ctrl+1 as well as Alt+1 on Windows and Linux, the two keys the help center gives it; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the keyboard's Menu key opens the context menu, as Shift+F10 does; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; sidebar number and text fields keep their text vertically centered when focused, including typography spacing; with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); colour picker review fixes for text undo, fitted sidebars, moving controls and gradient variables; Corner smoothing: an original icon and the shared number-field drag gesture, preserving fractional baselines; guides snap to layers when dragged; Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); the Design panel's sections on one grid — 16 / 8 margins, 88 + 8 + 88 + 8 + 24 columns, 24 pt rows, 4 pt between a row's buttons (#858); the toolbar on one 32 pt grid, without its Resources button (#1210); colour picker LCH and OKLCH models; an XML (Android Vector Drawable) export format; Context menus: the Menu key reaches egui 0.37 but is unbound (row done → partial); the Text on a path tool; board tool keys pinned; community fixes: the text box by dragging, the font picker keys, the pen path on leaving Design, a still canvas in vector edit mode, a scrolling pages list, colour emoji, readable new text in frames, system theme on first run; the Small caps sample in Type settings drawn from capitals; recent files as cards; vector edit mode: hovering, hatching, selecting and dragging filled regions; home screen: Templates tab, first-run templates and Getting started tips; number fields: scrub rates, arrow steps, arithmetic with brackets, relative edits of mixed values; outline mode's hidden layers and object bounds; Hide when publishing; cursors per tool and modifier; panel widths; dark pages for files made in the dark theme; drag threshold and double-clicks into text in groups; rotation origin on Alt+R and placing with Enter: no documented shortcut missing; keyboard shortcut parity suite and bindings; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and the vector edit tail; canvas navigation, guides and grids behaviour suite and fixes; shapes and vector behaviour suite and fixes; paint and effects behaviour suite and fixes; frames, groups, sections and masks behaviour suite and fixes; layers panel keyboard: F2 rename, Shift+F10 context menu, F8 box selection; selection and transform behaviour suite and fixes; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; boolean hit testing on the result, group drags, frame outlines and slices; outlines for the selection, mask outlines; arc fields, live boolean editing, shape builder on strokes, one-sided widths; fields select their text on focus; Typography spacing icons support scrubbing (#373); CSS colour names in hex fields; a rename selects the whole name, so typing replaces it; Escape or Enter after a pen path stays on the same vector (#760); IME composition kept on through idle frames of a text edit, candidates at the caret (#747); Selection colors for mixed selections and smart-selection spacing (#753); submenus with a hover delay and a safe triangle; the Actions palette's tabs, ranked search, highlight and recents; menu items that ask for a value; editor fixes from the community batches) · **Target:** Figma Design UI3 (desktop app 126.10.7) Fine canvas control is what Figma users feel first: handles, snapping, nudging, modifier keys, drag behaviour, numeric precision. This checklist covers the tools, gestures and panels. Status: @@ -49,7 +49,7 @@ interaction feel only partly compared: the interactions measured so far, case by | Expand and collapse: Alt-click opens or closes everything inside; Collapse layers (Alt+L) keeps the way to the selection open | done | Alt-click pinned (the documentation is silent) | | Drag to reorder and into frames, groups and auto layout: insertion line, spring-loaded open, several layers together, Escape cancels | done | several layers dropped together land together (they split apart before); instances and a layer's own children refuse drops | | Eye and padlock: click, or drag across rows to set several in one step; layers in a locked frame show a faint padlock | done | the toggles no longer vanish under the pointer (clicks on them could miss) (a child's padlock can't be toggled while its parent is locked) | -| Rename: double click, F2 / Cmd+R, Tab to the next row; several layers open Rename layers (match, regular expressions, current name and number codes, start value, preview) | done | numbered in stacking order, pinned; Tab on the last row wraps to the first row's rename, measured in Figma's web app on 2026-11-12 (`tab_on_the_last_row_commits_and_wraps_to_the_first`); Shift+Tab on the first row ends the rename (not measured); Tab and Shift+Tab move only the rename, the selection stays on the layer first renamed, measured in Figma's web app on 2026-11-12 (`tab_while_renaming_leaves_the_selection_on_the_first_layer`) | +| Rename: double click, F2 / Cmd+R, Tab to the next row; several layers open Rename layers (match, regular expressions, current name and number codes, start value, preview) | done | numbered in stacking order, pinned; Tab on the last row wraps to the first row's rename, measured in Figma's web app on 2026-11-12 (`tab_on_the_last_row_commits_and_wraps_to_the_first`); Shift+Tab on the first row ends the rename (not measured); Tab and Shift+Tab move only the rename, the selection stays on the layer first renamed, measured in Figma's web app on 2026-11-12 (`tab_while_renaming_leaves_the_selection_on_the_first_layer`); a double-click on a row's icon zooms to the layer (selecting it first) and renames nothing, while a double-click on the name or elsewhere on the row still renames, measured in Figma's web app on 2026-11-12 (`a_double_click_on_a_layers_icon_zooms_to_it_instead_of_renaming`) | | Find layers (filter by name) | done | not covered by the documentation | | Pages: add, rename, drag to reorder, duplicate ("Copy of"), delete, dividers (a blank page named with a hyphen) | done | the line between Pages and Layers drags to size the pages list, kept in the preferences; a long list scrolls in its own area and a page dropped outside the visible list stays put (#272) (`layers_behaviour_tests`) | | Assets panel: folders from page, frames and slash names (fold away), search, thumbnails, drag onto the canvas or into frames and auto layout, Alt-drop swap, enabled libraries | done | Shift+I (Quick insert), Alt+2 and View ▸ Panels ▸ Assets open it; the toolbar's Resources button was removed (the left rail's Assets tab and those shortcuts are the ways in) | @@ -61,7 +61,7 @@ interaction feel only partly compared: the interactions measured so far, case by |---|---|---| | Click, Shift-click, marquee, Shift-marquee toggle | done | Shift-drag on a selected layer moves the selection, kept to the dominant axis with no 45° snap (#498; `shift_drag_moves_the_selection`; measured in Figma's web app, 2026-11-08); a marquee selects the top-level layers it touches, by the box and a rotated shape by its outline (rectangle and ellipse measured, the other shapes by the same code); a partly covered top-level frame or section gives the layers in it the marquee touches, an enclosed one is selected itself, an empty frame on touch; a drag from a frame's background selects that frame only when the marquee also takes another top-level frame (then whole), and also takes what it touches outside it; selecting a frame whole keeps the marquee at the top level (a partly covered frame then comes whole too); locked and hidden layers are skipped (`marquee_behaviour_tests`, `selection_behaviour_tests`; measured in Figma's web app, 2026-11-11; Shift and Cmd/Ctrl marquees not measured) (a locked layer selected from the panel ignores the arrow keys and the nudge commands; its properties still edit; measured in Figma's web app, 2026-11-10) | | Deep select (Cmd/Ctrl-click, Cmd/Ctrl-marquee) | done | | -| Select layer menu (every layer under the click) | done | | +| Select layer menu (every layer under the click) | done | shown only with more than one layer under the pointer; locked layers are listed with a padlock in the leading column and are selectable there, as Lock and unlock layers' note says (measured in Figma's web app, 2026-11-10; the "more than one layer" gate was measured on a single locked layer only) (`select_layer_marks_locked_layers_with_a_padlock_and_picks_them`, `select_layer_needs_more_than_one_layer_under_the_pointer`) | | Escape with layers selected | done | clears the selection at once, whatever the nesting; it never selects the parent. Measured in the Figma web app (2026-11-08) with a rectangle in a group in a frame, selected from the canvas (a double-click into the group), from the Layers panel, and after Tab moved the selection to its sibling: one Escape selects nothing, a second leaves nothing selected. Escape still leaves text and vector editing, ends gestures and the pen first, and ends the focus view once nothing or the focused frame is selected (`selection_behaviour_tests`, `devfocus_tests`) | | Enter / Shift+Enter (children / parent), Tab / Shift+Tab (siblings) | done | Tab renames the next layer while renaming | | Resize handles: Shift keeps proportions, Alt from centre, constraints-aware | done | Alt shrinks too; past an edge flips (several layers mirror); groups and mixed rotations scale each layer along its own axes, keeping rotation and flip (no skew: children turned off a right angle are approximate); Cmd/Ctrl ignores a frame's constraints (`transform_behaviour_tests`); Shift keeps the ratio (a corner by the axis dragged most, an edge scaling the other axis about the opposite edge's middle), Alt keeps the centre, Shift+Alt does both, each read afresh on every move (`handle_drags_resize_by_the_documented_rules`; measured in Figma's web app, 2026-11-08; Ctrl/Cmd while dragging not measurable) | @@ -69,10 +69,11 @@ interaction feel only partly compared: the interactions measured so far, case by | Rotate just outside a corner; Shift in 15° steps | done | rotated handle box when layers share a rotation; Shift lands the rotation on multiples of 15° (measured in Figma: a layer at 7° or -4.27° ends at 15°), not 15° steps from where the drag began; layers with different rotations step the turn from 0 | | Flip, rotate 90° | done | | | Rotation origin (Alt+R) | done | a handle at the selection's centre to drag (snaps to the box's corners, edge middles and centre), double-click puts it back, Escape or Alt+R hides it; the corner handles, the rotation field, Rotate 90°/180° and `transform.rotate` turn about it; it follows the layers and lasts as long as the selection, not saved (the documentation doesn't say; pinned) | +| Align and Distribute (Design panel and shortcuts) | done | single and multi-layer Align and Distribute were measured in Figma's web app on 2026-11-12 and match: one layer aligns to its frame, several to their combined bounds, Distribute spaces three or more. Align is disabled for a child in an auto layout frame's flow (Alt+A and Alt+S do nothing, the frame is untouched), as measured; the panel's tip says the frame places the layer, and an absolutely positioned child still aligns to its frame (not measured, so today's behaviour is kept). Tidy up was measured to differ (Figma keeps the order and sizes and evens one gap per axis): not yet. Tests: `align_is_unavailable_for_a_child_in_an_auto_layout_flow`, `an_absolute_child_of_an_auto_layout_frame_still_aligns_to_it`, `the_align_buttons_are_off_for_a_layer_in_an_auto_layout_flow` | | Enter with a shape or frame tool chosen | done | places what a click makes (100×100, lines 100 long, sections 400×300) in the middle of the view, selected (`tool.place`); from the toolbar, Enter on the chosen tool. With nothing selected, the arrows first show a crosshair in the middle of the view and then move it by the nudge amounts (`tool.crosshair`; Shift the large one), and Enter places there; Escape or a tool change takes it away ("Use the arrow keys to activate the crosshair cursor. It will appear in the middle of the viewport indicating where the new object will be placed", Accessibility at Figma; #1839) | | Alt-drag duplicate | done | the copy snaps to the layer it came from too (edges, centres, equal spacing); Duplicate (Cmd+D) then repeats the copy's offset, also after a Duplicate whose copy was moved, as long as the copies stay selected (the documentation doesn't say; pinned from community answers); Alt going down or up mid-drag turns the move into a copy or back to the original, with Shift a copy kept to one axis (`alt_pressed_during_a_drag_turns_the_move_into_a_copy`, `alt_shift_drag_on_a_selected_layer_duplicates_it`; measured in Figma's web app, 2026-11-08) | | Drag threshold; double-click into groups and text | done | a press moves or resizes only once the pointer has travelled 3 px on screen, so a click or double-click made with an unsteady hand drags nothing; a double-click goes one level into a group and the next one edits the text under it, wherever on the text it lands, with all of it selected (a double-click in the text being edited selects the word) (`double_click_tests`); Enter on a selected text does the same (all of it selected, typing replaces it) and Escape leaves editing with the layer still selected (`text_enter_tests`) | -| Scale tool (K): handles about an anchor, live factor, panel | done | Pressing K opens the Scale section with its factor field focused and its text selected; typing 2 (or 2x, 1.5) then Enter scales the selection by it about the panel's origin (FigCraft's starts at the top left; Figma's grid starts at the centre, left for a follow-up because the origin also sets where a handle drag pivots, which is not measured), as one undo step, then closes the section and returns to Move with the selection kept; Escape in the field closes it, back to Move, nothing changed. Measured in Figma's web app, 2026-11-09. Tests: `pressing_k_focuses_the_scale_field_with_its_text_selected`, `k_two_enter_scales_the_selection_by_two`, `escape_in_the_scale_field_closes_it_and_changes_nothing`. | +| Scale tool (K): handles about the opposite handle, live factor, panel | done | Dragging a handle ignores the origin grid and pivots on the opposite handle's point (the opposite corner, or the opposite edge's middle for an edge, which scales both ways), with Alt on the centre; the origin grid (`tool.scaleAnchor`) starts at the centre and sets only what the Scale field and the W and H fields keep fixed (W and H with a non-centre origin are unmeasured). Measured in Figma's web app, 2026-11-09. Tests: `a_scale_handle_drag_pivots_on_the_opposite_handle_whatever_the_origin`, `the_scale_origin_starts_at_the_centre`. Pressing K opens the Scale section with its factor field focused and its text selected; typing 2 (or 2x, 1.5) then Enter scales the selection by it about the panel's origin, which starts at the centre, as one undo step, then closes the section and returns to Move with the selection kept; Escape in the field closes it, back to Move, nothing changed. Measured in Figma's web app, 2026-11-09. Tests: `pressing_k_focuses_the_scale_field_with_its_text_selected`, `k_two_enter_scales_the_selection_by_two`, `escape_in_the_scale_field_closes_it_and_changes_nothing`. | | Nudge 1 / Shift 10 (preference), Cmd+arrows resize | done | arrows reorder auto layout children | | Smart guides: edges, centres, equal spacing (between two layers or continuing a row's gap, labelled), spacing labels, parent, layout grid, ruler guides | done | red, `snap.rs`; a guide dragged out of a ruler or moved snaps to layer edges and centres too (Snap to Objects; Cmd/Ctrl suspends), on its own axis only; page guides see the page's top-level layers, frame guides the frame's box, layout grids and every layer in it, along a rotated frame's own axes; the object snap threshold is 4.5 screen pixels, measured against Figma (snapped at a gap of 4.4 screen px, not at 4.6, at 100% and 200% zoom, 2026-11-08; the equal-spacing snap shares it), but the ruler-guide and rotation-origin thresholds (5 px), the red guide's look and snapping with Snap to pixel grid off are not yet compared with Figma's (`guide_snap_tests`, `transform_behaviour_tests`) | | Ctrl to suspend snapping while dragging (macOS) | done | Control on macOS (Cmd keeps working), Ctrl elsewhere; moving, resizing and drawing | @@ -83,6 +84,7 @@ interaction feel only partly compared: the interactions measured so far, case by | Locked layers | done | selectable from the layers panel; no handles, not dragged with the rest of a selection | | Edit ▸ Set default properties: new layers take the selected layer's properties | done | from a shape (any layer but text): new rectangles, ellipses, polygons and stars drawn or clicked with their tools take its fills, strokes and their settings, effects, opacity, blend and corners; from a text layer: new text from the Text tool takes its fills and font (#2028). Silent in the help center on frames, lines and arrows: they keep their own look, as do layers made by commands; the defaults last for the session | | Smart selection spacing | partial | with layers in a row, a column or an aligned grid selected, the Layout section shows horizontal and vertical spacing ("Mixed" until set; typed, scrubbed, fractional and negative) and pink handles in the gaps on the canvas drag them, one undo step, Escape cancels (`arrange.spacing`; sizes, parents and offsets within each track kept; at most 2,000 layers; flow children, locked layers and layers inside instances left out). A ring at each layer's centre drags it to another place in a regular row, column or complete top-left-aligned grid: the others close up and make room around it with the gaps kept, and with Cmd/Ctrl held the two layers swap places instead, previewed live while dragging (`selection_reorder_tests`; no ring on a layer under 16 px on screen). Not covered: reordering irregular grids, and several marked layers moved together. Checked by its author on macOS and in the app on Windows (#402) | +| Tidy up | partial | measured in Figma's web app on 2026-11-12 (a row, a column, a 2 x 3 grid of unequal sizes and its transpose, and many runs on the gap, the unavailable cases among them): the order and the sizes are kept; in a row or a column the first layer also stays and the other axis is untouched (a grid can move a layer on both axes, as below). A row (one group of layers whose Y ranges overlap, side by side) evens its horizontal gaps and a column its vertical gaps to one gap: the most common existing gap (the smaller of two equally common ones), else the mean rounded to a whole number, half up (30, 40, 30 gives 30; 80, 20, 45 gives 48; 10, 10, 50, 90 gives 10; 10, 25 gives 18; 10, 25, 30 gives 22). Layers of a row may overlap along X, and overlapping layers in a chain count as a row (the first and third needn't touch): the negative gap counts in the mean (50 px squares at X 0, 60, 105, 170, gaps 10, -5, 15, give X 0, 57, 114, 171; squares at X 0, 40, 80, 150 give 0, 40, 80, 120). Measured in Figma's web app on 2026-11-13: a negative gap is raised so no layer reaches the one two places before it, floor(-w / 2) + 1 for the narrowest interior layer's width w, so 10, 20 and 30 wide interior layers among 100s give -4, -9 and -14 (X 0, 96, 102, 198, 294, 390 for widths 100, 10, 100 x4), while six layers 100 wide keep the most common gap, -40; only those widths were measured, and an explicit `spacing` is not raised. A grid (two or more rows and columns, one layer in every cell) is packed along the axis with more groups: a column is as wide as its widest layer around the middle of where its layers were, the first column stays, each layer is centred in its column to a whole pixel with Snap to pixel grid on, and every column is stacked from the selection's top; a grid with more rows than columns is the mirror image (centred rows, laid out left to right). The vertical gap reads 51 or 52 in Figma's own runs (mean 51.67), so FigCraft's positions along a stack can differ by a pixel there. Unavailable, as measured, for fewer than three layers, for layers that all overlap each other (one row and one column), for a diagonal and for an irregular layout: a greyed-out row with a tip in the Design panel's menu, the command moving nothing and adding no undo step. Not measured, FigCraft's choices: a 2 x 2 grid packed as columns; layers in an auto layout flow being unavailable (the frame places them; the measurement could not tell this from an irregular layout); the 2,000 layer cap; rotated layers counting by their box; gaps a pixel apart being different gaps; an explicit `spacing` setting the gap and taking two layers; no rounding with Snap to pixel grid off. Tests: tidy_tests | | Selection colors | partial | the Design panel shows the section from two paint groups (paints sharing a style, a variable and a value count as one group), or from one when a selected layer has children (a frame, group, component or instance), and lists their solid and gradient paints (children and text ranges included; hidden paints, masks, images, patterns and boolean operands left out; styles and variables listed apart): editing a colour changes every matching fill and stroke in one undo step, a row selects the layers that use it or applies a color style or color variable of the document, and a row linked to a style or variable detaches it, keeping the color (`selection.colors`, `selection.setPaint`, `selection.applyColorStyle`, `selection.bindColorVariable`, `selection.detachColor`, `selection.selectColor`). A row's Styles menu also offers enabled libraries' published color styles and Create style (`selection.createColorStyle`); no library variables and no new variable from a row (#403) | | Keyboard box selection | done | Alt+Space on macOS, Ctrl+Space on Windows and Linux, or F8 (`select.area`): a box around the selection or in the middle of the view; arrows move it, Cmd/Ctrl+arrows or Shift+arrows size it (Shift with Cmd/Ctrl: farther), Enter selects like a marquee (Shift+Enter toggles, Cmd/Ctrl+Enter nested), Escape closes; Tab while the box shows, or the chord again, switches to pick select: a pink outline on the first selected layer (the page's top layer with nothing selected), Tab and Shift+Tab move it between sibling layers in Layers order, Enter into a frame's top child, Shift+Enter out to the parent, Space selects it, Escape or a press on the canvas ends it; `ui.key` takes the same keys (#1836) | | Selection colors | partial | the Design panel shows the section from two paint groups (paints sharing a style, a variable and a value count as one group), or from one when a selected layer has children (a frame, group, component or instance; a layer without children shows it only with two paint groups, such as a red fill and a blue stroke; one paint group, however many layers share it, hides it), counting the selected layers' own fills and strokes and their descendants' (measured in Figma's web app, 2026-11-09, #2188, on frames, groups and rectangles only; the rule for components and instances is not measured), and lists their solid and gradient paints (children and text ranges included; hidden paints, masks, images, patterns and boolean operands left out; styles and variables listed apart): editing a colour changes every matching fill and stroke in one undo step, a row selects the layers that use it or applies a color style or color variable of the document, and a row linked to a style or variable detaches it, keeping the color (`selection.colors`, `selection.setPaint`, `selection.applyColorStyle`, `selection.bindColorVariable`, `selection.detachColor`, `selection.selectColor`). A row's Styles menu also lists each enabled library's published color styles under the library's name (a library that can't be read offers none), and a linked row's menu switches it to another style; a library style is copied in, linked and read-only, in the same undo step (`selection.applyColorStyle` with `library`). Create style on an ordinary row asks for a name (the next free "Color n" first) and makes a style of the row's whole paint, gradients, opacity, blend mode and variables bound to gradient stops included, linked to every fill and stroke the row stands for in one undo step; a name in use keeps the window open (`selection.createColorStyle`). Text ranges with fills of their own take the style's value, without a link. No library variables from there, and no new variable from a row (#403) | @@ -95,7 +97,7 @@ interaction feel only partly compared: the interactions measured so far, case by | Move, hand (Space), zoom (hold Z, Alt out, drag area) | done | the middle mouse button and a mouse's side buttons (4 and 5) pan as Space does (#1758) | | Frame (presets panel, swap orientation), section, slice | done | | | Rectangle, ellipse (arc handles and Design panel arc fields), polygon, star, line, arrow; Shift/Alt | done | Alt draws lines from the centre too (`shapes_behaviour_tests`) | -| Corner radius handles (inside each corner of a rectangle or frame, a polygon's or star's top point; Alt: one corner), star ratio handle; Count and Ratio fields | done | handles hide under 48 px on screen; no count handle on the canvas (the Count field instead); corner smoothing rounds rectangles and frames only | +| Corner radius handles (inside each corner of a rectangle or frame, a polygon's or star's top point; Alt: one corner), star ratio handle; Count and Ratio fields | done | handles hide under 48 px on screen; a Count handle sits on a polygon's first vertex or a star's first outer point clockwise from the top, and the count follows the pointer's angle about the centre, `round(360 / angle)` clockwise from the top point, clamped to 3 to 60, in one undo step (measured in Figma's web app, 2026-11-12; a polygon's maximum wasn't read and is clamped at 60 like the star's, the help center's range); corner smoothing rounds rectangles and frames only | | Pen: vector networks, branch, close, bend; pencil | done | pen pressure on Windows and from browser styluses only; outside edit mode the Pen closes on its first point, connects to its other points and continues a selected open path from an end point (`vector_multi_behaviour_tests`); Escape ends the path and keeps its layer in edit mode with the pen, so the next path joins the same vector and another Escape leaves edit mode (#760, `pen_end_tests`); Enter or a double-click ends the path (at the double-click's point, added once) and edits the vector with the Move tool, a double-click with the idle pen edits the layer under it, and in edit mode the pen's Enter or double-click takes the Move tool (#1430, `pen_vector_edit_tests`); switching from Design to Prototype or Inspect ends the path and returns to Move (#308) | | Vector edit mode: bend, paint bucket, lasso, cut, eraser, transform box, point snapping, mirroring | done | a mirror mode on a sharp point turns it smooth by the measured rule (#2110); a double-click a few pixels off a thin stroke enters edit mode (#646); entering edit mode and picking a region keep the canvas still (#322); a point dropped on another point merges with it, and dropping one end of an open path on the other closes it (a 2-point line's end just moves, #401); Flatten keeps open paths open (#377), and bakes a vector's point corner radius into its path (each rounded point becomes the arc's end points joined by curves, the layer stays a vector and its box fits the real geometry, #2195); paint bucket drags across areas; cut drags divide a shape into layers; delete and heal follows the curve; rounded points are drawn; Shift-click deselects a point at a corner of the box (`vector_behaviour_tests`); several vectors edited at once, Shift-click handles to drag them together, a cap and join per point, rounded points beside curves (`vector_multi_behaviour_tests`); filled regions with the Move tool: the area under the pointer is hatched ("/" lines in the selection colour, clipped by the area's own fill rule, holes left out, gone 3.5 px from a point or 2 px from a segment at any zoom), the line spacing follows octave folding (fitted to measurements at several zoom levels: 8 px at every power-of-two zoom, growing with the zoom and stepping back at √2 · 2ⁿ) and stays fixed to the shape when panning; a click selects the area and its points (moved with it but drawn unselected), Shift adds or removes an area, a press on a selected area drags the whole selection, no hover hatch during drags, a click on an empty spot (a hole) clears it and stays in edit mode; `vector.edit.select {regions}` (`regions_tests`, `vector_regions_tests`); a Bend click on a sharp point between two segments curves it (handles along the line between its neighbours, a third of the way to each, `ops::auto_smooth`), on a curved one sharpens it, a drag sets the handles by hand (#1875); with regions selected, the Fill section (its rows and the colour picker) and `fill.set`, `fill.add`, `fill.remove`, `fill.move` and `fill.paste` edit those regions' own fills, the layer's untouched, or the regions named by `regions: [index, ...]`; Copy fill takes the region's paint, the colour picker and its canvas gradient and crop handles edit it (an image from Upload from computer included; a file dropped on the picker goes to the canvas instead), what belongs to the layer (its fill style, a variable bound to its fill, the image crop button) stays off a region's rows, and `fill.pattern` sets the layer's fill (#1875); the Point section's X and Y show the value the selected points share, or Mixed, and a typed value sets every selected point's own coordinate, in the layer being edited (measured in Figma on 2026-11-08); Copy and Cut with points or segments selected take just those (a lone point: the segments touching it) as a vector with the layer's look, at their own place, so a paste outside edit mode is a new layer in place; Cut removes them as Delete does, the path splitting in the same layer with edit mode staying on; Paste while editing adds the clipboard's segments, or a copied shape's or boolean's outline, to the edited network in place with the new points selected, skipping layers with no outline (text, frames, groups; named in `skipped`) and refusing when none has one, as measured in Figma (`vector_clipboard_tests`, #1875). Not yet: areas of other layers edited at once; the Point section's X and Y over points of several edited layers | | Shape builder (Shift+M) on fills, strokes and open paths; variable width (Shift+W), one side with Alt | done | | @@ -215,6 +217,11 @@ This audit records candidates for subsequent fixes; their behaviour is unchanged | Date | Change | Summary | |---|---|---| | 2026-11-08 | patch | Number fields: scrubbing a label moves half a step a point, not a step, as measured in Figma (X from 100: +6 for a 12.2 px drag, +31 for 61.2 px; rotation 6° and opacity 5% for 12.2 px); Shift (x10), Alt (x0.1) and the speed by height are kept on top of it and were not measured, and no field's scrub direction changed | +| 2026-11-12 | patch | M8: a double-click on a layer's icon in the Layers panel selects the layer and zooms the canvas to it (`view.zoomSelection`) and starts no rename, as measured in Figma's web app on 2026-11-12; a double-click on the name or elsewhere on the row still renames; the icon's hit area is the rect the row paints the icon in (`a_double_click_on_a_layers_icon_zooms_to_it_instead_of_renaming`), Rename row | +| 2026-11-12 | minor | M8: Tidy up keeps the order and sizes and evens the gaps, as measured in Figma's web app on 2026-11-12. A row or column evens one gap (the most common one, the smaller of a tie, else the mean rounded half up) and keeps the other axis, layers of a row may overlap along X (also in a chain, and a negative gap is raised so no layer reaches the one two before it, measured in Figma's web app on 2026-11-13), and a grid is packed along the axis with more groups; fewer than three layers, layers that all overlap, a diagonal and an irregular layout grey the row out and move nothing. Measured: those rules and the unavailable cases; FigCraft's choices: a 2 x 2 grid as columns, auto layout flow children, the 2,000 layer cap, rotated layers by their box, `spacing` with two layers, and no rounding with pixel snapping off. Tests: tidy_tests (a_row_keeps_its_order_sizes_and_y_and_evens_the_gaps, gaps_that_all_differ_take_their_mean_taken_down, a_mean_is_rounded_half_up, two_equally_common_gaps_give_the_smaller, an_overlapping_pair_in_a_row_is_tidied_and_its_negative_gap_counts, a_grid_is_tidied_by_columns, a_transposed_grid_is_tidied_by_rows, layers_on_a_diagonal_are_unavailable, an_irregular_selection_is_unavailable and the rest). | +| 2026-11-13 | patch | M8, #2307: with Crop chosen in an image fill's colour picker, a press and drag on the image moved the whole layer: the press closed the picker, which committed the crop as a plain move. The picker now treats a crop drag as its own control (as it does the open gradient's handles, #1852), so the drag moves the picture inside the layer. A drag whose gesture something else committed under the held button no longer shows the engine's internal "no gesture in progress" as a message (`EngineError::NoGesture`, dropped by the canvas). Tests: `crop_image_tests::crop_from_the_colour_picker_then_a_drag_on_the_image_moves_the_crop_not_the_layer`, `a_drag_whose_gesture_was_committed_under_the_button_shows_no_message`. | +| 2026-11-12 | minor | M8: Align is unavailable for the one selected layer of an auto layout frame that takes part in its flow, as in Figma (measured in Figma's web app on 2026-11-12: the Design panel's Align buttons are greyed out, Alt+A and Alt+S do nothing and the frame's alignment doesn't change). `align_target` returns none for it, so `can_align` is false and the `align.*` commands leave the layout alone; the disabled tip reads "A layer in an auto layout frame is placed by its frame" (`align_blocked_by_auto_layout`). An absolutely positioned child still aligns to its frame and multi-layer selections are unchanged (neither measured). Single and multi-layer Align and Distribute otherwise matched Figma; Tidy up differs (Figma keeps the order and sizes and evens one gap per axis) and is not yet changed. Tests: `align_is_unavailable_for_a_child_in_an_auto_layout_flow`, `an_absolute_child_of_an_auto_layout_frame_still_aligns_to_it`, `the_align_buttons_are_off_for_a_layer_in_an_auto_layout_flow` | +| 2026-11-12 | patch | M5, #1560: the context menu's Select layer lists locked layers with a padlock in the leading column (the Layers panel's padlock icon; a row both selected and locked shows the check) and picking one selects it, as Lock and unlock layers' note says and as measured in Figma's web app, 2026-11-10; the submenu shows only with more than one layer under the pointer (measured on a single locked layer only: the least certain rule). Left clicks, hover and marquee still never reach a locked layer. `select.layersAt` lists locked layers too and its rows gain `locked`. Tests: `layers_at_a_point_list_locked_layers_with_a_flag_and_select_set_takes_them`, `select_layer_marks_locked_layers_with_a_padlock_and_picks_them`, `select_layer_needs_more_than_one_layer_under_the_pointer`. Counts unchanged | | 2026-11-09 | patch | Zoom to selection: the selection is fitted with a 40 pt margin into the canvas above the floating bottom toolbar (`ViewState::bottom_inset`, set by the UI each frame, never saved; `view.set` takes `bottomInset`) and centred in that area, as measured in Figma's web app on 2026-11-09. Zoom to fit is unchanged (margin not measured yet). Numbers unchanged. | | 2026-11-13 | patch | M1: Shift+Cmd/Ctrl+V (Paste over selection) puts the pasted layers just above the selected layer, in its parent and in the copied order, at its position; they went to the top of the parent's layers, so in an auto layout frame they ended the flow instead of following the selected layer. | | 2026-11-12 | patch | Drag modifiers compared in Figma's web app (2026-11-08): Shift locks a move to the dominant axis with no 45° snap, Alt copies, Shift keeps a resize's ratio (an edge scales about the opposite edge's middle), Alt keeps the centre, Shift+Alt does both, and a modifier changed mid-drag is read fresh on each move; FigCraft matches in all six, Ctrl/Cmd while dragging could not be measured; no code change | this page | @@ -332,4 +339,6 @@ This audit records candidates for subsequent fixes; their behaviour is unchanged | 2026-10-11 | minor | Outline mode done: outlines for the selection (the selected layers draw as outlines, the rest normally) and mask outlines | | 2026-10-11 | minor | Design panel arc fields, live boolean editing (operands on the canvas, live results, per-operand operations), shape builder on strokes and open paths, one-sided widths (Alt-drag a width handle) | | 2026-11-09 | patch | M8, #2146: K focuses the Scale tool's factor field with its text selected, so K, 2, Enter scales the selection by two about the panel's origin (FigCraft's starts at the top left; Figma's grid starts at the centre, left for a follow-up because the origin also sets where a handle drag pivots, which is not measured) in one undo step, after which the tool returns to Move with the selection kept; Escape in the field closes it with the tool back on Move and nothing changed (measured in Figma's web app, 2026-11-09; `pressing_k_focuses_the_scale_field_with_its_text_selected`, `k_two_enter_scales_the_selection_by_two`, `escape_in_the_scale_field_closes_it_and_changes_nothing`) | +| 2026-11-12 | patch | M8: Scale tool handle drags pivot on the opposite handle whatever the origin, and the origin starts at the centre, so K, 2, Enter scales about the centre (measured in Figma's web app, 2026-11-09; `a_scale_handle_drag_pivots_on_the_opposite_handle_whatever_the_origin`, `the_scale_origin_starts_at_the_centre`) | +| 2026-11-12 | minor | M8: a selected polygon or star has a Count handle on the canvas (hover label Count N), measured in Figma's web app on 2026-11-12: it sits on the first vertex clockwise from the top (a star's first outer point, not inset), and a drag sets the count to round(360 / the pointer's clockwise angle from the top point about the centre), so 90 degrees gives 4, 72 gives 5 and 45 gives 8, with the step shrinking as the count grows; one drag is one undo step. The count is clamped to 3 to 60 (the help center's range for a star; a polygon's maximum was not read). Tests: `a_polygon_has_a_count_handle_on_its_first_vertex_clockwise_from_the_top`, `dragging_the_count_handle_sets_the_count_by_the_angle_about_the_centre`, `a_count_drag_is_one_undo_step` | | 2026-10-10 | major | Created from the ROADMAP's look-and-feel and interaction items, the keymap and the canvas code |