mirror of
https://github.com/storytold/figcraft.git
synced 2026-11-15 23:02:36 +00:00
Merge remote-tracking branch 'origin/main' into fix2284
This commit is contained in:
commit
8b1f315335
42 files changed
+2048
-126
No files matched your search
@@ -112,7 +112,7 @@ fn pages_can_be_inserted_onto_a_page_less_base() {
|
||||
assert!(d.pages.is_empty() && d.node_count() == 0);
|
||||
let p = Node::new(
|
||||
NodeId(C3 | 1),
|
||||
NodeKind::Page { background: figcraft_color::Color::DEFAULT_PAGE, flows: vec![], prototype: Default::default() },
|
||||
NodeKind::Page { background: figcraft_color::Color::DEFAULT_PAGE, flows: vec![], prototype: Default::default(), opening: false },
|
||||
"P",
|
||||
0.0,
|
||||
0.0,
|
||||
|
||||
+39
-16
@@ -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<NodeId> {
|
||||
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<NodeId> {
|
||||
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<NodeId> {
|
||||
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<OutlineHits>) -> Option<NodeId> {
|
||||
/// 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<OutlineHits>,
|
||||
opts: HitOpts,
|
||||
) -> Option<NodeId> {
|
||||
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);
|
||||
}
|
||||
|
||||
@@ -439,8 +439,13 @@ impl Document {
|
||||
/// Add a page at the end.
|
||||
pub fn add_page(&mut self, name: &str) -> NodeId {
|
||||
let id = self.alloc_id();
|
||||
let node =
|
||||
Node::new(id, NodeKind::Page { background: Color::DEFAULT_PAGE, flows: Vec::new(), prototype: Default::default() }, name, 0.0, 0.0);
|
||||
let node = Node::new(
|
||||
id,
|
||||
NodeKind::Page { background: Color::DEFAULT_PAGE, flows: Vec::new(), prototype: Default::default(), opening: false },
|
||||
name,
|
||||
0.0,
|
||||
0.0,
|
||||
);
|
||||
self.nodes.insert(id, Arc::new(node));
|
||||
self.dirty.touch(id);
|
||||
self.pages.push(id);
|
||||
|
||||
@@ -312,7 +312,7 @@ impl Document {
|
||||
let id = self.alloc_id();
|
||||
let node = Node::new(
|
||||
id,
|
||||
NodeKind::Page { background: figcraft_color::Color::DEFAULT_PAGE, flows: Vec::new(), prototype: Default::default() },
|
||||
NodeKind::Page { background: figcraft_color::Color::DEFAULT_PAGE, flows: Vec::new(), prototype: Default::default(), opening: false },
|
||||
STORE_NAME,
|
||||
0.0,
|
||||
0.0,
|
||||
|
||||
@@ -91,6 +91,10 @@ pub enum NodeKind {
|
||||
flows: Vec<crate::proto::Flow>,
|
||||
#[serde(default)]
|
||||
prototype: crate::proto::PrototypeSettings,
|
||||
/// The page chosen to open the file on for everyone (`page.setOpening`; at most one page):
|
||||
/// saving writes it as the document's `current_page` instead of the page the saver was viewing.
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
opening: bool,
|
||||
},
|
||||
Frame,
|
||||
Group,
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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<Rect> {
|
||||
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<Value> {
|
||||
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<Value> {
|
||||
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<(NodeId, Rect)>> = 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<Rect> = 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::<f64>())
|
||||
/ (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()
|
||||
}
|
||||
|
||||
+113
-11
@@ -3,7 +3,7 @@
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
use figcraft_doc::{Document, Effect, ExportSetting, ImageData, LayoutGrid, Node, NodeId, NodeKind};
|
||||
use figcraft_geom::Affine;
|
||||
use figcraft_geom::{Affine, Point};
|
||||
use serde_json::{Map, Value, json};
|
||||
|
||||
use super::{CommandSpec, ok};
|
||||
@@ -207,7 +207,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
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
|
||||
),
|
||||
@@ -616,7 +616,8 @@ fn delete(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
/// Layers duplicated last (Duplicate or Alt-drag) and their copies, in the same order. While the
|
||||
/// copies are the selection, Duplicate places the next copies as far from them as they are from
|
||||
/// their sources, measured then: so moving the copies first sets the step.
|
||||
/// their sources, measured then (their move and turn, not their size): so moving or turning the
|
||||
/// copies first sets the step.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Duplicated {
|
||||
pub sources: Vec<NodeId>,
|
||||
@@ -629,9 +630,12 @@ impl Duplicated {
|
||||
!self.copies.is_empty() && set(&self.copies) == set(sel)
|
||||
}
|
||||
|
||||
/// The page offset from the sources to the copies, if both are still there and the copies move
|
||||
/// freely (an auto layout places its own).
|
||||
fn offset(&self, doc: &Document) -> Option<(f64, f64)> {
|
||||
/// The step from the sources to the copies, if both are still there and the copies move freely
|
||||
/// (an auto layout places its own): the mean move of the copies' own centres in the page frame
|
||||
/// (less what a size change shifts them by), and the turn every copy has over its source (zero
|
||||
/// unless they all agree, or when a flip differs). A turn is not counted as a move, whether each
|
||||
/// copy turned about its own centre or the copies turned together about their shared centre.
|
||||
fn step(&self, doc: &Document) -> Option<Step> {
|
||||
let free = self
|
||||
.copies
|
||||
.iter()
|
||||
@@ -639,19 +643,109 @@ impl Duplicated {
|
||||
if !free || self.sources.iter().chain(&self.copies).any(|i| !doc.contains(*i)) {
|
||||
return None;
|
||||
}
|
||||
let (a, b) = (doc.bounds_of(&self.sources)?, doc.bounds_of(&self.copies)?);
|
||||
let d = (b.x0 - a.x0, b.y0 - a.y0);
|
||||
(d.0.is_finite() && d.1.is_finite() && (d.0 != 0.0 || d.1 != 0.0)).then_some(d)
|
||||
// A flip reads as a half turn and was not measured: never repeat a turn across one.
|
||||
let flips_differ = self
|
||||
.sources
|
||||
.iter()
|
||||
.zip(&self.copies)
|
||||
.any(|(s, c)| figcraft_geom::is_flipped(doc.world_transform(*s)) != figcraft_geom::is_flipped(doc.world_transform(*c)));
|
||||
let turns: Vec<f64> = self
|
||||
.sources
|
||||
.iter()
|
||||
.zip(&self.copies)
|
||||
.map(|(s, c)| {
|
||||
let d = figcraft_geom::rotation_degrees(doc.world_transform(*c)) - figcraft_geom::rotation_degrees(doc.world_transform(*s));
|
||||
let d = d.rem_euclid(360.0);
|
||||
if d > 180.0 { d - 360.0 } else { d }
|
||||
})
|
||||
.collect();
|
||||
let angle = match turns.first() {
|
||||
Some(first) if !flips_differ && turns.iter().all(|t| (t - first).abs() < 1e-6) => *first,
|
||||
_ => 0.0,
|
||||
};
|
||||
// Per pair, where the copy's own centre is, less what its size change moved that centre by
|
||||
// (a growing edge shifts it, in the source's frame), and where the source's centre is.
|
||||
let mut pairs = Vec::new();
|
||||
for (s, c) in self.sources.iter().zip(&self.copies) {
|
||||
let (sn, cn) = (doc.node(*s)?, doc.node(*c)?);
|
||||
let (sw, cw) = (doc.world_transform(*s), doc.world_transform(*c));
|
||||
let (ps, pc) = (sw * Point::new(sn.width / 2.0, sn.height / 2.0), cw * Point::new(cn.width / 2.0, cn.height / 2.0));
|
||||
let grow = Point::new((cn.width - sn.width) / 2.0, (cn.height - sn.height) / 2.0);
|
||||
let shift_in = |x: Affine| x * grow - x * Point::ORIGIN;
|
||||
// The order of a turn and a resize isn't recorded. A resize then a turn shifts the centre
|
||||
// along the source's axes; a turn then a resize, along the copy's. Take the copy's only
|
||||
// when it alone makes this pair's own move zero: a pure resize plus turn, either order,
|
||||
// with no move must give no move. Otherwise keep the source's.
|
||||
let (by_source, by_copy) = (pc - shift_in(sw), pc - shift_in(cw));
|
||||
let still = |q: Point| (q.x - ps.x).hypot(q.y - ps.y) < 1e-6;
|
||||
let corrected = if still(by_copy) && !still(by_source) { by_copy } else { by_source };
|
||||
pairs.push((ps, corrected));
|
||||
}
|
||||
// The mean of the residuals, and whether they all agree (the copies fit that reading).
|
||||
let fit = |res: &[(f64, f64)]| {
|
||||
let n = res.len() as f64;
|
||||
let mean = (res.iter().map(|m| m.0).sum::<f64>() / n, res.iter().map(|m| m.1).sum::<f64>() / n);
|
||||
let agree = res.iter().all(|m| (m.0 - mean.0).hypot(m.1 - mean.1) < 1e-6);
|
||||
(mean, agree)
|
||||
};
|
||||
// Reading A, each copy turned about its own centre: the residual is the move of its centre.
|
||||
let each: Vec<(f64, f64)> = pairs.iter().map(|(ps, pc)| (pc.x - ps.x, pc.y - ps.y)).collect();
|
||||
let (mut mv, each_fits) = fit(&each);
|
||||
// Reading B, the copies turned together about the sources' centre (as a Rotate on several
|
||||
// layers does): the residual is what is left once each source's centre is turned that way.
|
||||
// The centre is `turn_centre`, never read from the copies: a turn about another point shifts
|
||||
// every residual by the same vector, so where the copies are can't say which point they
|
||||
// turned about. Such a turn reads as this one plus a move.
|
||||
if angle != 0.0
|
||||
&& pairs.len() > 1
|
||||
&& !each_fits
|
||||
&& let Some(c) = turn_centre(doc, &self.sources)
|
||||
{
|
||||
let together: Vec<(f64, f64)> = pairs
|
||||
.iter()
|
||||
.map(|(ps, pc)| {
|
||||
let q = figcraft_geom::translation(figcraft_geom::rotate_about(Affine::translate(ps.to_vec2()), c, angle));
|
||||
(pc.x - q.x, pc.y - q.y)
|
||||
})
|
||||
.collect();
|
||||
let (m, together_fits) = fit(&together);
|
||||
if together_fits {
|
||||
mv = m;
|
||||
}
|
||||
}
|
||||
let (dx, dy) = mv;
|
||||
let step = Step { dx, dy, angle };
|
||||
(step.dx.is_finite() && step.dy.is_finite() && step.angle.is_finite() && (dx != 0.0 || dy != 0.0 || angle != 0.0)).then_some(step)
|
||||
}
|
||||
}
|
||||
|
||||
/// What Duplicate repeats: a move of the copies' centre in the page frame, then a turn about the
|
||||
/// centre of the new copies. Size is not part of it.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
struct Step {
|
||||
dx: f64,
|
||||
dy: f64,
|
||||
angle: f64,
|
||||
}
|
||||
|
||||
/// Where several layers turn, for the step and for its repeat: the centre of their handle box
|
||||
/// (`selection_box`), the point the Rotate handle and the rotate keys turn a selection about.
|
||||
/// One layer: its own centre. Several: their bounds centre, or the centre of the box turned
|
||||
/// with them when they share a rotation. `transform.rotate` without a pivot turns about the
|
||||
/// bounds centre instead, so its turn of layers that share a rotation repeats as a turn plus
|
||||
/// a move.
|
||||
fn turn_centre(doc: &Document, ids: &[NodeId]) -> Option<Point> {
|
||||
let q = crate::tools::selection_box(doc, ids)?;
|
||||
Some(Point::new(q.iter().map(|c| c.x).sum::<f64>() / 4.0, q.iter().map(|c| c.y).sum::<f64>() / 4.0))
|
||||
}
|
||||
|
||||
fn duplicate(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let ids = req_targets("edit.duplicate", s, p)?;
|
||||
let rename = s.prefs.rename_duplicates;
|
||||
let explicit = num(p, "dx").is_some() || num(p, "dy").is_some();
|
||||
let ds = s.ds()?;
|
||||
let roots_now = z_sorted(&ds.doc, &roots(&ds.doc, &ids));
|
||||
let repeat = ds.last_duplicate.as_ref().filter(|d| !explicit && d.is_selection(&roots_now)).and_then(|d| d.offset(&ds.doc));
|
||||
let repeat = ds.last_duplicate.as_ref().filter(|d| !explicit && d.is_selection(&roots_now)).and_then(|d| d.step(&ds.doc));
|
||||
let doc = s.doc_mut()?;
|
||||
let ids = roots_now;
|
||||
let mut out = Vec::new();
|
||||
@@ -670,7 +764,7 @@ fn duplicate(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
_ => (0.0, 0.0),
|
||||
};
|
||||
match repeat {
|
||||
Some((rx, ry)) => super::arrange::move_world(doc, nid, rx, ry)?,
|
||||
Some(st) => super::arrange::move_world(doc, nid, st.dx, st.dy)?,
|
||||
None => {
|
||||
let nn = doc.get_mut(nid)?;
|
||||
nn.transform = Affine::translate((dx, dy)) * nn.transform;
|
||||
@@ -683,6 +777,14 @@ fn duplicate(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
out.push(nid);
|
||||
}
|
||||
// A repeated turn is about the new copies' centre: one layer's own, several layers' shared one.
|
||||
if let Some(st) = repeat.filter(|st| st.angle != 0.0)
|
||||
&& let Some(c) = turn_centre(doc, &out)
|
||||
{
|
||||
for nid in out.iter().copied() {
|
||||
super::arrange::rotate_world(doc, nid, c, st.angle)?;
|
||||
}
|
||||
}
|
||||
crate::library::count_inserted(doc, &out);
|
||||
// Board connectors copied with what they join join the copies.
|
||||
let map = crate::board::copy_map(doc, &ids, &out);
|
||||
|
||||
@@ -8,9 +8,13 @@ pub(super) fn layers_at(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let zoom = s.ds()?.view.zoom.max(1e-6);
|
||||
let sel = s.selection();
|
||||
let result = crate::booleans::result_outline(doc, &sel);
|
||||
let layers: Vec<Value> = 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<Value> = 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}))
|
||||
}
|
||||
|
||||
@@ -85,7 +85,8 @@ impl FileSnapshot {
|
||||
/// files are from its folder.
|
||||
fn encode_at(&self, path: Option<&str>) -> Result<Vec<u8>> {
|
||||
let mut doc = (*self.doc).clone();
|
||||
doc.current_page = Some(self.page);
|
||||
let opening = doc.pages.iter().copied().find(|&p| matches!(doc.get(p).map(|n| &n.kind), Ok(NodeKind::Page { opening: true, .. })));
|
||||
doc.current_page = Some(opening.unwrap_or(self.page));
|
||||
if let Some(path) = path {
|
||||
crate::library::relate_links(&mut doc, path);
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! Pages.
|
||||
|
||||
use figcraft_doc::proto::Flow;
|
||||
use figcraft_doc::{Guide, NodeId, NodeKind};
|
||||
use figcraft_doc::{Document, Guide, NodeId, NodeKind};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::{CommandSpec, ok};
|
||||
@@ -109,8 +109,8 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
// The copy keeps the page's colour, flows (pointing at the copied frames), prototype settings and guides.
|
||||
let guides = doc.get(src)?.guides.clone();
|
||||
doc.get_mut(np)?.guides = guides;
|
||||
if let NodeKind::Page { background, flows, prototype } = doc.get(src)?.kind.clone()
|
||||
&& let NodeKind::Page { background: b, flows: f, prototype: pr } = &mut doc.get_mut(np)?.kind
|
||||
if let NodeKind::Page { background, flows, prototype, .. } = doc.get(src)?.kind.clone()
|
||||
&& let NodeKind::Page { background: b, flows: f, prototype: pr, .. } = &mut doc.get_mut(np)?.kind
|
||||
{
|
||||
*b = background;
|
||||
*f = flows
|
||||
@@ -147,6 +147,38 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
}
|
||||
ok()
|
||||
}),
|
||||
spec!(
|
||||
"page.setOpening",
|
||||
"Set as opening page",
|
||||
"{id?} (the page the file opens on, for everyone who opens or joins it; the current page when none is named)",
|
||||
true,
|
||||
|s, p| {
|
||||
// A document property (#1817), so it syncs in a live session and undoes; nobody's
|
||||
// own page moves (`page.select` is each viewer's).
|
||||
let id = page_target(s, "page.setOpening", p)?;
|
||||
if s.doc()?.is_divider(id) {
|
||||
return Err(bad("page.setOpening", "a divider isn't a page to open on"));
|
||||
}
|
||||
let is_opening = |doc: &Document, p: NodeId| matches!(doc.get(p).map(|n| &n.kind), Ok(NodeKind::Page { opening: true, .. }));
|
||||
if s.doc()?.current_page == Some(id) && is_opening(s.doc()?, id) {
|
||||
// Already the opening page: nothing changes, so no undo step.
|
||||
return ok();
|
||||
}
|
||||
let doc = s.doc_mut()?;
|
||||
doc.current_page = Some(id);
|
||||
// The flag lives on the page node (so it syncs with the node's kind): one page has it.
|
||||
for page in doc.pages.clone() {
|
||||
let want = page == id;
|
||||
if is_opening(doc, page) != want
|
||||
&& let NodeKind::Page { opening, .. } = &mut doc.get_mut(page)?.kind
|
||||
{
|
||||
*opening = want;
|
||||
}
|
||||
}
|
||||
settle(s, "page.setOpening")?;
|
||||
ok()
|
||||
}
|
||||
),
|
||||
spec!("page.list", "List pages", "{}", false, |s, _| {
|
||||
let doc = s.doc()?;
|
||||
let cur = s.page()?;
|
||||
|
||||
@@ -552,3 +552,31 @@ fn leaving_the_session_goes_back_to_snapshot_undo() {
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().node(r).unwrap().name, "Live");
|
||||
}
|
||||
|
||||
/// #1817: the page a file opens on is a document property: setting it syncs to the server, so
|
||||
/// everyone who joins afterwards lands on it, and moves nobody's own view.
|
||||
#[test]
|
||||
fn the_opening_page_syncs_and_moves_no_ones_view() {
|
||||
let mut room = Room::new(base(), 2, 7);
|
||||
let first = room.server.document().first_page().unwrap();
|
||||
let cover = NodeId(room.s(0).execute("page.add", &json!({"name": "Cover"})).unwrap()["id"].as_u64().unwrap());
|
||||
room.settle();
|
||||
room.check();
|
||||
assert_eq!(room.s(1).page().unwrap(), first, "another person's page is their own");
|
||||
room.s(0).execute("page.setOpening", &json!({"id": cover})).unwrap();
|
||||
room.settle();
|
||||
room.check();
|
||||
assert_eq!(room.server.document().current_page, Some(cover), "the server's file opens on it now");
|
||||
assert_eq!(room.s(1).page().unwrap(), first, "nobody's view moved");
|
||||
assert_eq!(Session::with_document(room.server.document().clone()).page().unwrap(), cover, "whoever joins next lands on it");
|
||||
// One undo step, the setter's.
|
||||
assert_eq!(room.s(0).execute("edit.undo", &json!({})).unwrap()["undone"], true);
|
||||
room.settle();
|
||||
room.check();
|
||||
assert_ne!(room.server.document().current_page, Some(cover), "undone for everyone");
|
||||
assert_eq!(
|
||||
Session::with_document(room.server.document().clone()).page().unwrap(),
|
||||
first,
|
||||
"whoever joins after the undo lands on the restored page"
|
||||
);
|
||||
}
|
||||
@@ -255,3 +255,277 @@ fn duplicate_repeats_a_nudged_step() {
|
||||
let c2 = cmd_d(&mut s);
|
||||
assert_eq!(at(&s, c2), (80.0, 0.0), "the nudge is the step");
|
||||
}
|
||||
|
||||
fn centre(s: &Session, id: NodeId) -> (f64, f64) {
|
||||
let c = s.doc().unwrap().world_bounds(id).unwrap().center();
|
||||
(c.x, c.y)
|
||||
}
|
||||
|
||||
fn turn(s: &Session, id: NodeId) -> f64 {
|
||||
figcraft_geom::rotation_degrees(s.doc().unwrap().world_transform(id))
|
||||
}
|
||||
|
||||
fn near(a: f64, b: f64) -> bool {
|
||||
(a - b).abs() < 1e-6
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn duplicate_repeats_the_copys_move_and_rotation() {
|
||||
let mut s = Session::new();
|
||||
let a = rect(&mut s, 0.0, 0.0);
|
||||
ex(&mut s, "select.set", json!({"ids": [a]}));
|
||||
let c1 = cmd_d(&mut s);
|
||||
ex(&mut s, "node.set", json!({"ids": [c1], "props": {"x": 150}}));
|
||||
ex(&mut s, "node.set", json!({"ids": [c1], "props": {"rotation": -15}}));
|
||||
assert!(near(centre(&s, c1).0, 200.0) && near(centre(&s, c1).1, 50.0));
|
||||
for k in 1..=3 {
|
||||
let c = cmd_d(&mut s);
|
||||
let (x, y) = centre(&s, c);
|
||||
let want = 200.0 + 150.0 * f64::from(k);
|
||||
assert!(near(x, want) && near(y, 50.0), "repeat {k}: centre ({x}, {y})");
|
||||
assert!(near(turn(&s, c), -15.0 - 15.0 * f64::from(k)), "repeat {k}: rotation {}", turn(&s, c));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn duplicate_repeats_a_rotation_in_place() {
|
||||
let mut s = Session::new();
|
||||
let a = rect(&mut s, 0.0, 0.0);
|
||||
ex(&mut s, "select.set", json!({"ids": [a]}));
|
||||
let c1 = cmd_d(&mut s);
|
||||
ex(&mut s, "node.set", json!({"ids": [c1], "props": {"rotation": 30}}));
|
||||
for k in 1..=3 {
|
||||
let c = cmd_d(&mut s);
|
||||
let (x, y) = centre(&s, c);
|
||||
assert!(near(x, 50.0) && near(y, 50.0), "repeat {k}: centre ({x}, {y})");
|
||||
assert!(near(turn(&s, c), 30.0 + 30.0 * f64::from(k)), "repeat {k}: rotation {}", turn(&s, c));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn duplicate_does_not_step_the_size() {
|
||||
let mut s = Session::new();
|
||||
let a = rect(&mut s, 0.0, 0.0);
|
||||
ex(&mut s, "select.set", json!({"ids": [a]}));
|
||||
let c1 = cmd_d(&mut s);
|
||||
ex(&mut s, "node.set", json!({"ids": [c1], "props": {"x": 150}}));
|
||||
ex(&mut s, "node.set", json!({"ids": [c1], "props": {"width": 120}}));
|
||||
let c1_centre = centre(&s, c1);
|
||||
for k in 1..=2 {
|
||||
let c = cmd_d(&mut s);
|
||||
let w = s.doc().unwrap().get(c).unwrap().width;
|
||||
assert!(near(w, 120.0), "repeat {k}: width {w}");
|
||||
assert!(near(centre(&s, c).0, c1_centre.0 + 150.0 * f64::from(k)), "repeat {k}: centre {:?}", centre(&s, c));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn duplicate_turns_several_layers_about_their_selection_centre() {
|
||||
let mut s = Session::new();
|
||||
let a = rect(&mut s, 0.0, 0.0);
|
||||
let b = rect(&mut s, 150.0, 0.0);
|
||||
ex(&mut s, "select.set", json!({"ids": [a, b]}));
|
||||
let out = ex(&mut s, "edit.duplicate", json!({}));
|
||||
let copies: Vec<NodeId> = out["ids"].as_array().unwrap().iter().map(|v| id_of(v).unwrap()).collect();
|
||||
ex(&mut s, "transform.nudge", json!({"dx": 150, "dy": 0}));
|
||||
// Turn the pair -15 about its combined centre.
|
||||
ex(&mut s, "transform.rotate", json!({"ids": copies, "degrees": -15}));
|
||||
let before: Vec<(f64, f64)> = copies.iter().map(|c| centre(&s, *c)).collect();
|
||||
let pair_before = s.doc().unwrap().bounds_of(&copies).unwrap().center();
|
||||
let again = ex(&mut s, "edit.duplicate", json!({}));
|
||||
let next: Vec<NodeId> = again["ids"].as_array().unwrap().iter().map(|v| id_of(v).unwrap()).collect();
|
||||
assert_eq!(next.len(), 2);
|
||||
let after = s.doc().unwrap().bounds_of(&next).unwrap().center();
|
||||
assert!(near(after.x, pair_before.x + 150.0) && near(after.y, pair_before.y), "pair centre {after:?}");
|
||||
for (i, c) in next.iter().enumerate() {
|
||||
assert!(near(turn(&s, *c), -30.0), "layer {i}: rotation {}", turn(&s, *c));
|
||||
// Expected: the layer's centre moved +150, then turned -15 about the moved pair's centre.
|
||||
let moved = figcraft_geom::Affine::translate((before[i].0 + 150.0, before[i].1));
|
||||
let want = figcraft_geom::translation(figcraft_geom::rotate_about(moved, after, -15.0));
|
||||
let got = centre(&s, *c);
|
||||
assert!(near(got.0, want.x) && near(got.1, want.y), "layer {i}: {got:?} vs {want:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_deselect_forgets_the_duplicate_step() {
|
||||
let mut s = Session::new();
|
||||
let a = rect(&mut s, 0.0, 0.0);
|
||||
ex(&mut s, "select.set", json!({"ids": [a]}));
|
||||
let c1 = cmd_d(&mut s);
|
||||
ex(&mut s, "node.set", json!({"ids": [c1], "props": {"x": 150}}));
|
||||
ex(&mut s, "select.none", json!({}));
|
||||
ex(&mut s, "select.set", json!({"ids": [c1]}));
|
||||
let c2 = cmd_d(&mut s);
|
||||
assert_eq!(at(&s, c2), (150.0, 0.0), "no step after a deselect: the copy lands in place");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn several_uneven_layers_turned_in_place_repeat_the_turn_without_a_move() {
|
||||
let mut s = Session::new();
|
||||
let wide = id_of(&ex(&mut s, "shape.rectangle", json!({"x": 200, "y": 0, "width": 300, "height": 100}))["id"]).unwrap();
|
||||
let ids = [rect(&mut s, 0.0, 200.0), wide];
|
||||
ex(&mut s, "select.set", json!({"ids": ids}));
|
||||
let out = ex(&mut s, "edit.duplicate", json!({}));
|
||||
let copies: Vec<NodeId> = out["ids"].as_array().unwrap().iter().map(|v| id_of(v).unwrap()).collect();
|
||||
for c in &copies {
|
||||
ex(&mut s, "node.set", json!({"ids": [*c], "props": {"rotation": -45}}));
|
||||
}
|
||||
let pivot = handle_box_centre(&s, &copies);
|
||||
let before: Vec<(f64, f64)> = copies.iter().map(|c| centre(&s, *c)).collect();
|
||||
let again = ex(&mut s, "edit.duplicate", json!({}));
|
||||
let next: Vec<NodeId> = again["ids"].as_array().unwrap().iter().map(|v| id_of(v).unwrap()).collect();
|
||||
for (i, c) in next.iter().enumerate() {
|
||||
assert!(near(turn(&s, *c), -90.0), "layer {i}: rotation {}", turn(&s, *c));
|
||||
// No move: each layer's centre only turned -45 about the copies' shared centre.
|
||||
let want =
|
||||
figcraft_geom::translation(figcraft_geom::rotate_about(figcraft_geom::Affine::translate((before[i].0, before[i].1)), pivot, -45.0));
|
||||
let got = centre(&s, *c);
|
||||
assert!(near(got.0, want.x) && near(got.1, want.y), "layer {i}: {got:?} vs {want:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The uneven pair the collective-turn tests share: a square and a wide one, selected and duplicated.
|
||||
fn uneven_pair_and_copies(s: &mut Session) -> Vec<NodeId> {
|
||||
let wide = id_of(&ex(s, "shape.rectangle", json!({"x": 200, "y": 0, "width": 300, "height": 100}))["id"]).unwrap();
|
||||
let ids = [rect(s, 0.0, 200.0), wide];
|
||||
ex(s, "select.set", json!({"ids": ids}));
|
||||
let out = ex(s, "edit.duplicate", json!({}));
|
||||
out["ids"].as_array().unwrap().iter().map(|v| id_of(v).unwrap()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn several_uneven_layers_turned_together_repeat_the_turn_without_a_move() {
|
||||
let mut s = Session::new();
|
||||
let copies = uneven_pair_and_copies(&mut s);
|
||||
ex(&mut s, "transform.rotate", json!({"ids": copies, "degrees": 90}));
|
||||
let pivot = s.doc().unwrap().bounds_of(&copies).unwrap().center();
|
||||
let before: Vec<(f64, f64)> = copies.iter().map(|c| centre(&s, *c)).collect();
|
||||
let again = ex(&mut s, "edit.duplicate", json!({}));
|
||||
let next: Vec<NodeId> = again["ids"].as_array().unwrap().iter().map(|v| id_of(v).unwrap()).collect();
|
||||
assert_eq!(next.len(), 2);
|
||||
for (i, c) in next.iter().enumerate() {
|
||||
assert!(near(turn(&s, *c).abs(), 180.0), "layer {i}: rotation {}", turn(&s, *c));
|
||||
let want = figcraft_geom::translation(figcraft_geom::rotate_about(figcraft_geom::Affine::translate((before[i].0, before[i].1)), pivot, 90.0));
|
||||
let got = centre(&s, *c);
|
||||
assert!(near(got.0, want.x) && near(got.1, want.y), "layer {i}: {got:?} vs {want:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn several_uneven_layers_moved_and_turned_together_repeat_both() {
|
||||
let mut s = Session::new();
|
||||
let copies = uneven_pair_and_copies(&mut s);
|
||||
ex(&mut s, "transform.nudge", json!({"dx": 150, "dy": 0}));
|
||||
ex(&mut s, "transform.rotate", json!({"ids": copies, "degrees": -15}));
|
||||
let pivot = handle_box_centre(&s, &copies);
|
||||
let before: Vec<(f64, f64)> = copies.iter().map(|c| centre(&s, *c)).collect();
|
||||
let again = ex(&mut s, "edit.duplicate", json!({}));
|
||||
let next: Vec<NodeId> = again["ids"].as_array().unwrap().iter().map(|v| id_of(v).unwrap()).collect();
|
||||
assert_eq!(next.len(), 2);
|
||||
let moved_pivot = figcraft_geom::Point::new(pivot.x + 150.0, pivot.y);
|
||||
for (i, c) in next.iter().enumerate() {
|
||||
assert!(near(turn(&s, *c), -30.0), "layer {i}: rotation {}", turn(&s, *c));
|
||||
let moved = figcraft_geom::Affine::translate((before[i].0 + 150.0, before[i].1));
|
||||
let want = figcraft_geom::translation(figcraft_geom::rotate_about(moved, moved_pivot, -15.0));
|
||||
let got = centre(&s, *c);
|
||||
assert!(near(got.0, want.x) && near(got.1, want.y), "layer {i}: {got:?} vs {want:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_widened_copy_turned_in_place_repeats_the_turn_without_a_move() {
|
||||
let mut s = Session::new();
|
||||
let a = rect(&mut s, 0.0, 0.0);
|
||||
ex(&mut s, "select.set", json!({"ids": [a]}));
|
||||
let c1 = cmd_d(&mut s);
|
||||
ex(&mut s, "node.set", json!({"ids": [c1], "props": {"width": 120}}));
|
||||
ex(&mut s, "node.set", json!({"ids": [c1], "props": {"rotation": -90}}));
|
||||
let c1_centre = centre(&s, c1);
|
||||
let c2 = cmd_d(&mut s);
|
||||
let got = centre(&s, c2);
|
||||
assert!(near(got.0, c1_centre.0) && near(got.1, c1_centre.1), "centre {got:?} vs {c1_centre:?}");
|
||||
assert!(near(turn(&s, c2).abs(), 180.0), "rotation {}", turn(&s, c2));
|
||||
assert!(near(s.doc().unwrap().get(c2).unwrap().width, 120.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_copy_turned_then_widened_repeats_the_turn_without_a_move() {
|
||||
let mut s = Session::new();
|
||||
let a = rect(&mut s, 0.0, 0.0);
|
||||
ex(&mut s, "select.set", json!({"ids": [a]}));
|
||||
let c1 = cmd_d(&mut s);
|
||||
ex(&mut s, "node.set", json!({"ids": [c1], "props": {"rotation": -90}}));
|
||||
ex(&mut s, "node.set", json!({"ids": [c1], "props": {"width": 120}}));
|
||||
let c1_centre = centre(&s, c1);
|
||||
let c2 = cmd_d(&mut s);
|
||||
let got = centre(&s, c2);
|
||||
assert!(near(got.0, c1_centre.0) && near(got.1, c1_centre.1), "centre {got:?} vs {c1_centre:?}");
|
||||
assert!(near(turn(&s, c2).abs(), 180.0), "rotation {}", turn(&s, c2));
|
||||
assert!(near(s.doc().unwrap().get(c2).unwrap().width, 120.0));
|
||||
}
|
||||
|
||||
/// The centre of the selection's handle box, which is what the Rotate handle turns about.
|
||||
fn handle_box_centre(s: &Session, ids: &[NodeId]) -> figcraft_geom::Point {
|
||||
let q = crate::tools::selection_box(s.doc().unwrap(), ids).unwrap();
|
||||
figcraft_geom::Point::new(q.iter().map(|c| c.x).sum::<f64>() / 4.0, q.iter().map(|c| c.y).sum::<f64>() / 4.0)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_turned_pair_turned_again_about_its_handle_box_repeats_without_a_move() {
|
||||
let mut s = Session::new();
|
||||
let wide = id_of(&ex(&mut s, "shape.rectangle", json!({"x": 200, "y": 0, "width": 300, "height": 100}))["id"]).unwrap();
|
||||
let ids = [rect(&mut s, 0.0, 200.0), wide];
|
||||
ex(&mut s, "transform.rotate", json!({"ids": ids, "degrees": 60}));
|
||||
ex(&mut s, "select.set", json!({"ids": ids}));
|
||||
let out = ex(&mut s, "edit.duplicate", json!({}));
|
||||
let copies: Vec<NodeId> = out["ids"].as_array().unwrap().iter().map(|v| id_of(v).unwrap()).collect();
|
||||
let p = handle_box_centre(&s, &copies);
|
||||
ex(&mut s, "transform.rotate", json!({"ids": copies, "degrees": 30, "cx": p.x, "cy": p.y}));
|
||||
let before: Vec<(f64, f64)> = copies.iter().map(|c| centre(&s, *c)).collect();
|
||||
let again = ex(&mut s, "edit.duplicate", json!({}));
|
||||
let next: Vec<NodeId> = again["ids"].as_array().unwrap().iter().map(|v| id_of(v).unwrap()).collect();
|
||||
assert_eq!(next.len(), 2);
|
||||
let pivot = handle_box_centre(&s, &next);
|
||||
for (i, c) in next.iter().enumerate() {
|
||||
assert!(near(turn(&s, *c), 120.0), "layer {i}: rotation {}", turn(&s, *c));
|
||||
let want = figcraft_geom::translation(figcraft_geom::rotate_about(figcraft_geom::Affine::translate((before[i].0, before[i].1)), pivot, 30.0));
|
||||
let got = centre(&s, *c);
|
||||
assert!(near(got.0, want.x) && near(got.1, want.y), "layer {i}: {got:?} vs {want:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn several_uneven_layers_turned_together_repeat_about_one_centre_each_time() {
|
||||
let mut s = Session::new();
|
||||
let mut copies = uneven_pair_and_copies(&mut s);
|
||||
// Upright, the pair's handle box is its bounds: both centres are (250, 150), so this is also
|
||||
// the Rotate handle's turn. Turned, the box keeps that centre; the bounds don't.
|
||||
ex(&mut s, "transform.rotate", json!({"ids": copies, "degrees": 30}));
|
||||
let pivot = figcraft_geom::Point::new(250.0, 150.0);
|
||||
for k in 1..=3 {
|
||||
let before: Vec<(f64, f64)> = copies.iter().map(|c| centre(&s, *c)).collect();
|
||||
let again = ex(&mut s, "edit.duplicate", json!({}));
|
||||
let next: Vec<NodeId> = again["ids"].as_array().unwrap().iter().map(|v| id_of(v).unwrap()).collect();
|
||||
assert_eq!(next.len(), 2);
|
||||
for (i, c) in next.iter().enumerate() {
|
||||
assert!(near(turn(&s, *c), 30.0 + 30.0 * f64::from(k)), "repeat {k}, layer {i}: rotation {}", turn(&s, *c));
|
||||
let want =
|
||||
figcraft_geom::translation(figcraft_geom::rotate_about(figcraft_geom::Affine::translate((before[i].0, before[i].1)), pivot, 30.0));
|
||||
let got = centre(&s, *c);
|
||||
assert!(near(got.0, want.x) && near(got.1, want.y), "repeat {k}, layer {i}: {got:?} vs {want:?}");
|
||||
}
|
||||
copies = next;
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_flipped_copy_does_not_repeat_a_half_turn() {
|
||||
let mut s = Session::new();
|
||||
let a = rect(&mut s, 0.0, 0.0);
|
||||
ex(&mut s, "select.set", json!({"ids": [a]}));
|
||||
let c1 = cmd_d(&mut s);
|
||||
ex(&mut s, "object.flipH", json!({"ids": [c1]}));
|
||||
let c2 = cmd_d(&mut s);
|
||||
assert!(near(turn(&s, c2), turn(&s, c1)), "rotation {} vs {}", turn(&s, c2), turn(&s, c1));
|
||||
}
|
||||
@@ -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")]
|
||||
|
||||
@@ -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;
|
||||
@@ -459,6 +460,8 @@ mod page_clipboard_tests;
|
||||
#[cfg(test)]
|
||||
mod page_copy_navigation_tests;
|
||||
#[cfg(test)]
|
||||
mod page_opening_tests;
|
||||
#[cfg(test)]
|
||||
mod page_target_tests;
|
||||
#[cfg(test)]
|
||||
mod paint_index_tests;
|
||||
@@ -609,6 +612,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;
|
||||
|
||||
@@ -0,0 +1,175 @@
|
||||
//! `page.setOpening` (#1817): the page a file opens on, for everyone who opens or joins it, written
|
||||
//! as a document change (so it syncs and undoes) without moving anyone's own view.
|
||||
|
||||
use figcraft_doc::NodeId;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::Session;
|
||||
|
||||
fn ex(s: &mut Session, cmd: &str, p: Value) -> Value {
|
||||
s.execute(cmd, &p).unwrap_or_else(|e| panic!("{cmd}: {e}"))
|
||||
}
|
||||
|
||||
fn id_of(v: &Value) -> NodeId {
|
||||
NodeId(v["id"].as_u64().unwrap())
|
||||
}
|
||||
|
||||
/// Setting the opening page writes the document, leaves this viewer where they are, is one undo
|
||||
/// step, and a file opened from that document lands on it.
|
||||
#[test]
|
||||
fn the_opening_page_is_written_without_moving_the_view_and_a_reopened_file_lands_on_it() {
|
||||
let mut s = Session::new();
|
||||
let first = s.page().unwrap();
|
||||
let cover = id_of(&ex(&mut s, "page.add", json!({"name": "Cover"})));
|
||||
ex(&mut s, "page.select", json!({"id": first}));
|
||||
let depth = s.undo_depth().0;
|
||||
ex(&mut s, "page.setOpening", json!({"id": cover}));
|
||||
assert_eq!(s.doc().unwrap().current_page, Some(cover), "written to the document");
|
||||
assert_eq!(s.page().unwrap(), first, "the view stays where it was");
|
||||
assert_eq!(s.undo_depth().0, depth + 1, "one undo step");
|
||||
let reopened = Session::with_document(s.doc().unwrap().clone());
|
||||
assert_eq!(reopened.page().unwrap(), cover, "a file opened from this document lands on it");
|
||||
ex(&mut s, "edit.undo", json!({}));
|
||||
assert_ne!(s.doc().unwrap().current_page, Some(cover), "undone");
|
||||
assert_eq!(Session::with_document(s.doc().unwrap().clone()).page().unwrap(), first);
|
||||
}
|
||||
|
||||
/// Without an id the current page is meant; a divider and a layer are refused and change nothing.
|
||||
#[test]
|
||||
fn the_current_page_is_the_default_and_dividers_and_layers_are_refused() {
|
||||
let mut s = Session::new();
|
||||
let two = id_of(&ex(&mut s, "page.add", json!({"name": "Two"})));
|
||||
assert_eq!(s.page().unwrap(), two, "page.add goes to the new page");
|
||||
ex(&mut s, "page.setOpening", json!({}));
|
||||
assert_eq!(s.doc().unwrap().current_page, Some(two), "the current page when none is named");
|
||||
let divider = id_of(&ex(&mut s, "page.add", json!({"name": "-"})));
|
||||
let r = id_of(&ex(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10})));
|
||||
let (view, depth) = (s.page().unwrap(), s.undo_depth());
|
||||
assert!(s.execute("page.setOpening", &json!({"id": divider})).is_err(), "a divider isn't a page to open on");
|
||||
assert!(s.execute("page.setOpening", &json!({"id": r})).is_err(), "a layer isn't a page");
|
||||
assert_eq!(s.doc().unwrap().current_page, Some(two), "refusals change nothing");
|
||||
assert_eq!(s.page().unwrap(), view, "the viewer's page is where it was");
|
||||
assert_eq!(s.undo_depth(), depth, "and no undo step was added");
|
||||
}
|
||||
|
||||
/// An id that is no node at all errors and changes nothing.
|
||||
#[test]
|
||||
fn an_unknown_id_is_refused_and_changes_nothing() {
|
||||
let mut s = Session::new();
|
||||
let first = s.page().unwrap();
|
||||
let depth = s.undo_depth();
|
||||
assert!(s.execute("page.setOpening", &json!({"id": 987_654_321u64})).is_err(), "no such node");
|
||||
assert_eq!(s.doc().unwrap().current_page, Some(first));
|
||||
assert_eq!(s.undo_depth(), depth);
|
||||
}
|
||||
|
||||
/// Setting the page that already is the opening page changes nothing and adds no undo step.
|
||||
#[test]
|
||||
fn setting_the_page_that_already_opens_the_file_adds_no_undo_step() {
|
||||
let mut s = Session::new();
|
||||
let first = s.page().unwrap();
|
||||
assert_eq!(s.doc().unwrap().current_page, Some(first));
|
||||
ex(&mut s, "page.setOpening", json!({"id": first}));
|
||||
let depth = s.undo_depth();
|
||||
ex(&mut s, "page.setOpening", json!({"id": first}));
|
||||
assert_eq!(s.undo_depth(), depth, "already the opening page: no step");
|
||||
assert_eq!(s.doc().unwrap().current_page, Some(first));
|
||||
}
|
||||
|
||||
/// Deleting the opening page leaves the file opening on a page that exists.
|
||||
#[test]
|
||||
fn deleting_the_opening_page_falls_back_to_a_page_that_exists() {
|
||||
let mut s = Session::new();
|
||||
let first = s.page().unwrap();
|
||||
let cover = id_of(&ex(&mut s, "page.add", json!({"name": "Cover"})));
|
||||
ex(&mut s, "page.setOpening", json!({"id": cover}));
|
||||
ex(&mut s, "page.delete", json!({"id": cover}));
|
||||
let doc = s.doc().unwrap().clone();
|
||||
let now = doc.current_page.expect("an opening page remains");
|
||||
assert!(doc.pages.contains(&now) && now != cover, "a page that exists");
|
||||
assert_eq!(now, first);
|
||||
assert_eq!(Session::with_document(doc).page().unwrap(), first, "a reopened file lands on it");
|
||||
}
|
||||
|
||||
/// The file written by a real save (the serializer, not a cloned document), opened again.
|
||||
fn saved_and_reopened(s: &Session) -> Session {
|
||||
let bytes = crate::cmd::file::file_bytes(s.ds().unwrap()).unwrap();
|
||||
let (doc, _) = figcraft_format::load_bytes(&bytes).unwrap();
|
||||
Session::with_document(doc)
|
||||
}
|
||||
|
||||
/// Saving writes the chosen opening page, not the page the saver was viewing.
|
||||
#[test]
|
||||
fn the_opening_page_survives_a_save_and_reopen_from_another_page() {
|
||||
let mut s = Session::new();
|
||||
let first = s.page().unwrap();
|
||||
let cover = id_of(&ex(&mut s, "page.add", json!({"name": "Cover"})));
|
||||
ex(&mut s, "page.select", json!({"id": first}));
|
||||
ex(&mut s, "page.setOpening", json!({"id": cover}));
|
||||
assert_eq!(s.page().unwrap(), first, "the saver stays on Page 1");
|
||||
assert_eq!(saved_and_reopened(&s).page().unwrap(), cover);
|
||||
}
|
||||
|
||||
/// With no opening page chosen, a file opens on the page it was saved on, as before.
|
||||
#[test]
|
||||
fn without_an_opening_page_a_file_reopens_on_the_page_it_was_saved_on() {
|
||||
let mut s = Session::new();
|
||||
let two = id_of(&ex(&mut s, "page.add", json!({"name": "Two"})));
|
||||
assert_eq!(s.page().unwrap(), two);
|
||||
assert_eq!(saved_and_reopened(&s).page().unwrap(), two);
|
||||
}
|
||||
|
||||
/// A deleted opening page no longer decides: the file opens where it was saved.
|
||||
#[test]
|
||||
fn deleting_the_opening_page_falls_back_to_the_saver_s_page() {
|
||||
let mut s = Session::new();
|
||||
let cover = id_of(&ex(&mut s, "page.add", json!({"name": "Cover"})));
|
||||
let two = id_of(&ex(&mut s, "page.add", json!({"name": "Two"})));
|
||||
ex(&mut s, "page.setOpening", json!({"id": cover}));
|
||||
ex(&mut s, "page.delete", json!({"id": cover}));
|
||||
ex(&mut s, "page.select", json!({"id": two}));
|
||||
assert_eq!(saved_and_reopened(&s).page().unwrap(), two);
|
||||
}
|
||||
|
||||
/// Undoing the choice puts the saver's page back in charge.
|
||||
#[test]
|
||||
fn undoing_the_opening_page_then_saving_reopens_on_the_saver_s_page() {
|
||||
let mut s = Session::new();
|
||||
let cover = id_of(&ex(&mut s, "page.add", json!({"name": "Cover"})));
|
||||
let two = id_of(&ex(&mut s, "page.add", json!({"name": "Two"})));
|
||||
ex(&mut s, "page.setOpening", json!({"id": cover}));
|
||||
ex(&mut s, "edit.undo", json!({}));
|
||||
ex(&mut s, "page.select", json!({"id": two}));
|
||||
assert_eq!(saved_and_reopened(&s).page().unwrap(), two);
|
||||
}
|
||||
|
||||
/// Choosing another opening page takes the choice off the first.
|
||||
#[test]
|
||||
fn setting_another_opening_page_clears_the_first() {
|
||||
let mut s = Session::new();
|
||||
let a = id_of(&ex(&mut s, "page.add", json!({"name": "A"})));
|
||||
let b = id_of(&ex(&mut s, "page.add", json!({"name": "B"})));
|
||||
let c = id_of(&ex(&mut s, "page.add", json!({"name": "C"})));
|
||||
ex(&mut s, "page.setOpening", json!({"id": a}));
|
||||
ex(&mut s, "page.setOpening", json!({"id": b}));
|
||||
let flagged: Vec<NodeId> = s.doc().unwrap().pages.iter().copied().filter(|&p| opening(&s, p)).collect();
|
||||
assert_eq!(flagged, vec![b]);
|
||||
ex(&mut s, "page.select", json!({"id": c}));
|
||||
assert_eq!(saved_and_reopened(&s).page().unwrap(), b);
|
||||
}
|
||||
|
||||
/// A copy of the opening page is just a page.
|
||||
#[test]
|
||||
fn a_duplicated_opening_page_is_not_an_opening_page() {
|
||||
let mut s = Session::new();
|
||||
let a = id_of(&ex(&mut s, "page.add", json!({"name": "A"})));
|
||||
ex(&mut s, "page.setOpening", json!({"id": a}));
|
||||
let copy = id_of(&ex(&mut s, "page.duplicate", json!({"id": a})));
|
||||
assert_ne!(copy, a);
|
||||
assert!(opening(&s, a));
|
||||
assert!(!opening(&s, copy));
|
||||
}
|
||||
|
||||
fn opening(s: &Session, p: NodeId) -> bool {
|
||||
matches!(s.doc().unwrap().get(p).map(|n| &n.kind), Ok(figcraft_doc::NodeKind::Page { opening: true, .. }))
|
||||
}
|
||||
@@ -2,3 +2,4 @@ pub mod rename;
|
||||
pub mod selection_colors;
|
||||
pub mod selection_reorder;
|
||||
pub mod selection_spacing;
|
||||
pub mod tidy;
|
||||
@@ -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<f64>, snap: bool) -> Vec<Move> {
|
||||
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<Item>, Shape)> {
|
||||
let mut seen = BTreeSet::new();
|
||||
let ids: Vec<NodeId> = 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<Shape> {
|
||||
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<Vec<Item>> {
|
||||
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<Item>> = 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<Item>], rows: &[Vec<Item>]) -> 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>) -> 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::<f64>() / 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<f64>) -> Vec<Move> {
|
||||
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<f64> = 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<f64> = 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<Item>], vertical: bool) -> Vec<f64> {
|
||||
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<Item>], vertical: bool, spacing: Option<f64>, snap: bool) -> Vec<Move> {
|
||||
let boxes: Vec<(f64, f64)> = units.iter().map(|u| unit_box(u, vertical)).collect();
|
||||
let across: Vec<f64> = 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
|
||||
}
|
||||
@@ -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");
|
||||
}
|
||||
@@ -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<NodeId>) -> 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.
|
||||
|
||||
@@ -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<NodeId> {
|
||||
xs.iter().map(|x| make(s, *x, 0.0, 50.0, 50.0)).collect()
|
||||
}
|
||||
fn xs_of(s: &Session, ids: &[NodeId]) -> Vec<f64> {
|
||||
ids.iter().map(|i| xy(s, *i).0).collect()
|
||||
}
|
||||
|
||||
fn row(s: &mut Session, xs: [f64; 4]) -> Vec<NodeId> {
|
||||
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<NodeId> {
|
||||
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<NodeId> = 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<NodeId> = (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<figcraft_geom::Rect> { [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<NodeId> {
|
||||
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.]);
|
||||
}
|
||||
@@ -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"
|
||||
@@ -1404,6 +1405,7 @@ name = "English"
|
||||
"Server for online sharing" = "Server for online sharing"
|
||||
"Server key" = "Server key"
|
||||
"Set as default" = "Set as default"
|
||||
"Set as opening page" = "Set as opening page"
|
||||
"Set corner smoothing to 60%" = "Set corner smoothing to 60%"
|
||||
"Set variable" = "Set variable"
|
||||
"Set variable mode" = "Set variable mode"
|
||||
@@ -1628,6 +1630,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"
|
||||
|
||||
@@ -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").
|
||||
|
||||
@@ -206,6 +206,13 @@ pub fn gradient_dragging(ctx: &egui::Context) -> bool {
|
||||
matches!(ctx.data(|d| d.get_temp::<Drag>(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>(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())
|
||||
|
||||
@@ -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));
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
@@ -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<egui::accesskit::Node> =
|
||||
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");
|
||||
}
|
||||
@@ -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<usize>) -> figcraft_color::ImagePaint {
|
||||
let n = u.app.session.doc().unwrap().node(id).unwrap();
|
||||
|
||||
@@ -594,23 +594,40 @@ fn group_rows(app: &mut FigApp, ui: &mut Ui, view: &View, coll: &Collection, st:
|
||||
}
|
||||
}
|
||||
|
||||
/// Rename the last part of group `g` of a collection (its variables `members`) to `new`: every
|
||||
/// variable under it moves along (one undo step).
|
||||
fn rename_group(app: &mut FigApp, members: &[&Variable], g: &str, new: &str, st: &mut Editor) {
|
||||
let new = new.trim().replace('/', "-");
|
||||
/// What renaming group `g` (of the variables `members`) to `new` does: the group's new path and
|
||||
/// each moved variable's (id, new name). `new` replaces the group's last part; a `/` in it nests
|
||||
/// the group, as in Figma ("Palette/Orange" puts it in a group Palette, made if there is none).
|
||||
/// Each part is trimmed and empty parts are dropped. The renames come deepest name first, so a
|
||||
/// variable moving into the group's own new path ("Orange" to "Orange/Warm") never takes a name
|
||||
/// another moved variable still holds. None when nothing changes.
|
||||
fn group_renames(members: &[&Variable], g: &str, new: &str) -> Option<(String, Vec<(String, String)>)> {
|
||||
let new = new.split('/').map(str::trim).filter(|p| !p.is_empty()).collect::<Vec<_>>().join("/");
|
||||
if new.is_empty() {
|
||||
return;
|
||||
return None;
|
||||
}
|
||||
let renamed = match g.rsplit_once('/') {
|
||||
Some((parent, _)) => format!("{parent}/{new}"),
|
||||
None => new,
|
||||
};
|
||||
if renamed == g {
|
||||
return None;
|
||||
}
|
||||
let prefix = format!("{g}/");
|
||||
let mut moved: Vec<(&Variable, &str)> = members.iter().filter_map(|v| Some((*v, v.name.strip_prefix(&prefix)?))).collect();
|
||||
// A longer name can only be one a shorter one moves to: rename those out of the way first.
|
||||
moved.sort_by_key(|(_, rest)| std::cmp::Reverse(rest.len()));
|
||||
Some((renamed.clone(), moved.into_iter().map(|(v, rest)| (v.id.clone(), format!("{renamed}/{rest}"))).collect()))
|
||||
}
|
||||
|
||||
/// Rename group `g` of a collection (its variables `members`) to `new` (see [`group_renames`]):
|
||||
/// every variable under it moves along, in one undo step.
|
||||
fn rename_group(app: &mut FigApp, members: &[&Variable], g: &str, new: &str, st: &mut Editor) {
|
||||
let Some((renamed, moves)) = group_renames(members, g, new) else {
|
||||
return;
|
||||
};
|
||||
let steps: Vec<serde_json::Value> =
|
||||
moves.iter().map(|(id, name)| json!({"command": "variable.update", "params": {"variable": id, "name": name}})).collect();
|
||||
let prefix = format!("{g}/");
|
||||
let steps: Vec<serde_json::Value> = members
|
||||
.iter()
|
||||
.filter(|v| v.name.starts_with(&prefix))
|
||||
.map(|v| json!({"command": "variable.update", "params": {"variable": v.id, "name": format!("{renamed}/{}", &v.name[prefix.len()..])}}))
|
||||
.collect();
|
||||
if app.run("command.batch", json!({"label": "Rename group", "commands": steps})).is_some()
|
||||
&& st.group.as_deref().is_some_and(|s| s == g || s.starts_with(&prefix))
|
||||
{
|
||||
@@ -1308,7 +1325,7 @@ fn bulk_details(app: &mut FigApp, ctx: &Context, vars: &Variables, st: &mut Edit
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{groups, tri};
|
||||
use super::{group_renames, groups, tri};
|
||||
|
||||
#[test]
|
||||
fn tri_is_checked_empty_or_mixed() {
|
||||
@@ -1330,4 +1347,47 @@ mod tests {
|
||||
assert_eq!(groups(names.into_iter()), ["color", "color/brand", "space"]);
|
||||
assert!(groups(["a", "b"].into_iter()).is_empty());
|
||||
}
|
||||
|
||||
/// The renames of group `g` among `names` (numbers in one collection) typed as `new`, by name.
|
||||
fn renames(names: &[&str], g: &str, new: &str) -> Option<(String, Vec<(String, String)>)> {
|
||||
let mut s = figcraft_engine::Session::new();
|
||||
s.execute("variable.createCollection", &serde_json::json!({"name": "Theme"})).unwrap();
|
||||
for n in names {
|
||||
s.execute("variable.create", &serde_json::json!({"collection": "Theme", "name": n, "type": "number", "value": 1})).unwrap();
|
||||
}
|
||||
let vars = &s.doc().unwrap().variables.variables;
|
||||
let members: Vec<_> = vars.iter().collect();
|
||||
let (renamed, moves) = group_renames(&members, g, new)?;
|
||||
let by_name = |id: &str| vars.iter().find(|v| v.id == id).unwrap().name.clone();
|
||||
Some((renamed, moves.into_iter().map(|(id, n)| (by_name(&id), n)).collect()))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_slash_in_a_group_rename_nests_the_group_keeping_its_parent() {
|
||||
let pair = |a: &str, b: &str| (a.to_string(), b.to_string());
|
||||
assert_eq!(
|
||||
renames(&["Orange/100", "Orange/200", "Blue/100"], "Orange", "Palette/Orange"),
|
||||
Some(("Palette/Orange".into(), vec![pair("Orange/100", "Palette/Orange/100"), pair("Orange/200", "Palette/Orange/200")]))
|
||||
);
|
||||
assert_eq!(
|
||||
renames(&["a/b/x"], "a/b", " / Warm // c / "),
|
||||
Some(("a/Warm/c".into(), vec![pair("a/b/x", "a/Warm/c/x")])),
|
||||
"parts are trimmed, empty parts dropped, and the parent stays"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_group_rename_to_nothing_or_to_itself_does_nothing() {
|
||||
for new in ["", " ", "/", " / // ", "Orange", " Orange ", "/Orange/"] {
|
||||
assert_eq!(renames(&["Orange/100"], "Orange", new), None, "{new:?}");
|
||||
}
|
||||
assert_eq!(renames(&["a/b/x"], "a/b", "b/"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_group_moved_into_its_own_subgroup_renames_the_deeper_names_first() {
|
||||
let (_, moves) = renames(&["Orange/100", "Orange/Warm/100"], "Orange", "Orange/Warm").unwrap();
|
||||
let order: Vec<&str> = moves.iter().map(|(old, _)| old.as_str()).collect();
|
||||
assert_eq!(order, ["Orange/Warm/100", "Orange/100"]);
|
||||
}
|
||||
}
|
||||
@@ -643,6 +643,50 @@ fn the_page_menus_rename_starts_with_the_keyboard_in_the_name() {
|
||||
assert_clicking_page_opens_it(&mut u, p2, p1, r2);
|
||||
}
|
||||
|
||||
/// Right-clicks `at` in the pages list and returns the menu's "Set as opening page" item, if shown.
|
||||
fn opening_item(u: &mut Ui, at: Pos2) -> Option<Pos2> {
|
||||
u.frame(vec![
|
||||
Event::PointerMoved(at),
|
||||
Event::PointerButton { pos: at, button: egui::PointerButton::Secondary, pressed: true, modifiers: Modifiers::NONE },
|
||||
]);
|
||||
u.frame(vec![Event::PointerButton { pos: at, button: egui::PointerButton::Secondary, pressed: false, modifiers: Modifiers::NONE }]);
|
||||
let shapes: Vec<egui::Shape> = u.frame_output(vec![]).shapes.into_iter().map(|c| c.shape).collect();
|
||||
crate::live_tests::has_text(&shapes, "Set as opening page").then(|| crate::live_tests::text_center(&shapes, "Set as opening page"))
|
||||
}
|
||||
|
||||
/// The pages list's menu offers "Set as opening page" on a page and not on a divider, and using it
|
||||
/// writes the document's opening page without moving the viewer's own page (#1817).
|
||||
#[test]
|
||||
fn the_page_menu_sets_the_opening_page_and_not_on_dividers() {
|
||||
let mut s = Session::new();
|
||||
let p1 = s.page().unwrap();
|
||||
let p2 = id(s.execute("page.add", &json!({})).unwrap());
|
||||
let div = id(s.execute("page.add", &json!({"name": "-"})).unwrap());
|
||||
s.execute("page.move", &json!({"id": div, "index": 1})).unwrap();
|
||||
s.execute("page.select", &json!({"id": p1})).unwrap();
|
||||
let mut u = Ui::new(s);
|
||||
let (r1, r2) = (page_row(&mut u, p1, p2), page_row(&mut u, p2, p1));
|
||||
let mid = Pos2::new(r1.x, (r1.y + r2.y) / 2.0);
|
||||
u.app.session.execute("page.select", &json!({"id": p1})).unwrap();
|
||||
u.frame(vec![]);
|
||||
assert_eq!(opening_item(&mut u, mid), None, "a divider has no such item");
|
||||
u.frame(vec![Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }]);
|
||||
for _ in 0..5 {
|
||||
u.frame(vec![]);
|
||||
}
|
||||
let item = opening_item(&mut u, r2).expect("a page has the item (and its menu is open)");
|
||||
assert_ne!(u.app.session.doc().unwrap().current_page, Some(p2), "not the opening page yet");
|
||||
u.frame(vec![Event::PointerMoved(item)]);
|
||||
u.button(item, true);
|
||||
u.button(item, false);
|
||||
for _ in 0..3 {
|
||||
u.frame(vec![]);
|
||||
}
|
||||
assert_eq!(u.app.session.doc().unwrap().current_page, Some(p2), "the document's opening page is the clicked page");
|
||||
assert_eq!(u.app.session.page().unwrap(), p1, "the viewer's own page stays");
|
||||
assert!(u.app.ui.last_error.is_none(), "{:?}", u.app.ui.last_error);
|
||||
}
|
||||
|
||||
/// The y of the line between the pages and the layers, above the layers' row at `layer` (found by
|
||||
/// the resize cursor it shows when hovered).
|
||||
fn pages_edge_at(u: &mut Ui, layer: f32) -> f32 {
|
||||
@@ -841,3 +885,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");
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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())
|
||||
|
||||
@@ -333,6 +333,13 @@ fn pages(app: &mut FigApp, ui: &mut Ui) {
|
||||
}
|
||||
ui.close();
|
||||
}
|
||||
// The page the file opens on, for everyone (#1817); a divider can't be one.
|
||||
if !divider && ui.button(tr("Set as opening page")).clicked() {
|
||||
if !crate::menus::dev_mode_refuses(app, "page.setOpening") {
|
||||
app.run("page.setOpening", json!({"id": id}));
|
||||
}
|
||||
ui.close();
|
||||
}
|
||||
if ui.button(tr("Delete page")).clicked() {
|
||||
if !crate::menus::dev_mode_refuses(app, "page.delete") {
|
||||
delete_page(app, id);
|
||||
@@ -1241,7 +1248,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 +1270,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) {
|
||||
|
||||
@@ -614,6 +614,8 @@ fn position(app: &mut FigApp, ui: &mut Ui, doc: &Arc<Document>, shown: &Arc<Docu
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub(crate) struct PositionValues {
|
||||
pub can_align: bool,
|
||||
/// Align is off because the one selected layer is placed by its auto layout frame.
|
||||
pub align_blocked: bool,
|
||||
pub x: Option<f64>,
|
||||
pub y: Option<f64>,
|
||||
pub rot: Option<f64>,
|
||||
@@ -644,6 +646,7 @@ pub(crate) fn position_values(ctx: &egui::Context, doc: &Arc<Document>, 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<Document>, 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<Document>, 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<Document>, 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<Document>, 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();
|
||||
}
|
||||
|
||||
@@ -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<NodeId> = 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");
|
||||
}
|
||||
@@ -332,6 +332,87 @@ fn a_second_duplicate_group_takes_the_next_free_name() {
|
||||
assert_eq!(n.len(), 6);
|
||||
}
|
||||
|
||||
/// A collection with the variables `names` (numbers).
|
||||
fn named_window(names: &[&str]) -> Ui {
|
||||
let mut s = Session::new();
|
||||
s.execute("variable.createCollection", &json!({"name": "Theme"})).unwrap();
|
||||
for n in names {
|
||||
s.execute("variable.create", &json!({"collection": "Theme", "name": n, "type": "number", "value": 1})).unwrap();
|
||||
}
|
||||
let mut u = Ui::new(s);
|
||||
u.app.ui.variables = Some(Default::default());
|
||||
for _ in 0..10 {
|
||||
u.frame(vec![]);
|
||||
}
|
||||
u
|
||||
}
|
||||
|
||||
/// Right-click the group row `name`, choose Rename group, type `to` and press Enter.
|
||||
fn rename_group(u: &mut Ui, name: &str, to: &str) {
|
||||
let p = row(u, name);
|
||||
click(u, p, PointerButton::Secondary, Modifiers::NONE);
|
||||
let menu = flat(&u.frame_output(vec![]).shapes);
|
||||
click(u, text_center(&menu, "Rename group"), PointerButton::Primary, Modifiers::NONE);
|
||||
u.frame(vec![Event::Text(to.into())]);
|
||||
for pressed in [true, false] {
|
||||
u.frame(vec![Event::Key { key: Key::Enter, physical_key: None, pressed, repeat: false, modifiers: Modifiers::NONE }]);
|
||||
}
|
||||
for _ in 0..5 {
|
||||
u.frame(vec![]);
|
||||
}
|
||||
}
|
||||
|
||||
fn sorted_names(u: &Ui) -> Vec<String> {
|
||||
let mut n = names(u);
|
||||
n.sort();
|
||||
n
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn renaming_a_group_with_a_slash_nests_it_in_a_new_parent_group_in_one_undo_step() {
|
||||
let mut u = named_window(&["Orange/100", "Orange/200", "Blue/100"]);
|
||||
let before = u.app.session.undo_labels(100).len();
|
||||
rename_group(&mut u, "Orange", "Palette/Orange");
|
||||
assert!(u.app.ui.last_error.is_none(), "{:?}", u.app.ui.last_error);
|
||||
assert_eq!(sorted_names(&u), ["Blue/100", "Palette/Orange/100", "Palette/Orange/200"]);
|
||||
assert_eq!(u.app.session.undo_labels(100).len(), before + 1, "one undo step");
|
||||
assert_eq!(u.app.session.undo_labels(1), ["Rename group"]);
|
||||
// The sidebar lists Palette with Orange indented under it.
|
||||
let shapes = flat(&u.frame_output(vec![]).shapes);
|
||||
let (parent, child) = (text_center(&shapes, "Palette"), text_center(&shapes, "Orange"));
|
||||
assert!(child.y > parent.y && child.x > parent.x, "Orange is indented under Palette: {parent:?} {child:?}");
|
||||
assert!(!has_text(&shapes, "Palette-Orange"));
|
||||
u.app.session.undo().unwrap();
|
||||
assert_eq!(sorted_names(&u), ["Blue/100", "Orange/100", "Orange/200"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_nested_groups_new_path_stays_in_its_parent_and_drops_empty_parts() {
|
||||
let mut u = named_window(&["Palette/Orange/100", "Palette/Orange/200"]);
|
||||
rename_group(&mut u, "Orange", " /Warm // Orange / ");
|
||||
assert!(u.app.ui.last_error.is_none(), "{:?}", u.app.ui.last_error);
|
||||
assert_eq!(sorted_names(&u), ["Palette/Warm/Orange/100", "Palette/Warm/Orange/200"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn renaming_a_group_into_its_own_new_subgroup_moves_the_deeper_names_first() {
|
||||
// Orange/100 takes Orange/Warm/100, which itself moves on to Orange/Warm/Warm/100.
|
||||
let mut u = named_window(&["Orange/100", "Orange/Warm/100"]);
|
||||
rename_group(&mut u, "Orange", "Orange/Warm");
|
||||
assert!(u.app.ui.last_error.is_none(), "{:?}", u.app.ui.last_error);
|
||||
assert_eq!(sorted_names(&u), ["Orange/Warm/100", "Orange/Warm/Warm/100"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_group_rename_onto_a_variable_name_that_stays_changes_nothing() {
|
||||
// The longer name moves first, whatever the order of the variables: Orange/1000 moves, then
|
||||
// Orange/200 collides, and the move already made is undone.
|
||||
let mut u = named_window(&["Orange/1000", "Orange/200", "Palette/Orange/200"]);
|
||||
rename_group(&mut u, "Orange", "Palette/Orange");
|
||||
assert!(u.app.ui.last_error.as_deref().is_some_and(|e| e.contains("Palette/Orange/200")), "{:?}", u.app.ui.last_error);
|
||||
assert_eq!(sorted_names(&u), ["Orange/1000", "Orange/200", "Palette/Orange/200"]);
|
||||
}
|
||||
|
||||
fn open_edit_variables(u: &mut Ui) -> Vec<egui::Shape> {
|
||||
let menu = select_three_and_open_menu(u);
|
||||
assert!(has_text(&menu, "Edit variables"), "the bulk menu offers Edit variables");
|
||||
|
||||
@@ -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<Rect> = app.ui.picker_button.into_iter().collect();
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Collaboration parity
|
||||
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-06 · **Change:** minor (M9: a joined live session reconnects until you leave and says when it is disconnected, and joining it again merges what you did while disconnected; ; a file shared on the local network can be shared to look at only: a view-only code next to the edit code, picked in the Share popover before or while sharing)
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-06 · **Change:** minor (a shared file's opening page can be set (`page.setOpening`, Set as opening page in the pages list) and syncs to everyone who joins afterwards (#1817); numbers unchanged) · **Target:** Figma Design (desktop app 126.10.7); M9: a joined live session reconnects until you leave and says when it is disconnected, and joining it again merges what you did while disconnected; ; a file shared on the local network can be shared to look at only: a view-only code next to the edit code, picked in the Share popover before or while sharing)
|
||||
|
||||
Figma is multiplayer first; FigCraft is local first. **Ready ~13% (estimated):** comments, version
|
||||
history and branches (review and merge) work inside one file; the real-time collaboration core landed in #103 (sync model,
|
||||
@@ -15,6 +15,7 @@ cursors, selections, text carets, cursor chat and spotlights shown live ([`colla
|
||||
| Real-time co-editing | yes | **core built, no networking** (#103): client-scoped ids, per-property change sets with fractional positions, server ordering and validation, optimistic clients, binary messages; randomized multi-client convergence tests over real commands. Live sessions over the network landed (`crates/collab-net`): the WebSocket transport (keep-alive, size and rate limits, a live connection reconnecting until you leave, and rejoining with offline edits merged), hosting from the app (this machine or the local network) with invite links, live cursors with name tags, selections, avatars and follow, `collab.*` commands. Document sync between apps works over them (the host's server orders every batch; guests open the host's file as a new tab). Sessions are per document: each open file has its own or none, several run at once (host one, join another, publish a third) and keep syncing behind the tab in front, and closing a file ends its session only. Revert to saved is refused until the document leaves its live session; its access checks and sync association stay intact. Undo is per person (only your own steps, others' later writes left alone), refused edits roll back with a toast, and a reconnect resumes as the same client with what it missed (or a snapshot) and sends what was made offline. The browser build joins (same messages through the browser's WebSocket API); `figcraft://` invite links open the desktop app and join. Styles, variables, collections, modes and comments made in a session take ids from their creator's space (the server checks it), so concurrent creations all survive; modes, per-mode values and replies inside one entry still resolve last-writer-wins. A standalone `figcraft-server` keeps many files, persists them (a snapshot plus a log, compacted), loses nothing confirmed across a restart (apps resume as the same participants) and takes files published from the app (File ▸ Publish to server…). The desktop app and the CLI open `wss://` links too (TLS through a reverse proxy), and releases ship the server for Linux with a deployment guide (systemd, Caddy, nginx, Docker) and `install.sh`. A server can be open to the public: anyone publishes without the key, within limits per address, and files nobody opens expire. Message limits follow the server's `max_file_mb`, so files above 64 MiB publish and open (the client takes at most 1 GiB from a server, and the server warns when large limits meet open publishing, #705); a damaged generation field in a file's log no longer drops the edits flushed to it (#687). Image entries are checked as they apply: a key must be a plain name (letters, digits, `-`, `_`; it becomes `images/<key>` in a saved file), bytes under a content-hash key must hash to it (lowercase sha256), a side is at most 65 535 px and the decoded bytes at most 256 MiB (what the importers read), a key's bytes can't be replaced and an image a layer shows can't be removed, so no collaborator can poison the shared image store or balloon memory; snapshots and server logs from before these checks open without the images they refuse (#1086). The batches kept for apps that reconnect are bounded in bytes by default (64 MiB; `max_log_mb` on `figcraft-server`), and an app further behind catches up with a snapshot (#1069). Placing a layer among its siblings is a binary search, so large pastes and reorders in one batch no longer take quadratic time (#1065). A refused batch's fixes take time linear in the batch: each deleted layer is restored once and each entry fix looked up once (#1063). Left: server archives beyond Linux | 25–55 |
|
||||
| Live cursors, selections, viewports; follow / observation mode; spotlight | yes | **done, in live sessions**: named cursors (one name for live sessions and comments: Preferences ▸ Your name, also in the Share popover and the Join dialog, kept in the browser too; a rename shows at once in the sessions you're in, #1380), selection outlines, avatars (an AI agent attached over MCP also shows its avatar and an outline around the layers it last edited or selected while it works, in or out of a session, #1416), follow (click an avatar), others' text carets and selected characters with their names, a note when two people type in one layer; spotlight (your avatar's menu, `collab.spotlight`): everyone follows your view and page, people who join later too, anyone who moves their view stops following and a banner offers to follow again, a newer spotlight takes over. Left: polish (no accounts, so anyone in the session can spotlight) | 2–4 |
|
||||
| Cursor chat, audio, high-fives | yes | **partial, in live sessions**: cursor chat (`/` opens a bubble at your pointer; everyone sees it as you type, it fades a few seconds after the last change, Enter sends and Escape takes it back, 100 characters; `collab.cursorChat` for agents); sent as ephemeral presence the host checks and rate-limits, never stored. No audio, high-fives or emote reactions | 2–5 |
|
||||
| Opening page of a shared file | the page a link names, else the first | **partial**: a file joined from a server opens on its opening page, which is the open document's current page: the page the file was opened on (the page stored in the file when it was opened, else the first page) until someone sets one, not always the first page; a later page switch, a save on another page or publishing does not move it (a local save stamps the page being viewed into the saved file's bytes for the next time that file is opened, but does not change the open document's opening page, which is the synced property, and a link cannot name a page; `page.setOpening {id?}` (the pages list's Set as opening page, the MCP server too) writes it as a document change, one undo step, so everyone who joins afterwards lands on it, unless a spotlight is on, in which case they follow the spotlighter's page instead; each viewer's own page stays their own (#1817) | — |
|
||||
| Share links, permissions (view / edit), teams and projects | yes | **partial**: sharing with a join code from the Share popover (online: the file goes to the server in Preferences and the server names its edit, comment and view links with short codes; local network: the app hosts and the code carries its address, with an edit code and a view-only code, picked before or while sharing, whose holders see every change and can't make one; one field joins with a code or a link, in the popover and on the home screen, and the Join dialog then shows the join until its file is ready (Cancel), or why it failed (Try again, #1381); the browser build also joins from a link in its URL's fragment, `#join=…`, which never reaches the web host's logs, capped at 6 KiB and checked like a `figcraft://` link (#712; unit-tested, not run in a browser), and shares online and publishes to a server as the desktop app does, though not on the local network (#917; the owner token of a file it puts on an open server lasts as long as the page)); `figcraft-server` share links per file with edit, comment or view access (a viewer sees changes and presence, a "View only" badge and only the moving tools; a commenter also adds, replies to, reacts to and resolves comment threads, with a "Can comment" badge and the comment tool, #1525; the server refuses their other edits), revocable at once, tokens stored as hashes; managed from the app's Share popover (first links), the server's command line or a managing connection. On a server open to the public, whoever published a file manages it with its owner token (links, name, removal: `collab.manageFile`), which the app remembers: Home ▸ Online lists your online files (open again as owner, start and stop sharing, copy the code, rename, remove, forget), with one request per server for what became of them; anyone in a file can report it, and the operator blocks addresses. The person hosting a session, or a file's owner, removes someone from it (right-click their avatar, `collab.removePerson`): they are disconnected and their address can't join that file again while it runs. The list is per computer; a server only a team reaches can also list the files shared from it now for everyone (`team_files`): Home ▸ Online shows that team list for the server in Preferences, a row joins its file, and its links (`figcraft://join?server=…&file=…&team=1`, or the browser build's) carry no secret and stop working with the share. No accounts, teams or projects | 8–17 |
|
||||
| Comments: pins on frames and layers, threads, reactions, @mentions, resolve, unread, search and filters, links, in the presenter | yes (shared) | **done, local**: stored in the file, your name from Preferences (an AI agent attached over MCP comments as its own name, marked Agent); a behaviour suite from the documentation (pinning and following layers, threads, own edits and deletes, mentions, reactions, C and Shift+C, stepping, filters, saving, copy and paste); restoring a version keeps them. `comment.list` (CLI, MCP) gives each message its `mentions` (`{name, known, you}`, by the highlighting rule). In a live session threads sync and anyone in it can reply, react and resolve (no accounts: a name is who you are) | (shared once multiplayer lands) |
|
||||
| Version history: named versions, autosave checkpoints, view before restore, restore, duplicate | yes (cloud) | **done**, saved in the `.figcraft` file: restoring keeps the replaced design as an autosave first, a titled autosave becomes a named version, merging a branch records the file before and after. Versions are per person in a live session (a shared history needs accounts); no comparing two versions (Developer Mode compares a ready-for-dev layer with its state when marked) | — |
|
||||
@@ -26,6 +27,8 @@ cursors, selections, text carets, cursor chat and spotlights shown live ([`colla
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-11-06 | minor | M9, #1972 review: the opening-page row said **done** but the default differs from the reference. With no opening page set, a file opens on the page that was current when it was saved or published (`Document::current_page`, written by save), which can be any page, where the reference opens on the first page, and a link cannot name a page. Regraded **partial**; setting the opening page is unchanged. Numbers unchanged. |
|
||||
| 2026-11-04 | minor | M9, #1817: a file on a server opened on the page that was current at publish time, with no way to change it: `DocProp::CurrentPage` was synced but nothing wrote it. `page.setOpening {id?}` (the pages list's "Set as opening page", the MCP server too) writes the opening page as a document change, one undo step, so everyone who joins afterwards lands on it; a divider is refused; nobody's own page moves. Tests: `page_opening_tests`, `collab_live_tests::the_opening_page_syncs_and_moves_no_ones_view`. Numbers unchanged. |
|
||||
| 2026-11-04 | minor | M9: a session you joined no longer turns into a local file by itself. A dropped connection reconnects until you leave (a minute's pause after each 12 attempts, a pause Retry now skips); only the host ending the session and refusals that are for good stop it; queued messages go out paced. While disconnected the tab shows a red mark and a strip across the canvas says so; a session that ended stays on its tab with Try again, Save a copy and Dismiss |
|
||||
| 2026-11-04 | minor | M9: joining a session again merges what you did while disconnected as one undoable edit, through the three-way merge branches use, as the same client when the server still knows it. What conflicts keeps the other person's, and your whole version opens beside it as an unsaved copy. A server that no longer knows you merges the same way instead of discarding unconfirmed work |
|
||||
| 2026-11-06 | patch | M9, #2026: one conflicting auto layout edit added a conflict for every size and place it moved (a padding changed on both sides of a file with one instance gave 10, with 15 instances 138), and a `layout` conflict took all auto layout fields together, so a gap changed only on the branch was lost if main won the padding. `merge::plan` now leaves out values both sides work out for themselves: a hugging frame's or a filling child's size, text sizing to its characters, an auto layout child's place (when both sides turn it the same way) and a value a layer in an instance takes from its main; merging keeps the file merged into's own value and normalising lays it out from the merged inputs. `layout` and `childLayout` merge field by field: a field changed on one side merges, each field changed both ways is its own conflict (`<id>/layout.padding`, shown as auto layout padding with both sides' values). Tests: `branch_tests::one_conflicting_auto_layout_edit_is_one_conflict`, `branch_tests::auto_layout_fields_changed_one_way_survive_a_conflict`, `branch_tests::sizes_auto_layout_works_out_never_conflict`; the merge fuzz test leaves worked-out values out of what each side must show |
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Components, variants, styles and variables parity
|
||||
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-12 · **Change:** minor (a group's context menu in the Local variables window has Duplicate group, a copy named after it plus " 2" holding a copy of every variable, in one undo step (#2084); pages take a variable mode: with nothing selected the Design panel's Page section shows a Variable modes section, Auto or a mode of each collection that has more than one, as the help center says ("Apply variable mode" in the Page section of the right sidebar) (#2215); a text style binds a number variable to its weight (#2174); an instance lists only the properties its variant's layers use and long property names are cut to one line (#2022); with several layers selected the Design panel header's component button offers Create multiple components (#2088); the Local variables window selects several variables (click, Shift+click for a range, Cmd/Ctrl+click to toggle, Escape to clear) and delete, move to a group and scope act on the selected local variables in one undo step (#2002); text styles carry paragraph spacing and indent, the list style and the OpenType features, as the Supported in text styles table of Create and apply text styles says (#1829); a layer's effect binding takes only a field its effect has; Go to main component on an instance of a library component opens the library file in a tab and selects the main there; glass effects take variables; Delete on a layer inside an instance hides it as an override instead of being refused, as the help center says: "Figma will only toggle the layer's visibility instead of removing it"; library analytics list how many layers and files use each style and variable; SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; a collection of this file can be extended (Extend collection on its row, `variable.extendCollection`), its extension following its edits at once, and extended collections extend again in the file; a typed or stored variable, collection or mode id names only the object with that id (#1613); colour variables can be calculated from other colours per mode — `{alpha}` replaces a colour's alpha, `{mix}` blends two — and follow them (#1280); stored variable and collection references keep their identity when another object is named like their id (follow-up to #1542); a component set's property rows fit the 240 px right panel: variant values wrap two to a line there and every + and − stays in view; opening a file contacts no team library server it names until you check it (#1097); an explicit variables file path (`variable.import`, the `variables` of `file.open` and `file.import`) is refused past 256 MiB or when it isn't a regular file, as the sibling `variables.json` already was (part of #1114); component properties keep the order they were made in when one is renamed, and Make slot asks for the slot's name first (#1536, #1537); components can't contain their own instances, directly or through others (#1084); the instance-swap menus have a search field (#1338); an instance-swap property's default menu scrolls (#1338); variables on a text style's fields from the style editor; instance-swap properties in the component playground; duplicating or Alt-dragging a main component makes an instance of it (#892); a bound colour variable's alpha applies once (#802); variables import reads `variables` outside `meta` and warns when it imports none (#790); variant properties reorder by drag; library files saved right after a read are read again; Hide when publishing note corrected; size and resizing overrides of layers inside instances (#731); variables export in the browser as a download; core editor leftovers: component playground, variables inside styles; layers and assets panels behaviour suite and fixes; extended collections tail; styles and variables behaviour suite and fixes; components behaviour suite and fixes; team libraries on the server, library usage and swapping a library; extended collections, variables import/export, gradient stops and variant properties bound to variables) · **Target:** Figma Design (desktop app 126.10.7)
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-14 · **Change:** minor (renaming a variable group to a path with `/` nests it under a parent group instead of turning the slash into a hyphen (#2353); a group's context menu in the Local variables window has Duplicate group, a copy named after it plus " 2" holding a copy of every variable, in one undo step (#2084); pages take a variable mode: with nothing selected the Design panel's Page section shows a Variable modes section, Auto or a mode of each collection that has more than one, as the help center says ("Apply variable mode" in the Page section of the right sidebar) (#2215); a text style binds a number variable to its weight (#2174); an instance lists only the properties its variant's layers use and long property names are cut to one line (#2022); with several layers selected the Design panel header's component button offers Create multiple components (#2088); the Local variables window selects several variables (click, Shift+click for a range, Cmd/Ctrl+click to toggle, Escape to clear) and delete, move to a group and scope act on the selected local variables in one undo step (#2002); text styles carry paragraph spacing and indent, the list style and the OpenType features, as the Supported in text styles table of Create and apply text styles says (#1829); a layer's effect binding takes only a field its effect has; Go to main component on an instance of a library component opens the library file in a tab and selects the main there; glass effects take variables; Delete on a layer inside an instance hides it as an override instead of being refused, as the help center says: "Figma will only toggle the layer's visibility instead of removing it"; library analytics list how many layers and files use each style and variable; SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; a collection of this file can be extended (Extend collection on its row, `variable.extendCollection`), its extension following its edits at once, and extended collections extend again in the file; a typed or stored variable, collection or mode id names only the object with that id (#1613); colour variables can be calculated from other colours per mode — `{alpha}` replaces a colour's alpha, `{mix}` blends two — and follow them (#1280); stored variable and collection references keep their identity when another object is named like their id (follow-up to #1542); a component set's property rows fit the 240 px right panel: variant values wrap two to a line there and every + and − stays in view; opening a file contacts no team library server it names until you check it (#1097); an explicit variables file path (`variable.import`, the `variables` of `file.open` and `file.import`) is refused past 256 MiB or when it isn't a regular file, as the sibling `variables.json` already was (part of #1114); component properties keep the order they were made in when one is renamed, and Make slot asks for the slot's name first (#1536, #1537); components can't contain their own instances, directly or through others (#1084); the instance-swap menus have a search field (#1338); an instance-swap property's default menu scrolls (#1338); variables on a text style's fields from the style editor; instance-swap properties in the component playground; duplicating or Alt-dragging a main component makes an instance of it (#892); a bound colour variable's alpha applies once (#802); variables import reads `variables` outside `meta` and warns when it imports none (#790); variant properties reorder by drag; library files saved right after a read are read again; Hide when publishing note corrected; size and resizing overrides of layers inside instances (#731); variables export in the browser as a download; core editor leftovers: component playground, variables inside styles; layers and assets panels behaviour suite and fixes; extended collections tail; styles and variables behaviour suite and fixes; components behaviour suite and fixes; team libraries on the server, library usage and swapping a library; extended collections, variables import/export, gradient stops and variant properties bound to variables) · **Target:** Figma Design (desktop app 126.10.7)
|
||||
|
||||
Design systems are why teams adopt Figma. **Components: breadth ~96%, ready ~72%. Styles and
|
||||
variables: breadth ~95%, ready ~76% (estimated).** QA'd with a synthetic design system of ~300
|
||||
@@ -81,6 +81,7 @@ updates with overrides kept: `library_tests.rs`, `components_scale_tests.rs`.
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-11-14 | patch | M3, #2353: renaming a group in the Local variables window to a path with `/` nests it, as in Figma: `Orange` renamed to `Palette/Orange` moves its variables to `Palette/Orange/100`… and the sidebar shows Orange indented under a new Palette group, where the slash used to become a hyphen (`Palette-Orange`). The typed path replaces the group's last part (a nested group stays in its parent), each part is trimmed and empty parts are dropped; a rename onto a variable name that stays is refused with nothing changed, and it is one undo step. Tests: `variables_select_tests::renaming_a_group_with_a_slash_nests_it_in_a_new_parent_group_in_one_undo_step` and the group rename tests beside it, `variables_panel::tests`. Grade unchanged. |
|
||||
| 2026-11-07 | minor | M3, #2084: a group's context menu in the Local variables window has Duplicate group (after Rename group, before Delete group). It adds a group named after the original plus " 2" (the next free number when taken: " 3"), whose variables are copies of the originals with the same leaf names, values in every mode, description, scopes, hidden-from-publishing and code syntax, each sent as `variable.duplicate` plus a rename in one `command.batch` labelled Duplicate group, so one undo step. Measured in the incumbent with one mode; an alias to a variable of the same group keeps pointing at the original. Ungroup is not built. Tests: `variables_select_tests` (headless UI). Grade unchanged |
|
||||
| 2026-11-07 | minor | M3, #2082: Edit variables in the context menu of a selection of several local variables opens the reference's compact editor with two tabs: Details holds only Hide from publishing, Scope the scopes every selected variable's type has (All supported properties and one box per scope; a selection that shares none says so). Each box is checked when all selected variables have it, empty when none, and shows a dash when they differ; a click sets it on all (or clears it when checked on all), each change one `command.batch`, so one undo step. Names, descriptions and code syntax stay single-variable, as in the reference. The Scope: menu entries stay. A tri-state `widgets::checkbox_tri` draws the dash. Tests: `variables_select_tests` (headless UI). Grade unchanged |
|
||||
| 2026-11-12 | minor | M7, #2215: pages take a variable mode: with nothing selected the Design panel's Page section shows a Variable modes section, Auto or a mode of each collection that has more than one, as the help center says ("Apply variable mode" in the Page section of the right sidebar) (#2215). The same section the frames' Variable modes use (`variable.setMode` without layers sets the page's mode), one undo step per pick. Binding the page background to a variable is not in the reference and is not offered |
|
||||
|
||||
+6
-3
@@ -691,7 +691,10 @@ on; `key` resolves keys the way the canvas does. Commands behind keys:
|
||||
in the pages list, never opened and holding no layers), `page.list` (each page's `divider`),
|
||||
`page.rename`, `page.move {id, index}`, `page.duplicate` ("Copy of …", after its source, with its colour,
|
||||
flows (starting at the copied frames), prototype settings and guides),
|
||||
`page.delete` (the last page that isn't a divider stays).
|
||||
`page.delete` (the last page that isn't a divider stays), `page.setOpening {id?}` (the page the
|
||||
file opens on for everyone who opens or joins it, the current page when none is named, a divider
|
||||
refused: a document change, so it syncs in a live session and undoes, #1817; the choice is saved
|
||||
with the file and opens it for everyone, whichever page the saver was on).
|
||||
- `component.list`: each component's `folder` (the Assets panel's folders: its page, the frames
|
||||
holding it, then its name's slash parts) and `label` (the name on its tile).
|
||||
- `view.contextMenu` (`Shift+F10`): the selection's context menu, at its layer row when the layers
|
||||
@@ -2084,8 +2087,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
|
||||
|
||||
+12
-4
@@ -1,6 +1,6 @@
|
||||
# UI and interaction parity
|
||||
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-10 · **Change:** minor (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 Line truncated
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-12 · **Change:** minor (Duplicate repeats the last copy's move and its rotation (about the copy's centre, or the selection's centre for several layers), not its size, and forgets the step when the selection changes, measured in Figma's web app on 2026-11-12 (#2293); 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 strLine truncated
|
||||
|
||||
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,8 +69,9 @@ 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) |
|
||||
| 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 move and rotation (the move of its centre in the page frame, then the turn about the copy's own centre, or the selection's centre for several layers; not its size), also after a Duplicate whose copy was moved, as long as the copies stay selected and the selection hasn't changed (measured in Figma's web app, 2026-11-12); 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 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 |
|
||||
@@ -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) |
|
||||
@@ -214,6 +216,11 @@ This audit records candidates for subsequent fixes; their behaviour is unchanged
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 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 |
|
||||
@@ -334,3 +341,4 @@ This audit records candidates for subsequent fixes; their behaviour is unchanged
|
||||
| 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 |
|
||||
| 2026-11-12 | minor | M8, #2293: Duplicate repeats the last copy's move and rotation, not only the shift of its bounds' corner. The step is the move of the copies' centre in the page frame (not turned by the accumulated rotation) plus the turn each copy has over its source, applied about the new copy's centre, or the selection's centre for several layers; size is not stepped; a deselect forgets the step. Measured in Figma's web app on 2026-11-12 (typed and dragged moves and turns, one layer and two). |
|
||||
Reference in new issue
Block a user