diff --git a/.github/workflows/sonarcloud.yml b/.github/workflows/sonarcloud.yml index e78fe1ea3..50616c871 100644 --- a/.github/workflows/sonarcloud.yml +++ b/.github/workflows/sonarcloud.yml @@ -16,6 +16,11 @@ concurrency: jobs: sonarcloud: - # Tracked at @main so org-wide CI improvements propagate without PR churn. - uses: storytold/craft-common-actions/.github/workflows/sonarcloud.yml@main + # Pin the coverage setup that checks out this repo's pinned craft-i18n data. + uses: storytold/craft-common-actions/.github/workflows/sonarcloud.yml@ea24c9c24e1997238334182160f60e602e5bce32 + with: + # The shared coverage archive's shards omit the CLI executable used by integration tests. + # Run this repository's suite in one instrumented job and provide its pinned test data. + shards: 1 + fonts-ref: 37827adc41fd165f9a9234ac40f94dbad353aa69 secrets: inherit diff --git a/Cargo.lock b/Cargo.lock index b7990a4ee..37e09b205 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1134,7 +1134,7 @@ dependencies = [ [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b" +source = "git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280#e98299546f5c5c3c22388d16507f8b5e61a5f280" dependencies = [ "chrono", "dunce", diff --git a/Cargo.toml b/Cargo.toml index 80ca99a27..0d6e387ad 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -43,7 +43,7 @@ craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-l # pull a second egui family version). craft-window = { git = "https://github.com/storytold/craft-libs", rev = "e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545" } # craft-update: app-specific pretend versions apply to startup and manual checks. -craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b", features = ["egui"] } +craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280", features = ["egui"] } # The suite's font store: exact lookup of a missing font in the pinned Google Fonts and Noto # indexes, and checksum-verified installs into the one folder every Craft app reads (craft-libs). craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545" } diff --git a/crates/doc/src/text.rs b/crates/doc/src/text.rs index dafbfb1f3..2ce80a8cf 100644 --- a/crates/doc/src/text.rs +++ b/crates/doc/src/text.rs @@ -276,6 +276,31 @@ pub enum TextDirection { /// Deepest list nesting (levels 0..=MAX_LIST_INDENT). pub const MAX_LIST_INDENT: u8 = 8; +/// For each paragraph, whether it is an item where a list starts counting. Numbers count the items +/// of one list at one level and restart after a plain paragraph, a shallower item or the other +/// kind of list; the first item of such a run starts counting (and takes its own start number). +/// The layout numbers by this rule. +pub fn list_item_starts_counting(lists: &[ParaList]) -> Vec { + let mut run = [ListStyle::None; MAX_LIST_INDENT as usize + 1]; + lists + .iter() + .map(|pl| { + if pl.list == ListStyle::None { + run.fill(ListStyle::None); + return false; + } + let d = usize::from(pl.indent).min(run.len() - 1); + for c in run.iter_mut().skip(d + 1) { + *c = ListStyle::None; + } + let Some(c) = run.get_mut(d) else { return false }; + let starts = *c != pl.list; + *c = pl.list; + starts + }) + .collect() +} + /// One paragraph's list settings and base direction. #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] #[serde(default)] @@ -937,6 +962,24 @@ impl TextData { self.fold_paragraph_lists(); } + /// Keep a start number only on the item where a numbered list starts counting, and give every + /// item that goes on counting 0 (the rule the layout numbers by, [`list_item_starts_counting`]). + /// An imported file may carry the list's start on every line; once the list is split, the + /// items after the split must restart at 1, not at the old start. + pub fn keep_list_starts_where_counting_starts(&mut self) { + if self.paragraphs.iter().all(|p| p.start_offset == 0) { + return; + } + self.fill_paragraphs(); + let starts = list_item_starts_counting(&self.paragraphs); + for (pl, starts) in self.paragraphs.iter_mut().zip(starts) { + if !starts { + pl.start_offset = 0; + } + } + self.fold_paragraph_lists(); + } + /// One style for all paragraphs with no nesting or start folds back into `list`. fn fold_paragraph_lists(&mut self) { if let Some(first) = self.paragraphs.first().copied() @@ -1251,6 +1294,41 @@ mod case_tests { t.clear_list_starts(0, 0); assert_eq!(t.para_list(0).start_offset, 0); } + + #[test] + fn list_starts_stay_only_where_counting_starts() { + use ListStyle::{Bulleted as B, None as P, Numbered as N}; + let pl = |list, indent, start_offset| ParaList { list, indent, start_offset, ..ParaList::default() }; + // (paragraphs, the starts kept, derivation) + let cases: Vec<(Vec, Vec, &str)> = vec![ + (vec![pl(N, 0, 4), pl(N, 0, 4), pl(N, 0, 4)], vec![4, 0, 0], "items that go on counting lose theirs"), + (vec![pl(N, 0, 4), pl(P, 0, 0), pl(N, 0, 6)], vec![4, 0, 6], "a list after a plain paragraph keeps its own"), + (vec![pl(N, 0, 4), pl(B, 0, 0), pl(N, 0, 6)], vec![4, 0, 6], "and one after a bullet item"), + ( + vec![pl(N, 0, 4), pl(N, 1, 2), pl(N, 1, 2), pl(N, 0, 4)], + vec![4, 2, 0, 0], + "a nested level keeps its first item's; the outer count goes on", + ), + (vec![pl(N, 0, 1), pl(N, 1, 2), pl(N, 0, 9), pl(N, 1, 3)], vec![1, 2, 0, 3], "a shallower item starts the deeper count again"), + (vec![pl(N, 255, 4), pl(N, 9, 4), pl(N, 8, 4)], vec![4, 0, 0], "levels past the deepest count as the deepest"), + ]; + for (paragraphs, want, why) in cases { + let characters = vec!["x"; paragraphs.len()].join("\n"); + let mut t = TextData { characters, paragraphs, ..TextData::new("") }; + t.keep_list_starts_where_counting_starts(); + let got: Vec = (0..t.paragraph_count()).map(|p| t.para_list(p).start_offset).collect(); + assert_eq!(got, want, "{why}"); + } + // No start anywhere: nothing is spelled out. + let mut t = TextData { list: N, ..TextData::new("a\nb") }; + t.keep_list_starts_where_counting_starts(); + assert!(t.paragraphs.is_empty()); + // More entries than paragraphs, and an empty last paragraph. + let mut t = TextData { paragraphs: vec![pl(N, 0, 4); 5], ..TextData::new("a\n") }; + t.keep_list_starts_where_counting_starts(); + assert_eq!((t.para_list(0).start_offset, t.para_list(1).start_offset), (4, 0)); + assert!(list_item_starts_counting(&[]).is_empty()); + } } #[cfg(test)] diff --git a/crates/engine/src/board_mindmap_tests.rs b/crates/engine/src/board_mindmap_tests.rs index 19bb459ae..fa717b8eb 100644 --- a/crates/engine/src/board_mindmap_tests.rs +++ b/crates/engine/src/board_mindmap_tests.rs @@ -383,3 +383,41 @@ fn the_caps_refuse_what_is_too_far_and_cut_what_is_too_long() { assert_eq!(text_data(&s, id(&out, "id")).characters.chars().count(), 500); assert_eq!(text_data(&s, id(&out["children"][0], "id")).characters.chars().count(), 500); } + +/// Where a node's own origin (the place `x`/`y` name) is on the page. +fn origin(s: &Session, n: NodeId) -> Point { + s.doc().unwrap().world_transform(n) * Point::new(0.0, 0.0) +} + +#[test] +fn a_mind_map_in_a_section_without_a_place_is_centred_on_the_view() { + let mut s = board(); + let (vx, vy) = { + let v = &s.ds().unwrap().view; + (v.cx, v.cy) + }; + let sec = id(&s.execute("node.create", &json!({"type": "section", "x": 1000, "y": 500, "width": 4000, "height": 4000})).unwrap(), "id"); + let out = s.execute("board.mindMap", &json!({"parent": sec})).unwrap(); + let c = origin(&s, id(&out, "id")); + assert!(same(c.x, vx) && same(c.y, vy), "the root's place {c:?} is the view's centre ({vx}, {vy})"); +} + +#[test] +fn a_mind_map_in_a_turned_frame_without_a_place_is_centred_on_the_view_and_a_given_place_is_the_frames() { + let mut s = board(); + let (vx, vy) = { + let v = &s.ds().unwrap().view; + (v.cx, v.cy) + }; + let fr = id(&s.execute("node.create", &json!({"type": "frame", "x": 300, "y": 200, "width": 2000, "height": 2000})).unwrap(), "id"); + s.execute("node.set", &json!({"id": fr, "props": {"rotation": 30}})).unwrap(); + let out = s.execute("board.mindMap", &json!({"parent": fr})).unwrap(); + let c = origin(&s, id(&out, "id")); + assert!(same(c.x, vx) && same(c.y, vy), "the root's place {c:?} is the view's centre ({vx}, {vy})"); + + // A given place is the frame's own, as on the page: (10, 20) of the frame, carried through it. + let given = id(&s.execute("board.mindMap", &json!({"parent": fr, "x": 10, "y": 20})).unwrap(), "id"); + let want = s.doc().unwrap().world_transform(fr) * Point::new(10.0, 20.0); + let got = origin(&s, given); + assert!(same(got.x, want.x) && same(got.y, want.y), "{got:?} against {want:?}"); +} diff --git a/crates/engine/src/board_tests.rs b/crates/engine/src/board_tests.rs index 6dc1e28f8..dfcb28d32 100644 --- a/crates/engine/src/board_tests.rs +++ b/crates/engine/src/board_tests.rs @@ -88,7 +88,7 @@ fn a_sticky_is_a_square_frame_whose_note_grows_taller_as_it_fills() { assert_eq!(n.fills[0].solid_color(), board_color("blue")); assert!(n.layout.is_some() && !n.effects.is_empty()); assert_eq!(n.children.len(), 2, "the note and its author"); - assert_eq!(node(&s, note).kind.text().unwrap().style.font_size, 18.0); + assert_eq!(node(&s, note).kind.text().unwrap().style.font_size, 16.0); // A click on the note picks the sticky whole. let doc = s.doc().unwrap(); assert_eq!(figcraft_doc::geometry::select_target(doc, note, &[], false), st); @@ -99,19 +99,69 @@ fn a_sticky_is_a_square_frame_whose_note_grows_taller_as_it_fills() { assert!(node(&s, st).width == 200.0 && node(&s, st).height >= 200.0); // Undo puts the short note back. s.execute("edit.undo", &json!({})).unwrap(); - assert_eq!(node(&s, note).kind.text().unwrap().style.font_size, 18.0); + assert_eq!(node(&s, note).kind.text().unwrap().style.font_size, 16.0); } #[test] -fn a_new_sticky_starts_at_18() { +fn a_new_sticky_is_small_16() { let mut s = board(); for (cmd, p) in [("board.sticky", json!({"x": 0, "y": 0, "text": "Hi"})), ("board.sticky", json!({"x": 300, "y": 0}))] { let note = id(&s.execute(cmd, &p).unwrap(), "text"); - assert_eq!(node(&s, note).kind.text().unwrap().style.font_size, 18.0); + assert_eq!(node(&s, note).kind.text().unwrap().style.font_size, 16.0); } let next = id(&s.execute("board.nextSticky", &json!({})).unwrap(), "text"); - assert_eq!(node(&s, next).kind.text().unwrap().style.font_size, 18.0); - assert_eq!(STICKY_TEXT_SIZE, 18.0); + assert_eq!(node(&s, next).kind.text().unwrap().style.font_size, 16.0); + assert_eq!(STICKY_TEXT_SIZE, 16.0); +} + +#[test] +fn the_sticky_sizes_are_figjams() { + let table = [("Small", 16.0), ("Medium", 24.0), ("Large", 40.0), ("Extra large", 64.0), ("Huge", 96.0)]; + assert_eq!(crate::board::STICKY_SIZES, table); +} + +fn note_size(s: &Session, note: NodeId) -> f64 { + node(s, note).kind.text().unwrap().style.font_size +} + +#[test] +fn set_style_font_size_sizes_every_selected_sticky() { + let mut s = board(); + let a = s.execute("board.sticky", &json!({"x": 0, "y": 0, "text": "A"})).unwrap(); + let b = s.execute("board.sticky", &json!({"x": 400, "y": 0, "text": "B"})).unwrap(); + let ids = json!([id(&a, "id").0, id(&b, "id").0]); + s.execute("board.setStyle", &json!({"ids": ids, "fontSize": 24})).unwrap(); + assert_eq!(note_size(&s, id(&a, "text")), 24.0); + assert_eq!(note_size(&s, id(&b, "text")), 24.0); + let bad = s.execute("board.setStyle", &json!({"ids": ids, "fontSize": 0})); + assert!(bad.is_err()); +} + +#[test] +fn the_sticky_tool_remembers_the_last_size() { + let mut s = board(); + let a = s.execute("board.sticky", &json!({"x": 0, "y": 0, "text": "A"})).unwrap(); + s.execute("board.setStyle", &json!({"ids": [id(&a, "id").0], "fontSize": 40})).unwrap(); + let b = s.execute("board.sticky", &json!({"x": 400, "y": 0, "text": "B"})).unwrap(); + assert_eq!(note_size(&s, id(&b, "text")), 40.0); + let c = s.execute("board.sticky", &json!({"x": 800, "y": 0, "fontSize": 64})).unwrap(); + assert_eq!(note_size(&s, id(&c, "text")), 64.0); + assert!(s.execute("board.sticky", &json!({"x": 0, "y": 400, "fontSize": 5000})).is_err()); +} + +#[test] +fn a_huge_sticky_grows_taller_and_shrinks_back() { + figcraft_text::scan_system_fonts(); + let mut s = board(); + let r = s.execute("board.sticky", &json!({"x": 0, "y": 0, "text": "Alpha"})).unwrap(); + let st = id(&r, "id"); + let ids = json!([st.0]); + let (w, h16) = (node(&s, st).width, node(&s, st).height); + s.execute("board.setStyle", &json!({"ids": ids, "fontSize": 96})).unwrap(); + assert_eq!(node(&s, st).width, w, "the width stays"); + assert!(node(&s, st).height > h16, "Huge is taller than Small"); + s.execute("board.setStyle", &json!({"ids": ids, "fontSize": 40})).unwrap(); + assert_eq!(node(&s, st).height, h16, "Large is square again"); } #[test] @@ -131,7 +181,7 @@ fn a_sticky_keeps_its_text_size_as_text_is_added() { } let ten = node(&s, note).kind.text().unwrap().clone(); assert_eq!(ten.characters.matches('\n').count(), 9, "ten lines"); - assert_eq!(ten.style.font_size, 18.0); + assert_eq!(ten.style.font_size, 16.0); assert!(node(&s, note).height > text_height, "ten lines make the text taller"); assert!(node(&s, st).height > height, "and the note"); assert_eq!(node(&s, st).child_layout.sizing_v, figcraft_doc::Sizing::Hug, "the note hugs its text"); @@ -140,8 +190,8 @@ fn a_sticky_keeps_its_text_size_as_text_is_added() { crate::textedit::end(&mut s).unwrap(); let t = node(&s, note).kind.text().unwrap().clone(); assert!(t.characters.chars().count() >= 250); - assert_eq!(t.style.font_size, 18.0); - assert!(t.runs.iter().all(|r| r.style.font_size == 18.0)); + assert_eq!(t.style.font_size, 16.0); + assert!(t.runs.iter().all(|r| r.style.font_size == 16.0)); assert_eq!(node(&s, st).width, w, "the note keeps its width"); assert!(node(&s, st).height > h10, "and grows taller"); } diff --git a/crates/engine/src/board_tools_tests.rs b/crates/engine/src/board_tools_tests.rs index 1e306a7d9..f36503edc 100644 --- a/crates/engine/src/board_tools_tests.rs +++ b/crates/engine/src/board_tools_tests.rs @@ -166,9 +166,9 @@ fn styles_labels_and_their_refusals() { assert!(s.execute("board.label", &json!({"id": c, "text": ""})).unwrap()["label"].is_null()); assert!(!s.doc().unwrap().contains(l)); // What doesn't take a style or colour says so. - assert!(s.execute("board.setStyle", &json!({"ids": [a], "fontSize": 30})).is_err(), "stickies size their own text"); assert!(s.execute("board.setStyle", &json!({"ids": [c], "fontSize": 0})).is_err()); let st = id(&s.execute("board.stamp", &json!({"x": 0, "y": 0, "stamp": "check"})).unwrap(), "id"); + assert!(s.execute("board.setStyle", &json!({"ids": [st], "fontSize": 30})).is_err(), "a stamp has no text to size"); assert!(s.execute("board.setColor", &json!({"ids": [st], "color": "blue"})).is_err()); assert!(s.execute("board.setColor", &json!({"ids": [a]})).is_err()); assert!(s.execute("board.label", &json!({"id": a, "text": "x"})).is_err()); diff --git a/crates/engine/src/boards/board.rs b/crates/engine/src/boards/board.rs index d87b82914..ddee2d823 100644 --- a/crates/engine/src/boards/board.rs +++ b/crates/engine/src/boards/board.rs @@ -100,12 +100,16 @@ const HIGHLIGHTER: (f64, f32) = (20.0, 0.45); const ERASER_PX: f64 = 8.0; /// The text sizes the contextual bar offers. pub const TEXT_SIZES: [(&str, f64); 4] = [("S", 12.0), ("M", 16.0), ("L", 24.0), ("XL", 36.0)]; +/// The text sizes a sticky's menu offers (FigJam's, measured 2026-11-12): name and size. +pub const STICKY_SIZES: [(&str, f64); 5] = [("Small", 16.0), ("Medium", 24.0), ("Large", 40.0), ("Extra large", 64.0), ("Huge", 96.0)]; /// The board tools' choices: the colour new stickies get, the shape and stamp the tools place, /// how new connectors run and the marker's and highlighter's colours. #[derive(Clone, Debug)] pub struct BoardTool { pub sticky: Color, + /// The text size new stickies get (the last one chosen on a sticky). + pub sticky_size: f64, pub shape: BoardShape, pub stamp: Stamp, pub routing: Routing, @@ -118,6 +122,7 @@ impl Default for BoardTool { let first = BOARD_COLORS.first().map_or(Color::WHITE, |c| c.1); Self { sticky: first, + sticky_size: STICKY_TEXT_SIZE, shape: BoardShape::Rectangle, stamp: Stamp::ThumbsUp, routing: Routing::Elbow, @@ -132,7 +137,7 @@ pub fn specs() -> Vec { spec!( "board.sticky", "Sticky note", - "{x, y (its top-left, in the parent), text?, color? (yellow|orange|red|pink|violet|blue|green|gray or hex; default the sticky tool's), author? (a name, or false for none; default yours), parent?} → {id, text}", + "{x, y (its top-left, in the parent), text?, color? (yellow|orange|red|pink|violet|blue|green|gray or hex; default the sticky tool's), fontSize? (1 to 1000; default the sticky tool's, 16 at first), author? (a name, or false for none; default yours), parent?} → {id, text}", true, sticky_cmd ), @@ -217,7 +222,7 @@ pub fn specs() -> Vec { spec!( "board.setStyle", "Board style", - "{ids?, shape? (shapes with text), fontSize? (their text), style?: straight|elbow|curved, startCap?, endCap? (connectors)}", + "{ids?, shape? (shapes with text), fontSize? (the text of stickies, shapes, labels and mind nodes; stickies remember it for new ones), style?: straight|elbow|curved, startCap?, endCap? (connectors)}", true, set_style ), diff --git a/crates/engine/src/boards/board/edit.rs b/crates/engine/src/boards/board/edit.rs index 88a38d438..61a3c5659 100644 --- a/crates/engine/src/boards/board/edit.rs +++ b/crates/engine/src/boards/board/edit.rs @@ -130,9 +130,12 @@ impl Restyle { BoardItem::Connector(ref c) => self.restyle_connector(doc, id, c.clone())?, _ => false, }; - // Text sizes: shapes' and labels' text (stickies size theirs to fit). + // Text sizes: the text of stickies, shapes, labels and mind nodes (a sticky's note grows taller + // when its text no longer fits, by its auto layout). let sized = match (self.size, &item) { - (Some(size), BoardItem::Shape { .. } | BoardItem::Label { .. } | BoardItem::MindNode) => resize_text(doc, id, size), + (Some(size), BoardItem::Sticky { .. } | BoardItem::Shape { .. } | BoardItem::Label { .. } | BoardItem::MindNode) => { + resize_text(doc, id, size) + } _ => false, }; Ok(changed || sized) @@ -191,13 +194,19 @@ pub(super) fn set_style(s: &mut Session, p: &Value) -> Result { let restyle = Restyle::of(cmd, p)?; let doc = s.doc_mut()?; let mut changed = Vec::new(); + let mut sticky_sized = false; for (id, item) in items(doc, &ids) { + let sticky = matches!(item, BoardItem::Sticky { .. }); if restyle.apply(doc, id, item)? { changed.push(id); + sticky_sized |= sticky && restyle.size.is_some(); } } if changed.is_empty() { - return Err(bad(cmd, "nothing selected takes these (shapes with text, connectors, labels)")); + return Err(bad(cmd, "nothing selected takes these (stickies, shapes with text, connectors, labels)")); + } + if let (true, Some(size)) = (sticky_sized, restyle.size) { + s.tool.board.sticky_size = size; } Ok(json!({"ids": changed})) } diff --git a/crates/engine/src/boards/board/items.rs b/crates/engine/src/boards/board/items.rs index c70952695..431a27cf9 100644 --- a/crates/engine/src/boards/board/items.rs +++ b/crates/engine/src/boards/board/items.rs @@ -57,12 +57,13 @@ pub(crate) fn add_text(doc: &mut Document, parent: NodeId, text: &str, size: f64 Ok(id) } -/// The text size of a new sticky's note, FigJam's "Small" default (measured in the web app, -/// 2026-11-09): it never changes as the note fills, the note grows taller instead. -pub const STICKY_TEXT_SIZE: f64 = 18.0; +/// The text size of a new sticky's note, FigJam's "Small" default: 16, measured twice in the web +/// app on 2026-11-12 from the size field's value (an earlier reading of 18 did not reproduce). It +/// never changes as the note fills, the note grows taller instead. +pub const STICKY_TEXT_SIZE: f64 = 16.0; /// A sticky note's layers: the frame, the note and (when known) its author. -fn make_sticky(doc: &mut Document, parent: NodeId, at: (f64, f64), text: &str, color: Color, author: &str) -> Result<(NodeId, NodeId)> { +fn make_sticky(doc: &mut Document, parent: NodeId, at: (f64, f64), text: &str, color: Color, author: &str, size: f64) -> Result<(NodeId, NodeId)> { let id = add(doc, parent, NodeKind::Frame, "Sticky", at, (STICKY, STICKY), |n| { n.fills = vec![Paint::solid(color)]; n.corners.radii = [2.0; 4]; @@ -80,7 +81,7 @@ fn make_sticky(doc: &mut Document, parent: NodeId, at: (f64, f64), text: &str, c n.board = Some(BoardItem::Sticky { author: author.to_string() }); })?; let inner = STICKY - 2.0 * STICKY_PAD; - let note = add_text(doc, id, text, STICKY_TEXT_SIZE, INK, TextAlignH::Left, inner)?; + let note = add_text(doc, id, text, size, INK, TextAlignH::Left, inner)?; if !author.is_empty() { let a = add_text(doc, id, author, 10.0, AUTHOR_INK, TextAlignH::Left, inner)?; if let Some(n) = doc.node_mut(a) { @@ -102,7 +103,12 @@ pub(super) fn sticky_cmd(s: &mut Session, p: &Value) -> Result { let parent = parent_of(cmd, s, p)?; let text = string(p, "text").unwrap_or_default(); let at = (num_or(p, "x", 0.0), num_or(p, "y", 0.0)); - let (id, note) = make_sticky(s.doc_mut()?, parent, at, &text, color, &author)?; + let size = match num(p, "fontSize") { + None => s.tool.board.sticky_size, + Some(v) if v.is_finite() && (1.0..=1000.0).contains(&v) => v, + Some(_) => return Err(bad(cmd, "`fontSize` is from 1 to 1000")), + }; + let (id, note) = make_sticky(s.doc_mut()?, parent, at, &text, color, &author, size)?; s.set_selection(vec![id]); Ok(json!({"id": id, "text": note})) } @@ -155,11 +161,11 @@ pub(super) fn next_sticky(s: &mut Session, p: &Value) -> Result { "above" => (0.0, -(STICKY + STICKY_GAP)), other => return Err(bad(cmd, format!("`side` is right, below, left or above, not `{other}`"))), }; - let author = author(s); + let (author, size) = (author(s), s.tool.board.sticky_size); if editing.is_some() { textedit::end(s)?; } - let (id, note) = make_sticky(s.doc_mut()?, parent, (at.x + dx, at.y + dy), "", color, &author)?; + let (id, note) = make_sticky(s.doc_mut()?, parent, (at.x + dx, at.y + dy), "", color, &author, size)?; s.set_selection(vec![id]); if boolean(p, "edit") == Some(true) { // Typing goes on in the new sticky once this step is recorded. @@ -227,13 +233,13 @@ pub(super) fn add_connected(s: &mut Session, p: &Value) -> Result { } None => (to_at, from_side, to_side), }; - let (routing, author, page) = (s.tool.board.routing, author(s), s.page()?); + let (routing, author, page, size) = (s.tool.board.routing, author(s), s.page()?, s.tool.board.sticky_size); if editing.is_some() { textedit::end(s)?; } let doc = s.doc_mut()?; let (id, text) = match shape { - None => make_sticky(doc, parent, to_at, "", color, &author)?, + None => make_sticky(doc, parent, to_at, "", color, &author, size)?, Some(shape) => make_shape(doc, parent, to_at, next, shape, "", color)?, }; let connector = Connector { diff --git a/crates/engine/src/boards/board/mindmap.rs b/crates/engine/src/boards/board/mindmap.rs index 5e2cff1ce..656a3fa14 100644 --- a/crates/engine/src/boards/board/mindmap.rs +++ b/crates/engine/src/boards/board/mindmap.rs @@ -168,9 +168,13 @@ pub(super) fn mind_map_cmd(s: &mut Session, p: &Value) -> Result { let cmd = "board.mindMap"; require(s, cmd)?; let parent = parent_of(cmd, s, p)?; + // The view's centre is on the page, and `x`/`y` are in the parent: a map in a section or frame + // takes the centre in that parent's coordinates (a parent that can't be inverted gives a + // non-finite centre, which `coord` refuses). let (vx, vy) = { - let v = &s.ds()?.view; - (v.cx, v.cy) + let ds = s.ds()?; + let c = ds.doc.world_transform(parent).inverse() * figcraft_geom::Point::new(ds.view.cx, ds.view.cy); + (c.x, c.y) }; let (x, y) = (coord(cmd, p, "x", vx)?, coord(cmd, p, "y", vy)?); let texts = starters(cmd, p)?; diff --git a/crates/engine/src/canvas/rotation_origin.rs b/crates/engine/src/canvas/rotation_origin.rs index 8498f708a..5552bc77b 100644 --- a/crates/engine/src/canvas/rotation_origin.rs +++ b/crates/engine/src/canvas/rotation_origin.rs @@ -8,7 +8,7 @@ use figcraft_doc::{Document, NodeId}; use figcraft_geom::Point; use crate::cmd::edit::roots; -use crate::tools::{SNAP_PX, selection_box}; +use crate::tools::{UNMEASURED_SNAP_PX, selection_box}; use crate::{DocState, EngineError, Result, Session}; /// How near (screen pixels) a press must be to grab the origin handle. @@ -115,7 +115,7 @@ impl Session { let snapped = box_points(&ds.doc, &ds.selection).and_then(|b| { b.iter() .enumerate() - .filter(|(_, q)| (**q - p).hypot() * zoom.max(1e-6) <= SNAP_PX) + .filter(|(_, q)| (**q - p).hypot() * zoom.max(1e-6) <= UNMEASURED_SNAP_PX) .min_by(|x, y| (*x.1 - p).hypot().total_cmp(&(*y.1 - p).hypot())) .map(|(i, q)| (i, *q)) }); diff --git a/crates/engine/src/canvas/snap.rs b/crates/engine/src/canvas/snap.rs index cd40437d3..ff1a6b64d 100644 --- a/crates/engine/src/canvas/snap.rs +++ b/crates/engine/src/canvas/snap.rs @@ -9,7 +9,7 @@ use figcraft_geom::{Affine, Point, Rect, Vec2, transform_rect_bbox}; use serde::Serialize; use crate::guides; -use crate::tools::SNAP_PX; +use crate::tools::UNMEASURED_SNAP_PX; /// A guide line to draw: from (x0, y0) to (x1, y1) in page coordinates, with an optional label /// (a distance) at its middle; `dashed` marks a measurement's extension line. @@ -438,14 +438,14 @@ impl Targets { } /// Snap a guide on `owner` (a page or a top-level frame) to the nearest layer edge or centre along -/// its own axis, within `SNAP_PX` screen pixels at `zoom`. Returns the new offset in `owner`'s +/// its own axis, within `UNMEASURED_SNAP_PX` screen pixels at `zoom`. Returns the new offset in `owner`'s /// coordinates, or `None` when nothing is in reach. pub fn snap_guide(doc: &Document, page: NodeId, owner: NodeId, vertical: bool, offset: f64, zoom: f64) -> Option { // The guide moves along the owner's own axis (x for a vertical guide, y for a horizontal one), // which the owner's transform may scale: convert the screen-pixel reach into owner units. let [a, b, c, d, _, _] = doc.world_transform(owner).as_coeffs(); let axis = if vertical { a.hypot(b) } else { c.hypot(d) }; - let threshold = SNAP_PX / (zoom.max(1e-6) * axis.max(1e-6)); + let threshold = UNMEASURED_SNAP_PX / (zoom.max(1e-6) * axis.max(1e-6)); Targets::gather_for_guide(doc, page, owner).snap_axis(vertical, offset, threshold).map(|d| offset + d).filter(|v| v.is_finite()) } diff --git a/crates/engine/src/canvas/tools.rs b/crates/engine/src/canvas/tools.rs index 1ccf4f8ca..d9c265f88 100644 --- a/crates/engine/src/canvas/tools.rs +++ b/crates/engine/src/canvas/tools.rs @@ -34,7 +34,7 @@ pub use handles::{ PENCIL_STROKE, SMALL_BOX_PX, anchor_name, anchor_of, box_sides_px, handle_at, handle_at_corners, label_at, locked_in, scale_anchor_point, selection_box, selection_frame, shared_rotation_degrees, }; -pub(crate) use handles::{SNAP_PX, handle_cursor, readable_text_fills, resized_box}; +pub(crate) use handles::{SNAP_PX, UNMEASURED_SNAP_PX, handle_cursor, readable_text_fills, resized_box}; #[cfg(test)] pub(crate) use pen::pressure_profile; diff --git a/crates/engine/src/canvas/tools/handles.rs b/crates/engine/src/canvas/tools/handles.rs index ecd29e67a..6a871ceaf 100644 --- a/crates/engine/src/canvas/tools/handles.rs +++ b/crates/engine/src/canvas/tools/handles.rs @@ -71,8 +71,13 @@ const HANDLE_PX: f64 = 5.0; const ROTATE_PX: f64 = 18.0; -/// Snap distance in screen pixels. -pub(crate) const SNAP_PX: f64 = 5.0; +/// Object snap distance in screen pixels: measured in Figma, where an edge snaps at a gap of 4.4 +/// screen px and not at 4.6, at 100% and at 200% zoom. +pub(crate) const SNAP_PX: f64 = 4.5; + +/// Snap distance in screen pixels for ruler guides and the rotation origin, not measured against +/// Figma. +pub(crate) const UNMEASURED_SNAP_PX: f64 = 5.0; /// Screen pixels the pointer travels after a press before a move or resize starts: a click or a /// double-click made with an unsteady hand doesn't drag what it lands on. diff --git a/crates/engine/src/canvas/vectoredit/ops.rs b/crates/engine/src/canvas/vectoredit/ops.rs index 222c6f4ff..21fead47b 100644 --- a/crates/engine/src/canvas/vectoredit/ops.rs +++ b/crates/engine/src/canvas/vectoredit/ops.rs @@ -124,9 +124,62 @@ pub fn move_handles(net: &mut VectorNetwork, hs: &[(usize, bool)], d: Vec2, inde } } +/// Each handle of a sharp point turned smooth by a mirror mode is this fraction of the length of its +/// own segment. Measured in the incumbent (0.3905 and 0.390 at two angles): known to about 3 digits only. +const MIRROR_SMOOTH_FACTOR: f64 = 0.3905; + +/// Give a sharp point (two segments, no handles) the handles a mirror mode makes in the incumbent. +/// Both lie on one line through the point, along `(B - A) / |BA|^2 + (C - B) / |BC|^2` (A, C: the far +/// ends of the two segments). "Angle": each is [`MIRROR_SMOOTH_FACTOR`] x its own segment. +/// "Angle and length": both are that factor x the shorter segment (medium confidence: the +/// measurement could not separate this from other rules). Open-path ends, points with a handle +/// already and coincident neighbours are left alone. Returns whether handles were made. +fn smooth_sharp_point(net: &mut VectorNetwork, vi: usize, mode: HandleMirroring) -> bool { + if mode == HandleMirroring::None { + return false; + } + let inc = net.incident(vi); + let [(s1, a1), (s2, a2)] = inc.as_slice() else { return false }; + let (Some(h1), Some(h2)) = (net.handle(*s1, *a1), net.handle(*s2, *a2)) else { return false }; + if tvec(h1).hypot() > 1e-9 || tvec(h2).hypot() > 1e-9 { + return false; + } + let far = |s: usize, st: bool| net.segments.get(s).and_then(|x| net.vertices.get(if st { x.b } else { x.a })).map(|v| v.point()); + let (Some(b), Some(a), Some(c)) = (net.vertices.get(vi).map(|v| v.point()), far(*s1, *a1), far(*s2, *a2)) else { return false }; + let (ab, bc) = (b - a, c - b); + let (la, lc) = (ab.hypot(), bc.hypot()); + if !(la > 1e-9 && lc > 1e-9 && la.is_finite() && lc.is_finite()) { + return false; + } + let d = ab / (la * la) + bc / (lc * lc); + if !finite(d) || d.hypot() < 1e-12 { + return false; + } + let d = d.normalize(); + let (l_in, l_out) = if mode == HandleMirroring::AngleAndLength { + let l = MIRROR_SMOOTH_FACTOR * la.min(lc); + (l, l) + } else { + (MIRROR_SMOOTH_FACTOR * la, MIRROR_SMOOTH_FACTOR * lc) + }; + let (in_h, out_h) = (-d * l_in, d * l_out); + if !(finite(in_h) && finite(out_h)) { + return false; + } + net.set_handle(*s1, *a1, (in_h.x, in_h.y)); + net.set_handle(*s2, *a2, (out_h.x, out_h.y)); + true +} + /// Set the mirroring of vertices and make their handles agree with it. pub fn set_mirroring(net: &mut VectorNetwork, verts: &[usize], mode: HandleMirroring) { for &vi in verts { + if smooth_sharp_point(net, vi, mode) { + if let Some(v) = net.vertices.get_mut(vi) { + v.mirror = Some(mode); + } + continue; + } let inc = net.incident(vi); if let [(s1, a1), (s2, a2)] = inc.as_slice() && let (Some(h1), Some(h2)) = (net.handle(*s1, *a1), net.handle(*s2, *a2)) @@ -949,6 +1002,72 @@ mod tests { assert!((a + b).hypot() < 1e-9, "made symmetric: {a:?} {b:?}"); } + /// An open path A, B, C (the measured triangle of #2110) with B sharp. + fn triangle_path() -> VectorNetwork { + VectorNetwork::from_points(&[Point::new(-250.0, -174.0), Point::new(117.0, -174.0), Point::new(-67.0, 194.0)], false) + } + + fn handles_at_b(n: &VectorNetwork) -> (Vec2, Vec2) { + (tvec(n.segments[0].tb), tvec(n.segments[1].ta)) + } + + #[test] + fn mirror_modes_smooth_a_sharp_point_as_measured() { + // Mirror angle and length: both handles 0.3905 x the shorter segment (367), opposite. + let mut n = triangle_path(); + set_mirroring(&mut n, &[1], HandleMirroring::AngleAndLength); + let (i, o) = handles_at_b(&n); + assert!((o - Vec2::new(86.24, 114.47)).hypot() < 0.1, "{o:?}"); + assert!((i + o).hypot() < 1e-9, "{i:?} {o:?}"); + assert!((o.hypot() - 143.3).abs() < 0.1, "{}", o.hypot()); + // Mirror angle: each handle 0.3905 x its own segment; still collinear. + let mut n = triangle_path(); + set_mirroring(&mut n, &[1], HandleMirroring::Angle); + let (i, o) = handles_at_b(&n); + assert!((i - Vec2::new(-86.24, -114.47)).hypot() < 0.1, "{i:?}"); + assert!((o - Vec2::new(96.69, 128.33)).hypot() < 0.1, "{o:?}"); + assert!((i.x * o.y - i.y * o.x).abs() < 1e-6, "collinear"); + assert!((i.hypot() - 143.3).abs() < 0.1 && (o.hypot() - 160.7).abs() < 0.1); + assert_eq!(n.mirroring(1), HandleMirroring::Angle); + } + + #[test] + fn mirror_modes_smooth_other_angles_and_several_points() { + // A right angle at B with legs 100 and 50: d = (1,0)/100 + (0,1)/50, so the line leans to +y. + let mut n = VectorNetwork::from_points(&[Point::new(0.0, 0.0), Point::new(100.0, 0.0), Point::new(100.0, 50.0)], false); + set_mirroring(&mut n, &[1], HandleMirroring::Angle); + let (i, o) = handles_at_b(&n); + let want = Vec2::new(0.01, 0.02).normalize(); + assert!((o.normalize() - want).hypot() < 1e-9, "{o:?}"); + assert!((o.hypot() - 19.525).abs() < 1e-9 && (i.hypot() - 39.05).abs() < 1e-9, "{i:?} {o:?}"); + // Two sharp points of a closed square, both selected: both become smooth. + let mut sq = square(); + set_mirroring(&mut sq, &[0, 2], HandleMirroring::AngleAndLength); + for v in [0, 2] { + assert!(sq.incident(v).iter().all(|(s, st)| sq.handle(*s, *st).is_some_and(|h| tvec(h).hypot() > 1.0)), "vertex {v}"); + assert_eq!(sq.mirroring(v), HandleMirroring::AngleAndLength); + } + assert!(sq.segments.iter().all(|s| tvec(s.ta).x.is_finite() && tvec(s.tb).y.is_finite())); + } + + #[test] + fn mirror_modes_leave_unmeasured_points_alone() { + // Open-path ends have only one segment. + let mut n = open_line(); + set_mirroring(&mut n, &[0, 2], HandleMirroring::Angle); + assert!(n.segments.iter().all(|s| s.is_straight())); + // A zero-length neighbour: stays sharp, finite. + let mut z = VectorNetwork::from_points(&[Point::new(5.0, 5.0), Point::new(5.0, 5.0), Point::new(60.0, 0.0)], false); + set_mirroring(&mut z, &[1], HandleMirroring::AngleAndLength); + assert!(z.segments.iter().all(|s| s.is_straight())); + // One handle already: the old behaviour (the lone handle stays, the other mirrors it). + let mut h = open_line(); + h.segments[1].ta = (10.0, 5.0); + set_mirroring(&mut h, &[1], HandleMirroring::Angle); + assert_eq!(h.segments[1].ta, (10.0, 5.0)); + assert_eq!(h.segments[0].tb, (-10.0, -5.0)); + } + fn loop_is_continuous(n: &VectorNetwork, lp: &[usize]) -> bool { let ends: Vec<(usize, usize)> = n .loop_walk(lp) diff --git a/crates/engine/src/canvas/vectoredit/tests.rs b/crates/engine/src/canvas/vectoredit/tests.rs index ebe849761..c5f02d122 100644 --- a/crates/engine/src/canvas/vectoredit/tests.rs +++ b/crates/engine/src/canvas/vectoredit/tests.rs @@ -407,6 +407,24 @@ fn mirroring_position_and_join_commands() { assert!(s.execute("vector.join", &json!({"ids": [id]})).is_ok()); } +#[test] +fn mirror_mode_on_sharp_points_is_one_undo_step() { + // #2110: a mirror mode turns sharp points smooth; the whole command undoes in one step. + let mut s = Session::new(); + let r = ex(&mut s, "vector.create", json!({"points": [[-250, -174], [117, -174], [-67, 194]], "closed": false})); + let id = crate::params::id_of(&r["id"]).unwrap(); + ex(&mut s, "vector.edit.begin", json!({"id": id})); + ex(&mut s, "vector.edit.select", json!({"vertices": [1]})); + ex(&mut s, "vector.edit.mirroring", json!({"mode": "angleAndLength"})); + let n = net(&s, id); + let (i, o) = (n.segments[0].tb, n.segments[1].ta); + assert!((o.0 - 86.24).abs() < 0.1 && (o.1 - 114.47).abs() < 0.1, "{o:?}"); + assert!((i.0 + o.0).abs() < 1e-9 && (i.1 + o.1).abs() < 1e-9, "{i:?}"); + s.undo().unwrap(); + let n = net(&s, id); + assert!(n.segments.iter().all(|x| x.is_straight()), "one undo restores the sharp point"); +} + #[test] fn a_point_dropped_on_another_merges_into_it() { // #401: an open path's end dragged onto its start closes the path at that point. diff --git a/crates/engine/src/cmd/variables.rs b/crates/engine/src/cmd/variables.rs index 85e1454f3..d8c20e05a 100644 --- a/crates/engine/src/cmd/variables.rs +++ b/crates/engine/src/cmd/variables.rs @@ -184,7 +184,10 @@ fn duplicate(s: &mut Session, p: &Value) -> Result { let cmd = "variable.duplicate"; let v = req_string(cmd, p, "variable")?; let doc = s.doc_mut()?; - let pos = doc.variables.variables.iter().position(|x| x.id == v || x.name == v).ok_or_else(|| bad(cmd, "no such variable"))?; + // An exact id first, then a name: an earlier variable named like another's id must not be the + // one copied. + let vars = &doc.variables.variables; + let pos = vars.iter().position(|x| x.id == v).or_else(|| vars.iter().position(|x| x.name == v)).ok_or_else(|| bad(cmd, "no such variable"))?; let mut copy = doc.variables.variables.get(pos).cloned().ok_or_else(|| bad(cmd, "no such variable"))?; let taken = |n: &str| doc.variables.variables.iter().any(|x| x.collection == copy.collection && x.name == n); let name = (1..1000) diff --git a/crates/engine/src/dev/codegen.rs b/crates/engine/src/dev/codegen.rs index 202f7ef0f..428c3a711 100644 --- a/crates/engine/src/dev/codegen.rs +++ b/crates/engine/src/dev/codegen.rs @@ -506,6 +506,44 @@ mod tests { assert!(!css.contains("#000000 0%"), "{css}"); } + /// The measured frame: white at the bottom, a 20% gradient above it, 50% black on top. + fn layered_frame(s: &mut Session) -> figcraft_doc::NodeId { + let f = id_of(&s.execute("frame.create", &json!({"x": 0, "y": 0, "width": 200, "height": 120})).unwrap()["id"]).unwrap(); + let mut g = figcraft_color::Paint::gradient(figcraft_color::Gradient::default_for(figcraft_color::GradientKind::Linear, Color::BLACK)); + g.opacity = 0.2; + let mut top = figcraft_color::Paint::solid(Color::BLACK); + top.opacity = 0.5; + s.doc_mut().unwrap().get_mut(f).unwrap().fills = vec![figcraft_color::Paint::solid(Color::WHITE), g, top]; + f + } + + #[test] + fn several_fills_are_one_layered_background_top_first() { + let mut s = Session::new(); + let f = layered_frame(&mut s); + let css = code_for(s.doc().unwrap(), f, CodeLang::Css); + let bg: Vec<&str> = css.lines().filter(|l| l.starts_with("background:")).collect(); + assert_eq!(bg.len(), 1, "{css}"); + let v = bg[0]; + assert!( + v.starts_with( + "background: linear-gradient(0deg, rgba(0, 0, 0, 0.50), rgba(0, 0, 0, 0.50)), linear-gradient(180deg, rgba(0, 0, 0, 0.20) 0%, " + ), + "{v}" + ); + assert!(v.ends_with(", #FFFFFF;"), "{v}"); + } + + #[test] + fn one_solid_fill_stays_a_plain_colour() { + let mut s = Session::new(); + let f = id_of(&s.execute("frame.create", &json!({"x": 0, "y": 0, "width": 200, "height": 100})).unwrap()["id"]).unwrap(); + s.doc_mut().unwrap().get_mut(f).unwrap().fills = vec![figcraft_color::Paint::solid(Color::WHITE)]; + let css = code_for(s.doc().unwrap(), f, CodeLang::Css); + assert!(css.contains("background: #FFFFFF;\n"), "{css}"); + assert!(!css.contains("gradient"), "{css}"); + } + #[test] fn swiftui_and_compose_for_an_auto_layout_card() { let mut s = Session::new(); @@ -675,6 +713,27 @@ mod tests { assert!(!dart.lines().any(|l| l.trim_start().starts_with("void main()")), "a name never leaves its comment: {dart}"); } + #[test] + fn flutter_writes_no_spacing_for_the_space_distributions() { + // The space distributions spread the children themselves; a `spacing:` beside them would + // add the gap on top. + let mut s = Session::new(); + let row = id_of(&s.execute("frame.create", &json!({"x": 0, "y": 0, "width": 300, "height": 40})).unwrap()["id"]).unwrap(); + s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 50, "height": 20, "parent": row})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 60, "y": 0, "width": 50, "height": 20, "parent": row})).unwrap(); + s.execute("layout.add", &json!({"ids": [row], "direction": "horizontal"})).unwrap(); + for (align, flutter) in [("spaceBetween", "spaceBetween"), ("spaceAround", "spaceAround"), ("spaceEvenly", "spaceEvenly")] { + s.execute("node.set", &json!({"id": row, "props": {"gap": 10, "mainAlign": align}})).unwrap(); + let dart = code_for(s.doc().unwrap(), row, CodeLang::Flutter); + assert!(dart.contains(&format!("mainAxisAlignment: MainAxisAlignment.{flutter},")), "{dart}"); + assert!(!dart.contains("spacing:"), "{align} spreads the children itself: {dart}"); + } + // A packed line keeps its gap. + s.execute("node.set", &json!({"id": row, "props": {"gap": 10, "mainAlign": "center"}})).unwrap(); + let dart = code_for(s.doc().unwrap(), row, CodeLang::Flutter); + assert!(dart.contains("spacing: 10,"), "{dart}"); + } + #[test] fn flutter_expands_and_stretches_fill_children() { let mut s = Session::new(); diff --git a/crates/engine/src/dev/codegen/css.rs b/crates/engine/src/dev/codegen/css.rs index 46f579123..a5e6726a3 100644 --- a/crates/engine/src/dev/codegen/css.rs +++ b/crates/engine/src/dev/codegen/css.rs @@ -160,17 +160,48 @@ pub(crate) fn css_decls(doc: &Document, n: &Node, t: &mut Tokens, hug: (bool, bo put("transform", format!("rotate({}deg)", num(-rot))); put("transform-origin", "top left".into()); } - for (i, p) in n.fills.iter().enumerate().filter(|(_, p)| p.visible) { - match &p.kind { - PaintKind::Solid { color } => { - let key = if matches!(n.kind, NodeKind::Text(_)) { "color" } else { "background" }; - let c = color.with_alpha(color.a * p.opacity).to_css(); - // A variable binds the first paint's colour. - put(key, if i == 0 { tok(doc, n, &["fill"], c, t) } else { c }); + if matches!(n.kind, NodeKind::Text(_)) { + // Text: a solid is the ink (`color`), one per fill, so the last (top) one wins. + for (i, p) in n.fills.iter().enumerate().filter(|(_, p)| p.visible) { + match &p.kind { + PaintKind::Solid { color } => { + let c = color.with_alpha(color.a * p.opacity).to_css(); + // A variable binds the first paint's colour. + put("color", if i == 0 { tok(doc, n, &["fill"], c, t) } else { c }); + } + PaintKind::Gradient(g) => put("background", css_gradient(g, n.width, n.height, p.opacity)), + PaintKind::Image(_) => put("background", "url(image.png) center / cover".into()), + PaintKind::Pattern(_) => put("background", "url(pattern.png) repeat".into()), } - PaintKind::Gradient(g) => put("background", css_gradient(g, n.width, n.height, p.opacity)), - PaintKind::Image(_) => put("background", "url(image.png) center / cover".into()), - PaintKind::Pattern(_) => put("background", "url(pattern.png) repeat".into()), + } + } else { + // One `background` with every visible fill as a layer, top first (a document's fills run + // bottom to top, as the renderer paints them). CSS allows a plain colour only as the last + // layer, so a solid above another fill becomes a one-colour gradient. + let visible: Vec<(usize, &figcraft_color::Paint)> = n.fills.iter().enumerate().filter(|(_, p)| p.visible).collect(); + let layers: Vec = visible + .iter() + .enumerate() + .rev() + .map(|(pos, (i, p))| match &p.kind { + PaintKind::Solid { color } => { + let c = color.with_alpha(color.a * p.opacity).to_css(); + if pos > 0 { + format!("linear-gradient(0deg, {c}, {c})") + } else if *i == 0 { + // A variable binds the first paint's colour. + tok(doc, n, &["fill"], c, t) + } else { + c + } + } + PaintKind::Gradient(g) => css_gradient(g, n.width, n.height, p.opacity), + PaintKind::Image(_) => "url(image.png) center / cover".into(), + PaintKind::Pattern(_) => "url(pattern.png) repeat".into(), + }) + .collect(); + if !layers.is_empty() { + put("background", layers.join(", ")); } } for (key, value) in css_borders(doc, n, t) { diff --git a/crates/engine/src/dev/codegen/flutter.rs b/crates/engine/src/dev/codegen/flutter.rs index 98f280eaf..7a144a147 100644 --- a/crates/engine/src/dev/codegen/flutter.rs +++ b/crates/engine/src/dev/codegen/flutter.rs @@ -335,7 +335,7 @@ fn flutter_line(ctx: &Ctx, l: &AutoLayout, flow: &[Placed], slot: Option<&Param> out.push_str(&format!("{inner}textBaseline: TextBaseline.alphabetic,\n")); } // The gap between the children; the space distributions already spread them. - if l.gap > 0.0 && flutter_main_align(l.main_align).is_none_or(|m| !m.contains("Space")) { + if l.gap > 0.0 && !matches!(l.main_align, MainAlign::SpaceBetween | MainAlign::SpaceAround | MainAlign::SpaceEvenly) { out.push_str(&format!("{inner}spacing: {},\n", num(l.gap))); } out.push_str(&format!("{inner}children: [\n")); diff --git a/crates/engine/src/dev/tailwind.rs b/crates/engine/src/dev/tailwind.rs index 8c96ac820..fcc98a9a8 100644 --- a/crates/engine/src/dev/tailwind.rs +++ b/crates/engine/src/dev/tailwind.rs @@ -105,6 +105,23 @@ fn arb(v: &str) -> String { format!("[{}]", v.trim().replace('_', "\\_").replace(' ', "_")) } +/// Whether `v` has a comma outside any parentheses (a multi-layer `background`). +fn layered(v: &str) -> bool { + let mut depth = 0usize; + v.chars().any(|c| match c { + '(' => { + depth += 1; + false + } + ')' => { + depth = depth.saturating_sub(1); + false + } + ',' => depth == 0, + _ => false, + }) +} + /// The custom property a `var(--name, fallback)` value reads, when that one call is the whole /// value (not `var(--a, 4px) 8px`, four corners of which only the first is a variable). fn var_name(v: &str) -> Option<&str> { @@ -270,6 +287,8 @@ fn decl(key: &str, value: &str) -> Vec<(String, String)> { Ok(o) if ((o * 100.0).round() - o * 100.0).abs() < 1e-9 => one(format!("opacity-{}", num(o * 100.0))), _ => one(util("opacity", "", v, "")), }, + // Several fills are one layered `background`: commas between the layers, outside any call. + ("background", v) if layered(v) => one(format!("[background:{}]", arb(v).trim_matches(['[', ']']))), ("background", v) if v.contains("gradient(") => one(format!("bg-{}", arb(v))), // An image shorthand (`url(…) center / cover`) is a whole `background`, not a bg colour. ("background", v) if v.starts_with("url(") => one(format!("[background:{}]", arb(v).trim_matches(['[', ']']))), diff --git a/crates/engine/src/measure_tests.rs b/crates/engine/src/measure_tests.rs index 9f7937214..fb031102d 100644 --- a/crates/engine/src/measure_tests.rs +++ b/crates/engine/src/measure_tests.rs @@ -196,9 +196,9 @@ fn alt_drag_shows_live_distances_to_the_neighbours() { e }; s.pointer(&ev(PointerKind::Down, 30.0)).unwrap(); - // Alt duplicates: the copy, dragged to 110..160, snaps to equal spacing between the original + // Alt duplicates: the copy, dragged to 109..159, snaps to equal spacing between the original // and the other layer (105..155). - s.pointer(&ev(PointerKind::Move, 130.0)).unwrap(); + s.pointer(&ev(PointerKind::Move, 129.0)).unwrap(); let g = s.tool.overlay.guides.clone(); assert_eq!( labelled(&g), @@ -209,7 +209,7 @@ fn alt_drag_shows_live_distances_to_the_neighbours() { ("45".into(), [155, 50, 200, 50]) ] ); - s.pointer(&ev(PointerKind::Up, 130.0)).unwrap(); + s.pointer(&ev(PointerKind::Up, 129.0)).unwrap(); assert!(s.tool.overlay.guides.is_empty()); } diff --git a/crates/engine/src/tailwind_tests.rs b/crates/engine/src/tailwind_tests.rs index 970ecd1ca..7e66405bf 100644 --- a/crates/engine/src/tailwind_tests.rs +++ b/crates/engine/src/tailwind_tests.rs @@ -358,6 +358,22 @@ fn font_family_with_quote_and_bracket_stays_a_valid_class_token() { assert!(!inner.is_empty() && !inner.contains(['\\', '"', ']']), "{out}"); } +#[test] +fn several_fills_are_one_layered_background_class() { + let mut s = Session::new(); + let f = idv(&ex(&mut s, "frame.create", json!({"x": 0, "y": 0, "width": 200, "height": 120}))); + let mut g = + figcraft_color::Paint::gradient(figcraft_color::Gradient::default_for(figcraft_color::GradientKind::Linear, figcraft_color::Color::BLACK)); + g.opacity = 0.2; + let mut top = figcraft_color::Paint::solid(figcraft_color::Color::BLACK); + top.opacity = 0.5; + s.doc_mut().unwrap().get_mut(f).unwrap().fills = vec![figcraft_color::Paint::solid(figcraft_color::Color::WHITE), g, top]; + let out = code(&mut s, f, json!({})); + let class = out.split(['"', ' ']).find(|c| c.starts_with("[background:")).unwrap_or_default(); + assert!(class.starts_with("[background:linear-gradient(0deg,_rgba(0,_0,_0,_0.50),_rgba(0,_0,_0,_0.50)),_linear-gradient(180deg"), "{out}"); + assert!(class.ends_with(",_#FFFFFF]"), "{out}"); +} + /// Issue #2272: a desktop `page` 1440 wide and a mobile one 390 wide, each holding a fixed 48 x 48 /// `badge` and a `banner` that fills the page. fn badge_frames(s: &mut Session) -> (NodeId, NodeId) { diff --git a/crates/engine/src/text_tail_tests.rs b/crates/engine/src/text_tail_tests.rs index 1498118a1..af854a6ea 100644 --- a/crates/engine/src/text_tail_tests.rs +++ b/crates/engine/src/text_tail_tests.rs @@ -482,3 +482,29 @@ fn a_many_line_paste_clears_every_created_start() { assert_eq!(d.para_list(0).start_offset, 4, "the first item keeps its start"); assert!((1..d.paragraph_count()).all(|p| d.para_list(p).start_offset == 0 && d.para_list(p).list == N)); } + +#[test] +fn a_list_back_from_a_fig_split_in_the_middle_restarts_at_one() { + // #2273's steps: type "5. a", Enter, "b", Enter, "c"; save a copy as .fig and open it; + // Backspace at the start of "b". The export writes the start on every line, as Figma does, + // and "c" must then read 1., not 5. + let mut s = Session::new(); + three_typed_items(&mut s, "5. a"); + crate::textedit::end(&mut s).unwrap(); + let (bytes, _) = figcraft_format::fig::export(s.doc().unwrap(), None).unwrap(); + let (back, _) = figcraft_format::fig::import(&bytes, "x").unwrap(); + let t = back.nodes().find(|n| n.kind.text().is_some()).map(|n| n.id).unwrap(); + let mut s = Session::with_document(back); + let d = data(&s, t); + assert_eq!(lists(&s, t), [(N, 0); 3]); + assert_eq!( + (d.para_list(0).start_offset, d.para_list(1).start_offset, d.para_list(2).start_offset), + (4, 0, 0), + "only the first item carries the start" + ); + begin(&mut s, t, Some(2), false).unwrap(); + key(&mut s, "Backspace", false, false, false).unwrap(); + let d = data(&s, t); + assert_eq!(lists(&s, t), [(N, 0), (P, 0), (N, 0)]); + assert_eq!((d.para_list(0).start_offset, d.para_list(2).start_offset), (4, 0), "c reads 1."); +} diff --git a/crates/engine/src/transform_behaviour_tests.rs b/crates/engine/src/transform_behaviour_tests.rs index 7b0354b2e..3c37bf6c0 100644 --- a/crates/engine/src/transform_behaviour_tests.rs +++ b/crates/engine/src/transform_behaviour_tests.rs @@ -747,6 +747,27 @@ fn smart_guides_snap_to_edges_centres_and_equal_spacing() { assert_eq!(bounds(&s, b).origin(), Point::new(198.0, 2.0)); } +#[test] +fn a_layer_edge_snaps_within_4_5_screen_pixels_at_any_zoom() { + // Measured in Figma (2026-11-08): a dragged edge snaps at a gap of 4.4 screen px and not at 4.6, + // at 100% and at 200% zoom. + for (zoom, gap_px, snaps) in [(1.0, 4.4, true), (1.0, 4.8, false), (2.0, 4.4, true), (2.0, 4.8, false)] { + let mut s = Session::new(); + ex(&mut s, "view.snapPixel", json!({"on": false})); + rect(&mut s, 0.0, 0.0, 100.0, 100.0, None); + let b = rect(&mut s, 300.0, 300.0, 100.0, 100.0, None); + ex(&mut s, "select.set", json!({"ids": [b]})); + let gap = gap_px / zoom; + let to = Point::new(350.0 - (200.0 - gap), 350.0); + for (kind, p) in [(PointerKind::Down, Point::new(350.0, 350.0)), (PointerKind::Move, to), (PointerKind::Up, to)] { + s.pointer(&PointerEvent::at(kind, p.x, p.y, zoom)).unwrap(); + } + let want = if snaps { 100.0 } else { 100.0 + gap }; + let got = bounds(&s, b).x0; + assert!(near(got, want), "zoom {zoom}, gap {gap_px} screen px: left edge at {got}, wanted {want}"); + } +} + #[test] fn snapping_to_layers_wins_over_the_pixel_grid() { // Both on (the defaults): a layer's centre at x = 5.5 is still a target. diff --git a/crates/engine/src/variables_editor_tests.rs b/crates/engine/src/variables_editor_tests.rs index 806300c70..65cc04763 100644 --- a/crates/engine/src/variables_editor_tests.rs +++ b/crates/engine/src/variables_editor_tests.rs @@ -47,6 +47,18 @@ fn rename_describe_scope_and_duplicate() { assert_eq!(vars.get(&id).unwrap().scopes, brand.scopes); } +#[test] +fn duplicate_by_id_copies_that_variable_even_when_an_earlier_one_is_named_like_its_id() { + let mut s = Session::new(); + tokens(&mut s); + let brand = s.doc().unwrap().variables.get("brand").unwrap().id.clone(); + // The first variable in the list takes the later one's id as its name. + ex(&mut s, "variable.update", json!({"variable": "space/sm", "name": brand.clone()})); + let id = ex(&mut s, "variable.duplicate", json!({"variable": brand.clone()}))["id"].as_str().unwrap().to_string(); + let vars = &s.doc().unwrap().variables; + assert_eq!(vars.get(&id).unwrap().name, "brand copy"); +} + #[test] fn modes_and_collections_rename_and_delete() { let mut s = Session::new(); diff --git a/crates/engine/src/vector_multi_behaviour_tests.rs b/crates/engine/src/vector_multi_behaviour_tests.rs index ef337af83..c1daf39e7 100644 --- a/crates/engine/src/vector_multi_behaviour_tests.rs +++ b/crates/engine/src/vector_multi_behaviour_tests.rs @@ -215,9 +215,12 @@ fn corner_radius_mirroring_and_delete(s: &mut Session, a: NodeId, b: NodeId, atl fn bend_select_all_pen_and_clicks(s: &mut Session, a: NodeId, b: NodeId) { // The Bend tool (held with Cmd/Ctrl) bends the segment under the pointer, in its own layer. + // (The earlier mirroring step already turned the selected corners smooth, #2110.) + let a_before = net(s, a).segments; + let b_before = net(s, b).segments; drag(s, (250.0, 100.0), (250.0, 130.0), CMD); - assert!(net(s, b).segments.iter().any(|sg| !sg.is_straight()), "the bend lands on the layer under the pointer"); - assert!(net(s, a).segments.iter().all(|sg| sg.is_straight()), "other layers keep their segments"); + assert!(net(s, b).segments != b_before, "the bend lands on the layer under the pointer"); + assert!(net(s, a).segments == a_before, "other layers keep their segments"); // Select all takes every edited layer's points. let r = ex(s, "vector.edit.selectAll", json!({})); assert_eq!(r["count"], json!(8), "silent: select all takes the points of every edited layer (pinned)"); diff --git a/crates/format/src/fig.rs b/crates/format/src/fig.rs index 24268da3c..6b3d4efb2 100644 --- a/crates/format/src/fig.rs +++ b/crates/format/src/fig.rs @@ -38,6 +38,8 @@ mod paste_style_tests; #[cfg(test)] mod prop_value_tests; #[cfg(test)] +mod proto_background_tests; +#[cfg(test)] mod scale_factor_tests; #[cfg(test)] mod slot_tests; diff --git a/crates/format/src/fig/export.rs b/crates/format/src/fig/export.rs index ac8612b9c..be0c902cf 100644 --- a/crates/format/src/fig/export.rs +++ b/crates/format/src/fig/export.rs @@ -190,7 +190,7 @@ message GridTrackSizingFunction GridTrackSizingType type=1, float value=2 message GridTrackSize GridTrackSizingFunction minSizing=1, GridTrackSizingFunction maxSizing=2 message GUIDGridTrackSizeMapEntry GUID id=1, GridTrackSize trackSize=2 message GUIDGridTrackSizeMap GUIDGridTrackSizeMapEntry[] entries=1 -message NodeChange GUID guid=1, NodePhase phase=2, ParentIndex parentIndex=3, NodeType type=4, string name=5, bool visible=6, bool locked=7, float opacity=8, BlendMode blendMode=9, Vector size=11, Matrix transform=12, bool mask=16, MaskType maskType=317, float backgroundOpacity=19, bool backgroundEnabled=15, bool internalOnly=142, string description=318, StyleType styleType=163, string sortPosition=320, StyleId styleIdForFill=332, StyleId styleIdForStrokeFill=333, StyleId styleIdForText=334, StyleId styleIdForEffect=335, StyleId styleIdForGrid=336, VariableDataMap variableConsumptionMap=307, VariableModeBySetMap variableModeBySetMap=316, VariableSetMode[] variableSetModes=312, VariableSetID variableSetID=313, VariableResolvedDataType variableResolvedType=314, VariableDataValues variableDataValues=315, VariableScope[] variableScopes=353, DocumentColorProfile documentColorProfile=349, Paint[] fillPaints=38, Paint[] strokePaints=39, float strokeWeight=26, StrokeAlign strokeAlign=29, StrokeJoin strokeJoin=31, StrokeCap strokeCap=30, float[] dashPattern=13, float miterLimit=25, bool borderStrokeWeightsIndependent=299, float borderTopWeight=295, float borderRightWeight=298, float borderBottomWeight=296, float borderLeftWeight=297, Effect[] effects=43, float cornerRadius=20, float cornerSmoothing=160, bool rectangleCornerRadiiIndependent=149, float rectangleTopLeftCornerRadius=145, float rectangleTopRightCornerRadius=146, float rectangleBottomRightCornerRadius=148, float rectangleBottomLeftCornerRadius=147, ConstraintType horizontalConstraint=28, ConstraintType verticalConstraint=37, bool frameMaskDisabled=115, bool resizeToFit=117, bool isStateGroup=225, StateGroupPropertyValueOrder[] stateGroupPropertyValueOrders=238, bool sectionContentsHidden=283, Color backgroundColor=50, StackMode stackMode=105, float stackSpacing=107, float stackCounterSpacing=324, StackWrap stackWrap=323, StackCounterAlignContent stackCounterAlignContent=343, float stackHorizontalPadding=209, float stackVerticalPadding=210, float stackPaddingRight=233, float stackPaddingBottom=234, StackJustify stackPrimaryAlignItems=230, StackAlign stackCounterAlignItems=231, StackSize stackPrimarySizing=229, StackSize stackCounterSizing=221, bool bordersTakeSpace=294, bool stackReverseZIndex=271, float gridColumnGap=438, float gridRowGap=437, GUIDPositionMap gridColumns=436, GUIDPositionMap gridRows=435, GUIDGridTrackSizeMap gridColumnsSizing=474, GUIDGridTrackSizeMap gridRowsSizing=475, float stackChildPrimaryGrow=232, StackCounterAlign stackChildAlignSelf=236, StackPositioning stackPositioning=269, OptionalVector minSize=325, OptionalVector maxSize=326, GUID gridColumnAnchor=440, GUID gridRowAnchor=439, uint gridColumnSpan=442, uint gridRowSpan=441, LayoutGrid[] layoutGrids=47, ExportSettings[] exportSettings=45, TextData textData=42, FontName fontName=41, float fontSize=21, Number lineHeight=40, Number letterSpacing=165, TextCase textCase=34, TextDecoration textDecoration=35, TextAlignHorizontal textAlignHorizontal=32, TextAlignVertical textAlignVertical=33, TextAutoResize textAutoResize=46, TextTruncation textTruncation=280, int maxLines=351, float paragraphSpacing=23, float paragraphIndent=22, float listSpacing=264, LeadingTrim leadingTrim=322, bool hangingPunctuation=337, bool hangingList=339, Hyperlink hyperlink=223, bool autoRename=14, bool fontVariantCommonLigatures=127, bool fontVariantContextualLigatures=128, string fontVersion=202, uint textUserLayoutVersion=203, uint textExplicitLayoutVersion=396, uint textBidiVersion=279, float textTracking=27, bool textDecorationSkipInk=412, EmojiImageSet emojiImageSet=391, uint styleID=49, Path[] fillGeometry=51, Path[] strokeGeometry=52, VectorData vectorData=48, VectorMirror handleMirroring=44, uint count=10, float starInnerScale=24, ArcData arcData=195, BooleanOperation booleanOperation=36, string symbolDescription=144, VariableWidthPoint[] variableWidthPoints=447, PluginData[] pluginData=204, SymbolData symbolData=113, NodeChange[] derivedSymbolData=125, GUID overriddenSymbolID=143, ComponentPropDef[] componentPropDefs=266, ComponentPropRef[] componentPropRefs=267, ComponentPropAssignment[] componentPropAssignments=268, VariantPropSpec[] variantPropSpecs=483, VariableDataMap parameterConsumptionMap=445, GUIDPath guidPath=111, PrototypeInteraction[] prototypeInteractions=226, PrototypeStartingPoint prototypeStartingPoint=249, ScrollDirection scrollDirection=159, ScrollBehavior scrollBehavior=186, OverlayPositionType overlayPositionType=198, OverlayBackgroundInteraction overlayBackgroundInteraction=200, OverlayBackgroundAppearance overlayBackgroundAppearance=201 +message NodeChange GUID guid=1, NodePhase phase=2, ParentIndex parentIndex=3, NodeType type=4, string name=5, bool visible=6, bool locked=7, float opacity=8, BlendMode blendMode=9, Vector size=11, Matrix transform=12, bool mask=16, MaskType maskType=317, float backgroundOpacity=19, bool backgroundEnabled=15, bool internalOnly=142, string description=318, StyleType styleType=163, string sortPosition=320, StyleId styleIdForFill=332, StyleId styleIdForStrokeFill=333, StyleId styleIdForText=334, StyleId styleIdForEffect=335, StyleId styleIdForGrid=336, VariableDataMap variableConsumptionMap=307, VariableModeBySetMap variableModeBySetMap=316, VariableSetMode[] variableSetModes=312, VariableSetID variableSetID=313, VariableResolvedDataType variableResolvedType=314, VariableDataValues variableDataValues=315, VariableScope[] variableScopes=353, DocumentColorProfile documentColorProfile=349, Paint[] fillPaints=38, Paint[] strokePaints=39, float strokeWeight=26, StrokeAlign strokeAlign=29, StrokeJoin strokeJoin=31, StrokeCap strokeCap=30, float[] dashPattern=13, float miterLimit=25, bool borderStrokeWeightsIndependent=299, float borderTopWeight=295, float borderRightWeight=298, float borderBottomWeight=296, float borderLeftWeight=297, Effect[] effects=43, float cornerRadius=20, float cornerSmoothing=160, bool rectangleCornerRadiiIndependent=149, float rectangleTopLeftCornerRadius=145, float rectangleTopRightCornerRadius=146, float rectangleBottomRightCornerRadius=148, float rectangleBottomLeftCornerRadius=147, ConstraintType horizontalConstraint=28, ConstraintType verticalConstraint=37, bool frameMaskDisabled=115, bool resizeToFit=117, bool isStateGroup=225, StateGroupPropertyValueOrder[] stateGroupPropertyValueOrders=238, bool sectionContentsHidden=283, Color backgroundColor=50, StackMode stackMode=105, float stackSpacing=107, float stackCounterSpacing=324, StackWrap stackWrap=323, StackCounterAlignContent stackCounterAlignContent=343, float stackHorizontalPadding=209, float stackVerticalPadding=210, float stackPaddingRight=233, float stackPaddingBottom=234, StackJustify stackPrimaryAlignItems=230, StackAlign stackCounterAlignItems=231, StackSize stackPrimarySizing=229, StackSize stackCounterSizing=221, bool bordersTakeSpace=294, bool stackReverseZIndex=271, float gridColumnGap=438, float gridRowGap=437, GUIDPositionMap gridColumns=436, GUIDPositionMap gridRows=435, GUIDGridTrackSizeMap gridColumnsSizing=474, GUIDGridTrackSizeMap gridRowsSizing=475, float stackChildPrimaryGrow=232, StackCounterAlign stackChildAlignSelf=236, StackPositioning stackPositioning=269, OptionalVector minSize=325, OptionalVector maxSize=326, GUID gridColumnAnchor=440, GUID gridRowAnchor=439, uint gridColumnSpan=442, uint gridRowSpan=441, LayoutGrid[] layoutGrids=47, ExportSettings[] exportSettings=45, TextData textData=42, FontName fontName=41, float fontSize=21, Number lineHeight=40, Number letterSpacing=165, TextCase textCase=34, TextDecoration textDecoration=35, TextAlignHorizontal textAlignHorizontal=32, TextAlignVertical textAlignVertical=33, TextAutoResize textAutoResize=46, TextTruncation textTruncation=280, int maxLines=351, float paragraphSpacing=23, float paragraphIndent=22, float listSpacing=264, LeadingTrim leadingTrim=322, bool hangingPunctuation=337, bool hangingList=339, Hyperlink hyperlink=223, bool autoRename=14, bool fontVariantCommonLigatures=127, bool fontVariantContextualLigatures=128, string fontVersion=202, uint textUserLayoutVersion=203, uint textExplicitLayoutVersion=396, uint textBidiVersion=279, float textTracking=27, bool textDecorationSkipInk=412, EmojiImageSet emojiImageSet=391, uint styleID=49, Path[] fillGeometry=51, Path[] strokeGeometry=52, VectorData vectorData=48, VectorMirror handleMirroring=44, uint count=10, float starInnerScale=24, ArcData arcData=195, BooleanOperation booleanOperation=36, string symbolDescription=144, VariableWidthPoint[] variableWidthPoints=447, PluginData[] pluginData=204, SymbolData symbolData=113, NodeChange[] derivedSymbolData=125, GUID overriddenSymbolID=143, ComponentPropDef[] componentPropDefs=266, ComponentPropRef[] componentPropRefs=267, ComponentPropAssignment[] componentPropAssignments=268, VariantPropSpec[] variantPropSpecs=483, VariableDataMap parameterConsumptionMap=445, GUIDPath guidPath=111, PrototypeInteraction[] prototypeInteractions=226, PrototypeStartingPoint prototypeStartingPoint=249, ScrollDirection scrollDirection=159, ScrollBehavior scrollBehavior=186, OverlayPositionType overlayPositionType=198, OverlayBackgroundInteraction overlayBackgroundInteraction=200, OverlayBackgroundAppearance overlayBackgroundAppearance=201, Color prototypeBackgroundColor=141 struct Blob byte[] bytes message Message MessageType type=1, uint sessionID=2, NodeChange[] nodeChanges=4, Blob[] blobs=6 "; diff --git a/crates/format/src/fig/export/layer.rs b/crates/format/src/fig/export/layer.rs index bebd09059..201246648 100644 --- a/crates/format/src/fig/export/layer.rs +++ b/crates/format/src/fig/export/layer.rs @@ -26,7 +26,15 @@ impl<'d> Exporter<'d> { if !n.guides.is_empty() { self.warn("ruler guides were left out"); } - if *prototype != Default::default() { + let defaults = figcraft_doc::proto::PrototypeSettings::default(); + // Every page writes its colour, so Figma shows the same one (a page without the field shows Figma's own default). + // The colour is written opaque: the record measured has alpha 1, and the import reads the colour as opaque and + // an alpha of 0 as no background. + f.push(("prototypeBackgroundColor", color(prototype.background.with_alpha(1.0)))); + if prototype.background.a < 1.0 { + self.warn("a prototype background's opacity was left out"); + } + if (figcraft_doc::proto::PrototypeSettings { background: defaults.background, ..prototype.clone() }) != defaults { self.warn("prototype device settings were left out"); } self.modes(n, &mut f); diff --git a/crates/format/src/fig/proto_background_tests.rs b/crates/format/src/fig/proto_background_tests.rs new file mode 100644 index 000000000..eec5171a7 --- /dev/null +++ b/crates/format/src/fig/proto_background_tests.rs @@ -0,0 +1,113 @@ +//! A page's prototype background in `.fig` exports. + +use figcraft_doc::color::Color; +use figcraft_doc::proto::{DeviceRotation, PrototypeSettings}; +use figcraft_doc::{Document, NodeKind}; + +use super::kiwi::Kv; +use super::{Archive, decode_canvas, export, import}; + +fn blue() -> Color { + Color::from_rgb8_const(0x33, 0x66, 0x99) +} + +/// The background of the first page, and its device, after exporting and importing `doc`. +fn back(doc: &Document) -> (Color, String, Vec) { + let (bytes, warnings) = export(doc, None).unwrap(); + let (imported, _) = import(&bytes, "x").unwrap(); + let page = imported.first_page().and_then(|p| imported.node(p)).unwrap(); + let NodeKind::Page { prototype, .. } = &page.kind else { panic!("not a page") }; + (prototype.background, prototype.device.clone(), warnings) +} + +/// The `prototypeBackgroundColor` (r, g, b, a) in the record the export writes for the page of `doc`. +fn written(doc: &Document) -> Option<[f32; 4]> { + let (bytes, _) = export(doc, None).unwrap(); + let archive = Archive::open(&bytes).unwrap(); + let (schema, message) = decode_canvas(&archive.canvas).unwrap(); + let msg = schema.decode_message(schema.find("Message").unwrap(), &message).unwrap(); + let page = msg.get("nodeChanges").unwrap().list().iter().find(|n| n.get("type").and_then(Kv::str) == Some("CANVAS")).unwrap(); + page.get("prototypeBackgroundColor").map(|c| ["r", "g", "b", "a"].map(|k| c.get(k).and_then(Kv::f64).unwrap() as f32)) +} + +fn with_prototype(set: impl FnOnce(&mut figcraft_doc::proto::PrototypeSettings)) -> Document { + let mut doc = Document::new("t"); + let page = doc.first_page().unwrap(); + if let Some(NodeKind::Page { prototype, .. }) = doc.node_mut(page).map(|n| &mut n.kind) { + set(prototype); + } + doc +} + +#[test] +fn a_pages_prototype_background_survives_a_fig_export() { + let doc = with_prototype(|p| p.background = blue()); + assert_eq!(written(&doc), Some([blue().r, blue().g, blue().b, 1.0])); + let (background, _, warnings) = back(&doc); + assert_eq!(background, blue()); + assert!(warnings.iter().all(|w| !w.contains("prototype")), "{warnings:?}"); +} + +#[test] +fn a_page_with_a_device_keeps_its_background_and_warns_for_the_device() { + let doc = with_prototype(|p| { + p.background = blue(); + p.device = "iPhone 17".into(); + }); + let (background, _, warnings) = back(&doc); + assert_eq!(background.to_hex(), blue().to_hex()); + assert!(warnings.iter().any(|w| w.contains("prototype device settings were left out")), "{warnings:?}"); +} + +#[test] +fn a_default_page_writes_its_prototype_background_so_figma_shows_the_same_colour() { + let doc = with_prototype(|_| {}); + let default = PrototypeSettings::default().background; + assert_eq!(default.to_hex(), "1E1E1E"); + assert_eq!(written(&doc), Some([default.r, default.g, default.b, 1.0])); + let (background, _, warnings) = back(&doc); + assert_eq!(background, default); + assert!(warnings.iter().all(|w| !w.contains("prototype")), "{warnings:?}"); +} + +#[test] +fn the_schema_numbers_the_prototype_background() { + let s = super::kiwi::Schema::parse(super::export::SCHEMA).unwrap(); + let def = |n: &str| s.defs.iter().find(|d| d.name == n).unwrap(); + let id = |f: &str| def("NodeChange").fields.iter().find(|x| x.name == f).unwrap().value; + assert_eq!(id("prototypeBackgroundColor"), 141); +} + +#[test] +fn each_device_setting_alone_warns_and_keeps_the_default_background() { + let settings: [fn(&mut PrototypeSettings); 5] = [ + |p| p.device = "iPhone 17".into(), + |p| p.rotation = DeviceRotation::Landscape, + |p| p.color = "White".into(), + |p| p.custom_size = [320.0, 480.0], + |p| p.responsive = true, + ]; + for (i, set) in settings.into_iter().enumerate() { + let doc = with_prototype(set); + let default = PrototypeSettings::default().background; + assert_eq!(written(&doc), Some([default.r, default.g, default.b, 1.0]), "setting {i}"); + let (_, _, warnings) = back(&doc); + assert!(warnings.iter().any(|w| w == "prototype device settings were left out"), "setting {i}: {warnings:?}"); + } +} + +#[test] +fn a_prototype_background_is_written_opaque() { + // The import reads an alpha of 0 as no background, and any other alpha as 1. + for alpha in [0.0, 0.5] { + let doc = with_prototype(|p| p.background = blue().with_alpha(alpha)); + assert_eq!(written(&doc), Some([blue().r, blue().g, blue().b, 1.0]), "alpha {alpha}"); + let (background, _, warnings) = back(&doc); + assert_eq!(background, blue(), "alpha {alpha}"); + assert!(warnings.iter().any(|w| w == "a prototype background's opacity was left out"), "alpha {alpha}: {warnings:?}"); + } + // The default colour is written opaque too. + let doc = with_prototype(|p| p.background = p.background.with_alpha(0.5)); + let default = PrototypeSettings::default().background; + assert_eq!(written(&doc), Some([default.r, default.g, default.b, 1.0])); +} diff --git a/crates/format/src/fig/text_list_tests.rs b/crates/format/src/fig/text_list_tests.rs index a2d6702bc..ef0439694 100644 --- a/crates/format/src/fig/text_list_tests.rs +++ b/crates/format/src/fig/text_list_tests.rs @@ -64,7 +64,7 @@ fn numbered_lists_keep_their_start() { assert_eq!(starts(&doc, "From 1"), [(N, 0)]); assert_eq!(starts(&doc, "From 2"), [(N, 1)], "shows 2."); assert_eq!(starts(&doc, "First only"), [(N, 3), (N, 0), (N, 0)]); - assert_eq!(starts(&doc, "Every line"), [(N, 3), (N, 3), (N, 3)]); + assert_eq!(starts(&doc, "Every line"), [(N, 3), (N, 0), (N, 0)], "Figma writes the start on every line; only the first counts"); assert_eq!(starts(&doc, "Mixed"), [(P, 0), (N, 4), (B, 0)], "bullets have no number, so no start"); assert_eq!(starts(&doc, "Junk"), [(N, 0)], "a negative offset counts from 1"); } @@ -89,5 +89,23 @@ fn the_export_writes_where_a_list_starts() { // line or per list counts the same); bullets and plain lines carry none. assert_eq!(offsets, [1.0, 1.0, 0.0, 5.0, 0.0]); let (back, _) = import(&bytes, "x").unwrap(); - assert_eq!(starts(&back, "List"), [(N, 1), (N, 1), (P, 0), (N, 5), (B, 0)]); + assert_eq!(starts(&back, "List"), [(N, 1), (N, 0), (P, 0), (N, 5), (B, 0)], "reads back as it went in"); +} + +#[test] +fn a_start_on_every_line_counts_only_where_the_list_starts() { + use ListStyle::{None as P, Numbered as N}; + let nodes = vec![ + node(0, None, "DOCUMENT", "Document", vec![]), + node(1, Some((0, "!")), "CANVAS", "Page", vec![]), + text_node(2, "Three", "a\nb\nc", vec![line("ORDERED_LIST", 4, true), line("ORDERED_LIST", 4, false), line("ORDERED_LIST", 4, false)]), + text_node(3, "Split", "a\nb\nc", vec![line("ORDERED_LIST", 4, true), line("PLAIN", 4, false), line("ORDERED_LIST", 0, true)]), + text_node(4, "Two lists", "a\nb\nc", vec![line("ORDERED_LIST", 4, true), line("PLAIN", 4, false), line("ORDERED_LIST", 6, true)]), + ]; + let sc = Schema::parse(LIST_SCHEMA).unwrap(); + let (doc, warnings) = import(&canvas(&sc, &o(vec![("nodeChanges", arr(nodes))])), "x").unwrap(); + assert!(warnings.is_empty(), "{warnings:?}"); + assert_eq!(starts(&doc, "Three"), [(N, 4), (N, 0), (N, 0)]); + assert_eq!(starts(&doc, "Split"), [(N, 4), (P, 0), (N, 0)]); + assert_eq!(starts(&doc, "Two lists"), [(N, 4), (P, 0), (N, 6)], "a second list keeps its own start"); } diff --git a/crates/format/src/rest/tests.rs b/crates/format/src/rest/tests.rs index 6dc710979..6630ee406 100644 --- a/crates/format/src/rest/tests.rs +++ b/crates/format/src/rest/tests.rs @@ -675,7 +675,11 @@ fn kitchen_sink() -> Value { ]}, {"id": "k9", "name": "Sec", "type": "SECTION", "sectionContentsHidden": true, "relativeTransform": at(0.0, 0.0), "size": {"x": 50, "y": 50}, "children": [{"id": "k10", "name": "Use", "type": "INSTANCE", "componentId": "3:1", "relativeTransform": at(0.0, 0.0), "size": {"x": 24, "y": 24}, - "componentProperties": {"Show#4:1": {"type": "BOOLEAN", "value": false}}}]} + "componentProperties": {"Show#4:1": {"type": "BOOLEAN", "value": false}}}]}, + {"id": "k11", "name": "Listed", "type": "TEXT", "relativeTransform": at(0.0, 0.0), "size": {"x": 10, "y": 10}, "characters": "a\nb\nc\nd\ne\n", + "style": {"fontFamily": "Inter", "fontSize": 12}, + "lineTypes": ["ORDERED", "ORDERED", "ORDERED", "UNORDERED", "ORDERED", "ORDERED"], "lineIndentations": [0, 0, 1, 0, 300, 0], + "listStartOffsets": [4, 4, 3, 2, 7, 9]} ]); if let (Some(kids), Some(more)) = (v.pointer_mut("/document/children/0/children").and_then(Value::as_array_mut), extra.as_array()) { kids.extend(more.iter().cloned()); @@ -692,6 +696,9 @@ fn kitchen_sink_imports_cleanly() { assert!(matches!(named(&doc, "Sec").kind, NodeKind::Section { contents_hidden: true })); assert!(matches!(&named(&doc, "Use").kind, NodeKind::Instance { props, .. } if props.get("Show") == Some(&json!(false)))); assert!(matches!(named(&doc, "Txt").kind, NodeKind::Text(ref t) if t.list == ListStyle::Numbered && t.runs.len() == 3)); + let NodeKind::Text(l) = &named(&doc, "Listed").kind else { panic!("not text") }; + let got: Vec<(u8, u32)> = (0..l.paragraph_count()).map(|p| (l.para_list(p).indent, l.para_list(p).start_offset)).collect(); + assert_eq!(got, [(0, 4), (0, 0), (1, 3), (0, 0), (8, 7), (0, 9)], "starts stay where a count starts; the level is capped"); assert!(warnings.iter().all(|w| !w.contains("panick")), "{warnings:?}"); } @@ -801,3 +808,15 @@ fn an_arc_without_an_end_is_whole_wherever_it_starts() { assert_eq!(sweep, std::f64::consts::TAU, "start {start}"); } } + +#[test] +fn a_start_on_every_line_counts_only_where_the_list_starts() { + let (doc, _) = one(json!([ + {"id": "t1", "name": "Every", "type": "TEXT", "relativeTransform": at(0.0, 0.0), "size": {"x": 10, "y": 10}, "characters": "a\nb\nc", + "style": {"fontFamily": "Inter", "fontSize": 12}, + "lineTypes": ["ORDERED", "ORDERED", "ORDERED"], "listStartOffsets": [4, 4, 4]} + ])); + let figcraft_doc::NodeKind::Text(t) = &named(&doc, "Every").kind else { panic!("not text") }; + let offsets: Vec = (0..t.paragraph_count()).map(|p| t.para_list(p).start_offset).collect(); + assert_eq!(offsets, [4, 0, 0]); +} diff --git a/crates/format/src/rest/text.rs b/crates/format/src/rest/text.rs index f53eb0684..971e2fb8f 100644 --- a/crates/format/src/rest/text.rs +++ b/crates/format/src/rest/text.rs @@ -283,6 +283,9 @@ fn lists(v: &Value, td: &mut TextData) { .collect(); // Clamp the levels and fold one style for all back into the layer's list style. td.set_para_lists(0, td.char_count(), |_| {}); + // Only the item where a numbered list starts counting keeps its start; Figma writes the start on + // every line of the list, and a list split later must restart at 1. + td.keep_list_starts_where_counting_starts(); } /// The decoration's style, thickness, offset, skip ink and colour (`{value, unit}` lengths with diff --git a/crates/text/src/layout.rs b/crates/text/src/layout.rs index a003deb42..ebe35c722 100644 --- a/crates/text/src/layout.rs +++ b/crates/text/src/layout.rs @@ -1469,25 +1469,27 @@ pub(crate) fn list_markers(lists: &[ParaList]) -> Vec { // "Figma bullets will keep the same styling at all levels of indentation." (Create bulleted // and numbered lists) const BULLET: &str = "\u{2022}"; - let mut count = [(ListStyle::None, 0usize); figcraft_doc::MAX_LIST_INDENT as usize + 1]; + let starts = figcraft_doc::list_item_starts_counting(lists); + let mut count = [0usize; figcraft_doc::MAX_LIST_INDENT as usize + 1]; lists .iter() - .map(|pl| { + .zip(starts) + .map(|(pl, starts)| { if pl.list == ListStyle::None { - count.fill((ListStyle::None, 0)); + count.fill(0); return String::new(); } let d = usize::from(pl.indent).min(count.len() - 1); for c in count.iter_mut().skip(d + 1) { - *c = (ListStyle::None, 0); + *c = 0; } let Some(c) = count.get_mut(d) else { return String::new() }; let first = usize::try_from(pl.start_offset).unwrap_or(usize::MAX).saturating_add(1); - *c = if c.0 == pl.list { (pl.list, c.1.saturating_add(1)) } else { (pl.list, first) }; + *c = if starts { first } else { c.saturating_add(1) }; match (pl.list, d % 3) { - (ListStyle::Numbered, 1) => format!("{}.", alpha(c.1)), - (ListStyle::Numbered, 2) => format!("{}.", roman(c.1)), - (ListStyle::Numbered, _) => format!("{}.", c.1), + (ListStyle::Numbered, 1) => format!("{}.", alpha(*c)), + (ListStyle::Numbered, 2) => format!("{}.", roman(*c)), + (ListStyle::Numbered, _) => format!("{}.", *c), _ => BULLET.to_string(), } }) diff --git a/crates/ui-egui/locales/en.toml b/crates/ui-egui/locales/en.toml index 71e6ff010..777f6596a 100644 --- a/crates/ui-egui/locales/en.toml +++ b/crates/ui-egui/locales/en.toml @@ -522,6 +522,7 @@ name = "English" "Duo" = "Duo" "Duplicate" = "Duplicate" "Duplicate by dragging" = "Duplicate by dragging" +"Duplicate group" = "Duplicate group" "Duplicate mode" = "Duplicate mode" "Duplicate page" = "Duplicate page" "Edit" = "Edit" @@ -1578,6 +1579,11 @@ name = "English" "Text content" = "Text content" "Text on a path" = "Text on a path" "Text size" = "Text size" +"Small" = "Small" +"Medium" = "Medium" +"Large" = "Large" +"Extra large" = "Extra large" +"Huge" = "Huge" "Text style" = "Text style" "Text styles" = "Text styles" "Texts" = "Texts" diff --git a/crates/ui-egui/src/board_ui_tests.rs b/crates/ui-egui/src/board_ui_tests.rs index 867ba139a..bd0a8b21f 100644 --- a/crates/ui-egui/src/board_ui_tests.rs +++ b/crates/ui-egui/src/board_ui_tests.rs @@ -398,3 +398,29 @@ fn cmd_while_moving_a_connector_end_places_it_on_the_object() { drag(&mut u, Modifiers::NONE); assert!(matches!(end(&u), figcraft_doc::End::Node { at: None, side: figcraft_doc::Side::Right, .. }), "{:?}", end(&u)); } + +#[test] +fn a_selected_sticky_has_a_size_menu_instead_of_the_size_cells() { + let mut u = board(); + let r = u.app.session.execute("board.sticky", &json!({"x": 0, "y": 0, "text": "Alpha"})).unwrap(); + let note = figcraft_engine::board::text_of(u.app.session.doc().unwrap(), id(&r)).unwrap(); + u.frame(vec![]); + u.frame(vec![]); + let shapes = flat(&u.frame_output(vec![]).shapes); + assert!(has_text(&shapes, "Small"), "the menu reads Small"); + assert!(!has_text(&shapes, "XL"), "no S/M/L/XL cells"); + // The menu sits after the 8 colours (208 from the bar's left edge). + let b = bar(&u).expect("the bar shows"); + click(&mut u, pos2(b.min.x + 208.0 + 40.0, b.center().y)); + let shapes = flat(&u.frame_output(vec![]).shapes); + // Each row is padded to line up with the check mark on the current one. + for name in ["✓ Small", " Medium", " Large", " Extra large", " Huge"] { + assert!(has_text(&shapes, name), "{name:?} in the menu"); + } + click(&mut u, text_center(&shapes, " Large")); + let size = |u: &Ui| u.app.session.doc().unwrap().node(note).unwrap().kind.text().unwrap().style.font_size; + assert_eq!(size(&u), 40.0); + u.frame(vec![]); + let shapes = flat(&u.frame_output(vec![]).shapes); + assert!(has_text(&shapes, "Large") && !has_text(&shapes, "Small"), "the menu reads Large"); +} diff --git a/crates/ui-egui/src/canvas/board_bar.rs b/crates/ui-egui/src/canvas/board_bar.rs index e75116b66..fa3d5e4e5 100644 --- a/crates/ui-egui/src/canvas/board_bar.rs +++ b/crates/ui-egui/src/canvas/board_bar.rs @@ -4,7 +4,7 @@ use egui::{Color32, CornerRadius, Pos2, Rect, Sense, Stroke, StrokeKind, Ui, pos2, vec2}; use figcraft_doc::{BOARD_COLORS, BoardItem, BoardShape, NodeId, NodeKind, Routing, Stamp, StrokeCap}; -use figcraft_engine::board::{BoardTool, TEXT_SIZES}; +use figcraft_engine::board::{BoardTool, STICKY_SIZES, TEXT_SIZES}; use figcraft_engine::board_grid::GridStyle; use serde_json::{Value, json}; @@ -96,6 +96,9 @@ struct Has { color: bool, shape: Option, text: bool, + /// The first selected sticky's text size: stickies take a size menu (not the S/M/L/XL cells) + /// when they are the only text-bearing objects selected. + sticky: Option, connector: Option, /// Every selected board object is a connector: the colour part offers any colour too. only_lines: bool, @@ -121,7 +124,15 @@ fn has(app: &FigApp) -> Option { for n in ds.selection.iter().filter_map(|id| ds.doc.node(*id)) { others |= n.board.is_some() && !matches!(n.board, Some(BoardItem::Connector(_))); match &n.board { - Some(BoardItem::Sticky { .. } | BoardItem::Ink) => h.color = true, + Some(BoardItem::Sticky { .. }) => { + h.color = true; + let size = figcraft_engine::board::text_of(&ds.doc, n.id) + .and_then(|t| ds.doc.node(t)) + .and_then(|t| t.kind.text()) + .map_or(figcraft_engine::board::STICKY_TEXT_SIZE, |t| t.style.font_size); + h.sticky.get_or_insert(size); + } + Some(BoardItem::Ink) => h.color = true, Some(BoardItem::Shape { shape }) => { h.color = true; h.text = true; @@ -154,6 +165,8 @@ const SWATCH: f32 = 20.0; const GAP: f32 = 4.0; /// The room each part takes after its controls (the divider and the gap around it). const PART_END: f32 = 8.0; +/// The sticky size menu's width: its name ("Extra large") and the chevron. +const STICKY_W: f32 = 96.0; impl Has { /// The bar's width for these parts. @@ -168,6 +181,9 @@ impl Has { if self.shape.is_some() { w += CELL + 12.0 + GAP + PART_END; } + if self.sticky.is_some() && !self.text { + w += STICKY_W + PART_END; + } if self.text { w += TEXT_SIZES.len() as f32 * (CELL + 2.0) + PART_END; } @@ -226,6 +242,8 @@ pub fn show(app: &mut FigApp, ctx: &egui::Context) { } if h.text { x = size_part(app, ui, x, cy, &t); + } else if let Some(size) = h.sticky { + x = sticky_size_part(app, ui, size, pos2(x, cy), &t); } if h.table { x = crate::board_picker::table_part(app, ui, x, cy, &t); @@ -338,6 +356,42 @@ fn size_part(app: &mut FigApp, ui: &mut Ui, mut x: f32, cy: f32, t: &Tokens) -> divider(ui, t, x, cy) } +/// A sticky size's name as the UI says it (`None` when no entry has that size). +fn sticky_size_label(size: f64) -> Option<&'static str> { + STICKY_SIZES.iter().find(|(_, s)| (*s - size).abs() < 0.01).map(|(name, _)| match *name { + "Small" => tr_noop("Small"), + "Medium" => tr_noop("Medium"), + "Large" => tr_noop("Large"), + "Extra large" => tr_noop("Extra large"), + _ => tr_noop("Huge"), + }) +} + +/// The sticky text size menu at `at` (its left edge and middle), showing `size` by name, or as a +/// number when no entry has it; `board.setStyle {fontSize}`; where the next part starts. +fn sticky_size_part(app: &mut FigApp, ui: &mut Ui, size: f64, at: Pos2, t: &Tokens) -> f32 { + let r = Rect::from_min_size(pos2(at.x, at.y - CELL / 2.0), vec2(STICKY_W, CELL)); + let tip = tr("Text size"); + let resp = ui.interact(r, ui.scope_id().with("bb_sticky_size"), Sense::click()).on_hover_text(tip); + a11y::menu_button(&resp, tip, a11y::menu_open(&resp)); + if resp.hovered() { + ui.painter().rect_filled(r, CornerRadius::same(5), t.hover); + } + let name = sticky_size_label(size).map_or_else(|| format!("{}", (size * 100.0).round() / 100.0), |l| tr(l).to_string()); + ui.painter().text(pos2(r.min.x + 8.0, at.y), egui::Align2::LEFT_CENTER, name, semibold(11.0), t.text); + icons::paint(ui.painter(), Rect::from_center_size(pos2(r.max.x - 9.0, at.y), vec2(12.0, 12.0)), Icon::Chevron, t.icon_secondary); + crate::right::menu_popup(&resp).show(|ui| { + for (name, value) in STICKY_SIZES { + let label = sticky_size_label(value).unwrap_or(name); + if crate::right::menu_check(ui, (value - size).abs() < 0.01, tr(label), "") { + app.run("board.setStyle", json!({"fontSize": value})); + ui.close(); + } + } + }); + divider(ui, t, at.x + STICKY_W, at.y) +} + /// A start or end point menu's width: the end's picture and the menu's chevron. const CAP_W: f32 = 62.0; /// The line style menu's width. diff --git a/crates/ui-egui/src/dialogs/variables_panel.rs b/crates/ui-egui/src/dialogs/variables_panel.rs index 4367ac610..067d54ea9 100644 --- a/crates/ui-egui/src/dialogs/variables_panel.rs +++ b/crates/ui-egui/src/dialogs/variables_panel.rs @@ -574,6 +574,10 @@ fn group_rows(app: &mut FigApp, ui: &mut Ui, view: &View, coll: &Collection, st: start_rename(st, target.clone()); ui.close(); } + if menu_item(ui, tr("Duplicate group"), "") { + duplicate_group(app, &members, &list, g); + ui.close(); + } if menu_item(ui, tr("Delete group"), "") { let steps: Vec = members .iter() @@ -614,6 +618,28 @@ fn rename_group(app: &mut FigApp, members: &[&Variable], g: &str, new: &str, st: } } +/// Copy group `g` (its variables `members`, every mode, scope and setting) as the group named +/// after it plus " 2" (the next free number among the collection's groups `list`), in one undo +/// step. Each copy is `variable.duplicate` then a rename; an alias keeps pointing at its target. +fn duplicate_group(app: &mut FigApp, members: &[&Variable], list: &[String], g: &str) { + let (parent, leaf) = g.rsplit_once('/').map_or(("", g), |(p, l)| (p, l)); + let leaf = unique(leaf, |n| { + let full = if parent.is_empty() { n.to_string() } else { format!("{parent}/{n}") }; + full == g || list.contains(&full) || members.iter().any(|v| v.name.starts_with(&format!("{full}/"))) + }); + let copy = if parent.is_empty() { leaf } else { format!("{parent}/{leaf}") }; + let prefix = format!("{g}/"); + let mut steps: Vec = Vec::new(); + for (k, v) in members.iter().filter(|v| v.name.starts_with(&prefix)).enumerate() { + let tag = format!("copy{k}"); + steps.push(json!({"command": "variable.duplicate", "params": {"variable": v.id}, "as": tag})); + steps.push( + json!({"command": "variable.update", "params": {"variable": {"$ref": tag}, "name": format!("{copy}/{}", &v.name[prefix.len()..])}}), + ); + } + app.run("command.batch", json!({"label": "Duplicate group", "commands": steps})); +} + fn create_collection(app: &mut FigApp, vars: &Variables, st: &mut Editor) { let name = unique("Collection", |n| vars.collections.iter().any(|c| c.name == n)); if let Some(id) = diff --git a/crates/ui-egui/src/header_icon_size_tests.rs b/crates/ui-egui/src/header_icon_size_tests.rs index 917276c2a..a72a44b4e 100644 --- a/crates/ui-egui/src/header_icon_size_tests.rs +++ b/crates/ui-egui/src/header_icon_size_tests.rs @@ -6,11 +6,13 @@ use egui::{Context, Rect, pos2, vec2}; use crate::icons::{self, Icon}; use crate::widgets::{icon_button_at, icon_glyph_rect, section_header}; -/// Bounding box of everything painted in one frame of `add`. -fn painted_box(add: impl FnOnce(&mut egui::Ui)) -> Rect { +/// The bounding box of every glyph-like shape painted in one frame of `add`, one per shape, with +/// the pointer at `pointer` (hover-only buttons) when given. +pub(crate) fn painted_rects(pointer: Option, add: impl FnOnce(&mut egui::Ui)) -> Vec { let ctx = Context::default(); let mut add = Some(add); - let raw = egui::RawInput { screen_rect: Some(Rect::from_min_size(pos2(0.0, 0.0), vec2(400.0, 200.0))), ..Default::default() }; + let events = pointer.map(egui::Event::PointerMoved).into_iter().collect(); + let raw = egui::RawInput { screen_rect: Some(Rect::from_min_size(pos2(0.0, 0.0), vec2(400.0, 600.0))), events, ..Default::default() }; let mut out = ctx.run_ui(raw, |ui| { if let Some(f) = add.take() { f(ui); @@ -21,7 +23,27 @@ fn painted_box(add: impl FnOnce(&mut egui::Ui)) -> Rect { .iter() .filter(|s| matches!(s.shape, egui::Shape::Path(_) | egui::Shape::Mesh(_) | egui::Shape::LineSegment { .. } | egui::Shape::Circle(_))) .map(|s| s.shape.visual_bounding_rect()) - .fold(Rect::NOTHING, |a, b| a.union(b)) + .collect() +} + +/// Bounding box of everything painted in one frame of `add`. +fn painted_box(add: impl FnOnce(&mut egui::Ui)) -> Rect { + painted_rects(None, add).into_iter().fold(Rect::NOTHING, |a, b| a.union(b)) +} + +/// Whether `painted` holds `icon` drawn at the size of a 24 pt `icons::button`'s glyph (16 pt): the +/// reference glyph's shapes, moved by one offset, are all among `painted` (same sizes and spacing, +/// so a three-dot glyph's spread counts too). +pub(crate) fn paints_icon_at_button_size(painted: &[Rect], icon: Icon) -> bool { + let reference = painted_rects(None, |ui| { + icons::button(ui, icon, 24.0, false, "reference"); + }); + let same = |a: Rect, b: Rect| (a.min - b.min).length() < 0.5 && (a.size() - b.size()).length() < 0.5; + let Some(first) = reference.first() else { return false }; + painted.iter().any(|p| { + let shift = p.min - first.min; + reference.iter().all(|r| painted.iter().any(|q| same(*q, r.translate(shift)))) + }) } /// The header's eye, `icon_button_at`'s and a fill row's (`icons::button`, the reporter's diff --git a/crates/ui-egui/src/home/online.rs b/crates/ui-egui/src/home/online.rs index a011836dd..0b01017bb 100644 --- a/crates/ui-egui/src/home/online.rs +++ b/crates/ui-egui/src/home/online.rs @@ -180,7 +180,7 @@ fn row(app: &mut FigApp, ui: &mut Ui, t: &Tokens, f: &OnlineFile, busy: bool) { if mresp.hovered() { ui.painter().rect_filled(more, CornerRadius::same(5), t.pressed); } - icons::paint(ui.painter(), more.shrink(5.0), Icon::Dots, t.icon); + icons::paint(ui.painter(), crate::widgets::icon_glyph_rect(more), Icon::Dots, t.icon); let ctx = ui.ctx().clone(); let at = (f.server.as_str(), f.file.as_str()); crate::right::menu_popup(&mresp).width(240.0).show(|ui| { @@ -302,7 +302,7 @@ fn team_row(app: &mut FigApp, ui: &mut Ui, t: &Tokens, server: &str, web: &str, if mresp.hovered() { ui.painter().rect_filled(more, CornerRadius::same(5), t.pressed); } - icons::paint(ui.painter(), more.shrink(5.0), Icon::Dots, t.icon); + icons::paint(ui.painter(), crate::widgets::icon_glyph_rect(more), Icon::Dots, t.icon); crate::right::menu_popup(&mresp).width(240.0).show(|ui| { if crate::right::menu_item(ui, tr("Open"), "") { open_team(app, server, f); @@ -427,3 +427,29 @@ pub fn inspect(app: &FigApp) -> Value { "rename": app.ui.online.rename.as_ref().map(|r| &r.2), }) } + +#[cfg(test)] +mod icon_size_tests { + use super::*; + use crate::header_icon_size_tests::{painted_rects, paints_icon_at_button_size}; + use figcraft_engine::figcraft_collab::message::Access; + + /// The menu buttons of Online's file rows and team rows paint their dots at 16 pt (#2238). + #[test] + fn online_row_menus_paint_16pt() { + let t_app = || FigApp::new(figcraft_engine::Session::new(), Box::new(crate::NoServices)); + let mut app = t_app(); + let file = OnlineFile { server: "wss://share.example/".into(), file: "f".into(), name: "Trail".into(), ..OnlineFile::default() }; + let rows = painted_rects(None, |ui| { + let t = Tokens::get(ui.ctx()); + row(&mut app, ui, &t, &file, false); + }); + assert!(paints_icon_at_button_size(&rows, Icon::Dots), "file row menu is not 16 pt"); + let team = TeamFile { file: "f".into(), name: "Trail".into(), updated: 0, people: 0, access: Access::Edit }; + let teams = painted_rects(None, |ui| { + let t = Tokens::get(ui.ctx()); + team_row(&mut app, ui, &t, "wss://share.example/", "", &team); + }); + assert!(paints_icon_at_button_size(&teams, Icon::Dots), "team row menu is not 16 pt"); + } +} diff --git a/crates/ui-egui/src/icon_button_size_tests.rs b/crates/ui-egui/src/icon_button_size_tests.rs new file mode 100644 index 000000000..2d94f3fb8 --- /dev/null +++ b/crates/ui-egui/src/icon_button_size_tests.rs @@ -0,0 +1,37 @@ +//! Every 24 pt icon button paints its glyph at 16 pt, the size `icons::button` draws (#2238, after +//! the Design panel's in #2227). The panels' own buttons: the Layers panel's header, the Assets +//! panel's back button and the Dev Mode status button. The tests of the other panels sit beside +//! them (`present/tests.rs`, and the `icon_size_tests` modules of `versions`, `proto_panel`, +//! `online` and the style picker). + +use egui::{Rect, pos2, vec2}; +use figcraft_engine::Session; + +use crate::header_icon_size_tests::{painted_rects, paints_icon_at_button_size}; +use crate::icons::Icon; +use crate::{FigApp, NoServices}; + +fn app() -> FigApp { + FigApp::new(Session::new(), Box::new(NoServices)) +} + +#[test] +fn layers_and_assets_icon_buttons_paint_16pt() { + let mut a = app(); + let rail = painted_rects(None, |ui| crate::layers::left_panel(&mut a, ui)); + for icon in [Icon::Panels, Icon::Search, Icon::Plus] { + assert!(paints_icon_at_button_size(&rail, icon), "Layers panel: {icon:?} is not 16 pt"); + } + a.ui.libraries = true; + let back = painted_rects(None, |ui| crate::assets_panel::show(&mut a, ui)); + assert!(paints_icon_at_button_size(&back, Icon::ChevronLeft), "Assets panel: the back chevron is not 16 pt"); +} + +#[test] +fn the_dev_mode_status_button_paints_a_16pt_glyph() { + let mut a = app(); + let doc = a.session.doc().unwrap().clone(); + let button = Rect::from_min_size(pos2(20.0, 20.0), vec2(24.0, 24.0)); + let painted = painted_rects(None, |ui| crate::section_panel::status_icon(&mut a, ui, &doc, &[], button)); + assert!(paints_icon_at_button_size(&painted, Icon::Code), "the status button's code glyph is not 16 pt"); +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index c1f9811a8..19cb52397 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -132,6 +132,8 @@ mod home_tests; #[cfg(test)] mod host_save_tests; #[cfg(test)] +mod icon_button_size_tests; +#[cfg(test)] mod idle_tests; #[cfg(test)] mod ime_tests; diff --git a/crates/ui-egui/src/panels/assets_panel.rs b/crates/ui-egui/src/panels/assets_panel.rs index 0da5a9bee..41f7762ff 100644 --- a/crates/ui-egui/src/panels/assets_panel.rs +++ b/crates/ui-egui/src/panels/assets_panel.rs @@ -818,7 +818,7 @@ fn libraries_view(app: &mut FigApp, ui: &mut Ui) { if bresp.hovered() { ui.painter().rect_filled(back, CornerRadius::same(5), t.hover); } - icons::paint(ui.painter(), back.shrink(5.0), Icon::ChevronLeft, t.icon); + icons::paint(ui.painter(), crate::widgets::icon_glyph_rect(back), Icon::ChevronLeft, t.icon); ui.painter().text(pos2(back.max.x + 6.0, hr.center().y), Align2::LEFT_CENTER, tr("Libraries"), semibold(12.0), t.text); if bresp.clicked() { app.ui.libraries = false; diff --git a/crates/ui-egui/src/panels/layers.rs b/crates/ui-egui/src/panels/layers.rs index 71b9643a8..7179012b5 100644 --- a/crates/ui-egui/src/panels/layers.rs +++ b/crates/ui-egui/src/panels/layers.rs @@ -168,7 +168,7 @@ pub fn left_panel(app: &mut FigApp, ui: &mut Ui) { if hresp.hovered() { ui.painter().rect_filled(hr, CornerRadius::same(5), t.hover); } - icons::paint(ui.painter(), hr.shrink(5.0), Icon::Panels, t.icon); + icons::paint(ui.painter(), crate::widgets::icon_glyph_rect(hr), Icon::Panels, t.icon); if hresp.clicked() { app.run("view.minimize", json!({})); } @@ -204,7 +204,7 @@ fn pages(app: &mut FigApp, ui: &mut Ui) { if sresp.hovered() || app.ui.page_search { ui.painter().rect_filled(sr, CornerRadius::same(5), t.hover); } - icons::paint(ui.painter(), sr.shrink(5.0), Icon::Search, t.icon); + icons::paint(ui.painter(), crate::widgets::icon_glyph_rect(sr), Icon::Search, t.icon); let search_id = Id::unique("page_search_field"); if sresp.clicked() { app.ui.page_search = !app.ui.page_search; @@ -218,7 +218,7 @@ fn pages(app: &mut FigApp, ui: &mut Ui) { if aresp.hovered() { ui.painter().rect_filled(ar, CornerRadius::same(5), t.hover); } - icons::paint(ui.painter(), ar.shrink(5.0), Icon::Plus, t.icon); + icons::paint(ui.painter(), crate::widgets::icon_glyph_rect(ar), Icon::Plus, t.icon); if aresp.clicked() { app.ui.pages_focus = app.session.ds().ok().map(|d| d.uid); if !crate::menus::dev_mode_refuses(app, "page.add") { @@ -1090,7 +1090,7 @@ fn layers(app: &mut FigApp, ui: &mut Ui) { if sresp.hovered() || app.ui.layer_search { ui.painter().rect_filled(sr, CornerRadius::same(5), t.hover); } - icons::paint(ui.painter(), sr.shrink(5.0), Icon::Search, t.icon); + icons::paint(ui.painter(), crate::widgets::icon_glyph_rect(sr), Icon::Search, t.icon); let search_id = Id::unique("layer_search_field"); if sresp.clicked() { app.ui.layer_search = !app.ui.layer_search; diff --git a/crates/ui-egui/src/panels/proto_panel.rs b/crates/ui-egui/src/panels/proto_panel.rs index fa9f2585c..63b9278ac 100644 --- a/crates/ui-egui/src/panels/proto_panel.rs +++ b/crates/ui-egui/src/panels/proto_panel.rs @@ -374,7 +374,7 @@ fn icon_button(ui: &mut Ui, id: Id, rect: Rect, icon: Icon, tip: &str) -> bool { if resp.hovered() { ui.painter().rect_filled(rect, CornerRadius::same(5), t.hover); } - icons::paint(ui.painter(), rect.shrink(5.0), icon, t.icon); + icons::paint(ui.painter(), crate::widgets::icon_glyph_rect(rect), icon, t.icon); resp.clicked() } @@ -1354,3 +1354,21 @@ fn scroll_section(app: &mut FigApp, ui: &mut Ui, doc: &Document, sel: &[NodeId], }); } } + +#[cfg(test)] +mod icon_size_tests { + use super::*; + use crate::header_icon_size_tests::{painted_rects, paints_icon_at_button_size}; + + /// The panel's 24 pt icon buttons (flow play, preview, remove) paint their glyphs at 16 pt (#2238). + #[test] + fn prototype_icon_buttons_paint_16pt() { + for icon in [Icon::Play, Icon::Preview, Icon::Minus] { + let painted = painted_rects(None, |ui| { + let rect = Rect::from_min_size(pos2(20.0, 20.0), vec2(24.0, 24.0)); + icon_button(ui, Id::unique("proto_icon_size"), rect, icon, "x"); + }); + assert!(paints_icon_at_button_size(&painted, icon), "{icon:?} is not 16 pt"); + } + } +} diff --git a/crates/ui-egui/src/panels/section_panel.rs b/crates/ui-egui/src/panels/section_panel.rs index 4ea146924..0aa880052 100644 --- a/crates/ui-egui/src/panels/section_panel.rs +++ b/crates/ui-egui/src/panels/section_panel.rs @@ -71,7 +71,7 @@ pub fn status_icon(app: &mut FigApp, ui: &mut Ui, doc: &Document, ids: &[NodeId] Some((DevStatus::None, _)) | None => t.icon, Some(_) => t.accent_text, }; - icons::paint(ui.painter(), rect.shrink(5.0), Icon::Code, color); + icons::paint(ui.painter(), crate::widgets::icon_glyph_rect(rect), Icon::Code, color); menu_popup(&resp).width(160.0).show(|ui| status_menu(app, ui, ids, doc)); } diff --git a/crates/ui-egui/src/panels/versions.rs b/crates/ui-egui/src/panels/versions.rs index 7046b5fa7..73ed3eb16 100644 --- a/crates/ui-egui/src/panels/versions.rs +++ b/crates/ui-egui/src/panels/versions.rs @@ -441,7 +441,7 @@ fn version_row(ui: &mut Ui, row: &Row, last: bool, previewing: bool) -> Option Option { if more.hovered() || menu_open { ui.painter().rect_filled(br, CornerRadius::same(5), t.pressed); } - icons::paint(ui.painter(), br.shrink(5.0), Icon::Dots, t.icon); + icons::paint(ui.painter(), crate::widgets::icon_glyph_rect(br), Icon::Dots, t.icon); } let more = more.tip(tr("More")); let mut menu = |ui: &mut Ui| { @@ -607,3 +607,25 @@ fn buttons(ui: &mut Ui, primary: &str, enabled: bool) -> Option { }) .inner } + +#[cfg(test)] +mod icon_size_tests { + use super::*; + use crate::header_icon_size_tests::{painted_rects, paints_icon_at_button_size}; + + /// The version and branch rows' More buttons (shown on hover) paint their dots at 16 pt (#2238). + #[test] + fn version_and_branch_menus_paint_16pt() { + let over = Some(pos2(20.0, 20.0)); + let row = Row { id: "v".into(), name: "Draft".into(), description: String::new(), time: 0, auto: false }; + let version = painted_rects(over, |ui| { + version_row(ui, &row, true, false); + }); + assert!(paints_icon_at_button_size(&version, Icon::Dots), "version row menu is not 16 pt"); + let branch = BranchRow { id: "b".into(), name: "Try".into(), time: 0, state: BranchState::Active }; + let branches = painted_rects(over, |ui| { + branch_row(ui, &branch); + }); + assert!(paints_icon_at_button_size(&branches, Icon::Dots), "branch row menu is not 16 pt"); + } +} diff --git a/crates/ui-egui/src/popover.rs b/crates/ui-egui/src/popover.rs index d91558d46..82886227d 100644 --- a/crates/ui-egui/src/popover.rs +++ b/crates/ui-egui/src/popover.rs @@ -262,13 +262,13 @@ fn header_text(t: Tokens, dark: bool) -> Color32 { if dark { t.menu_text } else { t.text } } -/// The X: a 24-point button, its icon inset 6 (the colour picker's header). +/// The X: a 24-point button, its cross 16 points like every 24 pt icon button (the colour picker's header). fn close_button(ui: &mut Ui, id: Id, rect: Rect, dark: bool, t: Tokens) -> bool { let resp = ui.interact(rect, id, Sense::click()).tip(tr("Close")); if resp.hovered() { ui.painter().rect_filled(rect, CornerRadius::same(5), if dark { Color32::from_white_alpha(20) } else { t.hover }); } - icons::paint(ui.painter(), rect.shrink(6.0), Icon::Close, if dark { t.menu_text } else { t.icon }); + icons::paint(ui.painter(), crate::widgets::icon_glyph_rect(rect), Icon::Close, if dark { t.menu_text } else { t.icon }); resp.clicked() } diff --git a/crates/ui-egui/src/popover_tests.rs b/crates/ui-egui/src/popover_tests.rs index 06daca851..6c4e559ee 100644 --- a/crates/ui-egui/src/popover_tests.rs +++ b/crates/ui-egui/src/popover_tests.rs @@ -194,3 +194,24 @@ fn a_caller_can_put_it_where_it_likes() { draw(&ctx, &mut t, &mut p, at, Hold::default(), vec![]); assert!(near(p.rect.min, pos2(360.0, 300.0)), "dropped where the drag left it: {:?}", p.rect); } + +mod icon_size_tests { + use super::*; + use crate::header_icon_size_tests::paints_icon_at_button_size; + use crate::icons::Icon; + + /// The header's 24 pt X paints its cross at 16 pt, like every other 24 pt icon button (#2238). + #[test] + fn the_close_button_paints_a_16pt_cross() { + let ctx = context(); + let mut t = 0.0; + let mut p = Popover::new("popover_close_size", "Colour"); + let shapes = settle(&ctx, &mut t, &mut p, Open::At(pos2(160.0, 100.0))); + let painted: Vec = shapes + .iter() + .filter(|s| matches!(s, egui::Shape::Path(_) | egui::Shape::Mesh(_) | egui::Shape::LineSegment { .. } | egui::Shape::Circle(_))) + .map(|s| s.visual_bounding_rect()) + .collect(); + assert!(paints_icon_at_button_size(&painted, Icon::Close), "the popover's close cross is not 16 pt"); + } +} diff --git a/crates/ui-egui/src/present/player.rs b/crates/ui-egui/src/present/player.rs index 8bcbea09d..66a8e30f3 100644 --- a/crates/ui-egui/src/present/player.rs +++ b/crates/ui-egui/src/present/player.rs @@ -173,7 +173,7 @@ fn top_bar(p: &mut Presenter, ui: &mut Ui, bar: Rect, now: f64, chrome: Chrome) resp = resp.tip(tr("Inspect the layer under the pointer: size, colours, typography")); } if chrome.pane { - icons::paint(ui.painter(), br.shrink(5.0), *icon, if on { t.accent_on } else { t.icon }); + icons::paint(ui.painter(), crate::widgets::icon_glyph_rect(br), *icon, if on { t.accent_on } else { t.icon }); } else { ui.painter().text(br.center(), Align2::CENTER_CENTER, shown, regular(11.5), if on { t.accent_on } else { text }); } diff --git a/crates/ui-egui/src/present/tests.rs b/crates/ui-egui/src/present/tests.rs index bba998788..1a8b0f076 100644 --- a/crates/ui-egui/src/present/tests.rs +++ b/crates/ui-egui/src/present/tests.rs @@ -436,3 +436,21 @@ fn smart_animate_frame_cost() { let per = t0.elapsed().as_secs_f64() * 1000.0 / f64::from(n); eprintln!("smart animate: {per:.2} ms per frame (80 layers, 400x800 px)"); } + +/// The preview pane's 24 pt bar buttons paint their glyphs at 16 pt (#2238). +#[test] +fn pane_bar_buttons_paint_16pt() { + use super::layout::Chrome; + use super::player::player; + use crate::header_icon_size_tests::{painted_rects, paints_icon_at_button_size}; + use crate::icons::Icon; + let (d, a, ..) = device_doc(); + let mut p = player_on(d, a); + let pane = Chrome { pane: true, bar_h: 32.0, pad: 12.0, round: 8, keys: false }; + let painted = painted_rects(None, |ui| { + player(&mut p, ui, Rect::from_min_size(pos2(0.0, 0.0), vec2(400.0, 500.0)), 0.0, pane); + }); + for icon in [Icon::Close, Icon::Play, Icon::Reset] { + assert!(paints_icon_at_button_size(&painted, icon), "{icon:?} is not 16 pt"); + } +} diff --git a/crates/ui-egui/src/variables_select_tests.rs b/crates/ui-egui/src/variables_select_tests.rs index 1ae91bd57..3b32dc49d 100644 --- a/crates/ui-egui/src/variables_select_tests.rs +++ b/crates/ui-egui/src/variables_select_tests.rs @@ -251,6 +251,23 @@ fn the_bulk_menu_scrolls_when_forty_groups_make_it_taller_than_the_window() { assert!(screen.contains_rect(popup_rect(&u))); } +/// A collection with a group `space` of two number variables with distinct values in two modes. +fn grouped_window() -> Ui { + let mut s = Session::new(); + s.execute("variable.createCollection", &json!({"name": "Theme", "modes": ["Light", "Dark"]})).unwrap(); + for (n, light, dark) in [("space/sm", 4, 8), ("space/md", 16, 32)] { + s.execute("variable.create", &json!({"collection": "Theme", "name": n, "type": "number", "value": light})).unwrap(); + s.execute("variable.set", &json!({"variable": n, "mode": "Dark", "value": dark})).unwrap(); + s.execute("variable.update", &json!({"variable": n, "scopes": ["GAP"], "description": n})).unwrap(); + } + let mut u = Ui::new(s); + u.app.ui.variables = Some(Default::default()); + for _ in 0..10 { + u.frame(vec![]); + } + u +} + /// Three colour variables: bravo and charlie also have Stroke in their scopes, delta does not. fn colour_window() -> Ui { let mut s = Session::new(); @@ -269,6 +286,52 @@ fn colour_window() -> Ui { u } +/// Right-click the group row `name` and choose Duplicate group. +fn duplicate_group(u: &mut Ui, name: &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, "Duplicate group"), PointerButton::Primary, Modifiers::NONE); + assert!(u.app.ui.last_error.is_none(), "{:?}", u.app.ui.last_error); +} + +#[test] +fn duplicate_group_copies_every_variable_in_both_modes_in_one_undo_step() { + let mut u = grouped_window(); + let before = u.app.session.undo_labels(100).len(); + duplicate_group(&mut u, "space"); + let doc = u.app.session.doc().unwrap(); + let vars = &doc.variables; + for (leaf, light, dark) in [("sm", 4, 8), ("md", 16, 32)] { + let old = vars.variables.iter().find(|v| v.name == format!("space/{leaf}")).unwrap(); + let new = vars.variables.iter().find(|v| v.name == format!("space 2/{leaf}")).unwrap_or_else(|| panic!("no space 2/{leaf}")); + assert_ne!(old.id, new.id); + assert_eq!(new.values, old.values, "{leaf}: values in both modes"); + assert_eq!(new.scopes, old.scopes); + assert_eq!(new.description, old.description); + let _ = (light, dark); + } + assert_eq!(names(&u).len(), 4); + assert_eq!(u.app.session.undo_labels(100).len(), before + 1, "one undo step"); + assert_eq!(u.app.session.undo_labels(1), ["Duplicate group"]); + // The new group is listed directly after the original. + let shapes = flat(&u.frame_output(vec![]).shapes); + assert!(has_text(&shapes, "space 2")); + assert!(text_center(&shapes, "space 2").y > text_center(&shapes, "space").y); + u.app.session.undo().unwrap(); + assert_eq!(names(&u), ["space/sm", "space/md"]); +} + +#[test] +fn a_second_duplicate_group_takes_the_next_free_name() { + let mut u = grouped_window(); + duplicate_group(&mut u, "space"); + duplicate_group(&mut u, "space"); + let n = names(&u); + assert!(n.contains(&"space 2/sm".to_string()) && n.contains(&"space 3/md".to_string()), "{n:?}"); + assert_eq!(n.len(), 6); +} + fn open_edit_variables(u: &mut Ui) -> Vec { let menu = select_three_and_open_menu(u); assert!(has_text(&menu, "Edit variables"), "the bulk menu offers Edit variables"); diff --git a/crates/ui-egui/src/widgets/style_picker.rs b/crates/ui-egui/src/widgets/style_picker.rs index cc820ed71..ca063abad 100644 --- a/crates/ui-egui/src/widgets/style_picker.rs +++ b/crates/ui-egui/src/widgets/style_picker.rs @@ -303,7 +303,12 @@ fn menu_icon(ui: &mut Ui, rect: Rect, icon: Icon, tip: &str, on: bool) -> Respon if on || resp.hovered() { ui.painter().rect_filled(rect, CornerRadius::same(5), t.menu_hover); } - icons::paint(ui.painter(), rect.shrink(5.0), icon, t.menu_text); + let glyph = if (rect.width() - 24.0).abs() < 0.5 && (rect.height() - 24.0).abs() < 0.5 { + crate::widgets::icon_glyph_rect(rect) + } else { + rect.shrink(5.0) + }; + icons::paint(ui.painter(), glyph, icon, t.menu_text); resp } diff --git a/crates/ui-egui/src/widgets/style_picker/tests.rs b/crates/ui-egui/src/widgets/style_picker/tests.rs index 984f6c8d4..08c27f12d 100644 --- a/crates/ui-egui/src/widgets/style_picker/tests.rs +++ b/crates/ui-egui/src/widgets/style_picker/tests.rs @@ -558,3 +558,17 @@ fn text_style_editor_binds_variables_from_its_fields() { assert_eq!((def.font_size, def.font_style.as_str()), (18.0, "Bold"), "the style takes the variables' values"); assert!(u.app.ui.last_error.is_none(), "{:?}", u.app.ui.last_error); } + +/// The picker's 24 pt icon buttons paint their glyphs at 16 pt; a smaller button keeps a smaller one +/// (#2238). +#[test] +fn style_picker_icon_buttons_paint_16pt() { + use crate::header_icon_size_tests::{painted_rects, paints_icon_at_button_size}; + use crate::icons::Icon; + for icon in [Icon::Plus, Icon::Detach, Icon::ChevronLeft] { + let painted = painted_rects(None, |ui| { + menu_icon(ui, Rect::from_min_size(egui::pos2(20.0, 20.0), vec2(24.0, 24.0)), icon, "x", false); + }); + assert!(paints_icon_at_button_size(&painted, icon), "{icon:?} is not 16 pt"); + } +} diff --git a/docs/boards-parity.md b/docs/boards-parity.md index 04cb832bc..139461500 100644 --- a/docs/boards-parity.md +++ b/docs/boards-parity.md @@ -1,6 +1,6 @@ # Boards parity -> **Last reviewed:** 2026-10-24 · **Last updated:** 2026-11-10 · **Change:** minor (resizing a board table by height changes its rows, not blank space below them: a bottom or top edge grows the last row, a corner shares the change over every row, and a table keeps at least 40 per cell, measured in FigJam's web app, 2026-11-09 (#2172); a `.jam` file's stickies come in as native board stickies, with their colour, text and author kept and the size as saved (#1808); a sticky's text stays 18 and the note grows taller instead of the text shrinking, as measured in FigJam's web app (#2157); mind maps, first step: a first node with three children on curved branches, laid out again after every edit (`board.mindMap`, `board.mindMapAdd`, #2226); a `.jam` elbowed connector saved with its path keeps it on import instead of being routed again (#1910); a "+" handle dragged carries the preview: the next shape is made where it is let go, or a connector joins the object it is let go on (#1919); a connector attached to a side starts 4 pt outside the border, so its stroke never lies on the fill (#1916); a connector end moved with Cmd/Ctrl held goes on any part of an object, and stays there as the object moves or resizes; a connector end dropped along a side of a shape attaches to that side (#1708); a board connector's path can be reshaped by dragging its path handles (#1710); boards have 16 more shapes (arrows, polygons, star, plus and flowchart symbols), in pickers that lay them out in a grid; a board keeps earlier votes' results, listed newest first in Results and deleted one at a time; a connector's bar sets its start and end points, dashes, weight and any colour (#1596); cells copied from a spreadsheet paste onto a board as a table; Shift+Cmd/Ctrl+Enter on a selected board shape adds the next shape already joined to it, and goes on typing (#1597); "+" handles beside a selected sticky or shape make the next one, joined by a connector (#1597); a FigJam `.jam` file opens as a board (#1342); board grid settings: dots, lines, graph paper or none, spacing, size and contrast; the connector tool shows the connector it will make while dragging, ends snapping to attach points (#1387); templates and tables; facilitation: a shared timer and voting sessions; the dot grid, dragging a connector's end to re-attach it, curved connectors, elbows that go around what they join) · **Target:** the incumbent's whiteboard product (behaviour from its public help centre) +> **Last reviewed:** 2026-10-24 · **Last updated:** 2026-11-12 · **Change:** minor (a sticky has a text-size menu in the contextual bar, Small 16, Medium 24, Large 40, Extra large 64 and Huge 96, with Small the default (an earlier reading of 18 did not reproduce); `board.setStyle {fontSize}` sizes stickies and the sticky tool remembers the last size for new ones; the note grows taller at Huge and shrinks back, as measured in FigJam's web app, 2026-11-12; resizing a board table by height changes its rows, not blank space below them: a bottom or top edge grows the last row, a corner shares the change over every row, and a table keeps at least 40 per cell, measured in FigJam's web app, 2026-11-09 (#2172); a `.jam` file's stickies come in as native board stickies, with their colour, text and author kept and the size as saved (#1808); a sticky's text stays 18 and the note grows taller instead of the text shrinking, as measured in FigJam's web app (#2157); mind maps, first step: a first node with three children on curved branches, laid out again after every edit (`board.mindMap`, `board.mindMapAdd`, #2226); a `.jam` elbowed connector saved with its path keeps it on import instead of being routed again (#1910); a "+" handle dragged carries the preview: the next shape is made where it is let go, or a connector joins the object it is let go on (#1919); a connector attached to a side starts 4 pt outside the border, so its stroke never lies on the fill (#1916); a connector end moved with Cmd/Ctrl held goes on any part of an object, and stays there as the object moves or resizes; a connector end dropped along a side of a shape attaches to that side (#1708); a board connector's path can be reshaped by dragging its path handles (#1710); boards have 16 more shapes (arrows, polygons, star, plus and flowchart symbols), in pickers that lay them out in a grid; a board keeps earlier votes' results, listed newest first in Results and deleted one at a time; a connector's bar sets its start and end points, dashes, weight and any colour (#1596); cells copied from a spreadsheet paste onto a board as a table; Shift+Cmd/Ctrl+Enter on a selected board shape adds the next shape already joined to it, and goes on typing (#1597); "+" handles beside a selected sticky or shape make the next one, joined by a connector (#1597); a FigJam `.jam` file opens as a board (#1342); board grid settings: dots, lines, graph paper or none, spacing, size and contrast; the connector tool shows the connector it will make while dragging, ends snapping to attach points (#1387); templates and tables; facilitation: a shared timer and voting sessions; the dot grid, dragging a connector's end to re-attach it, curved connectors, elbows that go around what they join) · **Target:** the incumbent's whiteboard product (behaviour from its public help centre) **Breadth ~47%, ready ~29% (estimated, erring low).** A board is a FigCraft file of its own kind (`file.newBoard`) with a dot grid on the page, sticky notes, shapes with text, connectors that @@ -28,10 +28,10 @@ all end with the same geometry. |---|---|---| | Board files: File ▸ New board, the home screen's New board card, a light page | done | `file.newBoard`; the kind shows in `inspect_document`, tabs and file rows (a note mark; design files a pen nib) | | Board toolbar at the bottom | done | Move/Hand, Marker/Highlighter/Eraser, Sticky (colour flyout), Shapes (flyout), Connector, Text, Section, Stamp (flyout), Comment, Actions, then the templates and the Design panel's buttons — on the same 32 pt grid as a design file's (no Resources button, as there) | -| Design panel hidden by default; a contextual bar above the selection | done | colour, shape, text size (S/M/L/XL); for connectors straight/elbow/curved, the start and end points (none, round, square, line arrow, triangle arrow, reversed triangle, circle, diamond), solid or dashed, the weight, and any colour in the colour picker beside the board colours (#1596); each control says what it is on hover; the Design panel opens with its button or View ▸ Design panel | +| Design panel hidden by default; a contextual bar above the selection | done | colour, shape, text size (S/M/L/XL for shapes and labels; a size menu, Small to Huge, for stickies); for connectors straight/elbow/curved, the start and end points (none, round, square, line arrow, triangle arrow, reversed triangle, circle, diamond), solid or dashed, the weight, and any colour in the colour picker beside the board colours (#1596); each control says what it is on hover; the Design panel opens with its button or View ▸ Design panel | | Prototyping and Developer Mode refuse on boards | done | `proto.*`, `dev.*`, `view.prototype`, `view.devMode` say why | -| Sticky notes | done | a square frame (200 wide, growing taller through auto layout), 8 soft colours, a soft shadow, the note's text 18 by default and fixed (FigJam's "Small"): the note grows taller as it fills and never shrinks its text, measured in FigJam's web app, 2026-11-09; stickies saved with another size keep it, and there is no size menu yet (#2157), the author's name at the bottom; a click places one and starts typing; Enter or a double-click edits; Shift+Cmd/Ctrl+Enter adds the next one beside it | -| Sticky options: hide the author, change size presets, sticky stacks | partial | `board.sticky {author: false}`; no size presets or stacks | +| Sticky notes | done | a square frame (200 wide, growing taller through auto layout), 8 soft colours, a soft shadow, the note's text 16 by default (FigJam's "Small", read twice from its size field, 2026-11-12) and fixed as it fills: the note grows taller and never shrinks its text (2026-11-09, #2157); a size menu in the contextual bar (Small 16, Medium 24, Large 40, Extra large 64, Huge 96; a number when the size matches none) sets every selected sticky, the note grows taller when Huge no longer fits and shrinks back to square at Large, and the sticky tool remembers the last size for new stickies, all measured in FigJam's web app, 2026-11-12; stickies saved with another size keep it, the author's name at the bottom; a click places one and starts typing; Enter or a double-click edits; Shift+Cmd/Ctrl+Enter adds the next one beside it | +| Sticky options: hide the author, change size presets, sticky stacks | partial | `board.sticky {author: false}`; size presets done (the bar's menu, `board.setStyle {fontSize}`, `board.sticky {fontSize}`); no stacks | | Shapes with text | done | rectangle, rounded rectangle, ellipse, diamond, triangle, speech bubble, chevron; text centred and wrapping inside the outline; shape type and text size from the contextual bar | | Shape auto-fit to its text, more shapes (cylinder, cross, star…), shape libraries | missing | | | Connectors | done | from a layer's side (the facing one, or one named) to another layer or a free point, straight, elbow or curved, arrowheads (the stroke's caps), a label in the middle of the route by length (double-click to add); while one is dragged out it shows as it will be made (route, line and arrowhead), the object under the pointer outlined with its four attach points (side middles), the one the end goes to ringed; an end dropped on the outer half of an object takes the side it is towards (a drop along a whole edge chooses that edge), one in the middle takes the facing side; re-routed when either end moves or resizes; a deleted end stays where it was; an end attached to a side starts 4 pt outside the border (`board_route::END_GAP`), so the stroke never lies on the fill; elbows leaving one side share their first run along its normal and curves leave tangent to it (#1916) | @@ -72,6 +72,7 @@ all end with the same geometry. | Date | Change | Summary | |---|---|---| +| 2026-11-12 | minor | M12: a sticky's text-size menu. Measured in FigJam's web app, 2026-11-12: the menu lists Small 16, Medium 24, Large 40, Extra large 64 and Huge 96 (typing 40 shows Large), a fresh sticky is Small = 16 (read twice from the size field; the 18 of 2026-11-09 did not reproduce), the note stays square to Extra large and grows taller at Huge with the same width and shrinks back at Large, choosing a size with two stickies selected sets both, and the sticky tool remembers the last size. `STICKY_TEXT_SIZE` is 16, `STICKY_SIZES` holds the table, `board.setStyle {fontSize}` sizes stickies and sets the tool's size, `board.sticky` takes `fontSize`, and the contextual bar shows a size menu when only stickies carry text (shapes keep S/M/L/XL, unmeasured). Stacks are still missing. Tests: `a_new_sticky_is_small_16`, `the_sticky_sizes_are_figjams`, `set_style_font_size_sizes_every_selected_sticky`, `the_sticky_tool_remembers_the_last_size`, `a_huge_sticky_grows_taller_and_shrinks_back`, `a_selected_sticky_has_a_size_menu_instead_of_the_size_cells` | | 2026-11-09 | minor | M12, #2172: a board table's height change goes into its rows. Measured in FigJam's web app, 2026-11-09 (a table has no lock-proportions control and never scales proportionally): a bottom-edge drag grows only the last row, a corner drag shares the change equally over every row and column, text keeps its size, and a table stops shrinking at about 52 per cell with a row never shorter than its wrapped text. FigCraft already split a width change equally (every cell fills); the bug was height: a bottom or corner resize turned the table from hugging to fixed height, so the rows stayed at 40 with blank space below them (or were clipped when shrunk) and typing no longer grew the table. `board_table::settle_resize`, called first in the normalize pass, finds a table left at a fixed height, puts the change into the rows' minimum height (the last row, or every row when both axes changed), raises a width that is too narrow to `columns x 40`, and returns the table to hugging, so every route (drag, `node.set`, `transform.resize`, MCP, live-session peers) gives the same result, in one undo step. FigCraft's floor is 40 (FigJam's is about 52) and there are no per-column widths yet: a side drag of the right edge still splits equally where FigJam grows only the last column. Numbers unchanged. Tests: `board_tables_tests` (the bottom, corner and side drags, the floor, typing after a resize and undo, live sessions, junk). | | 2026-11-09 | patch | M12, #2157: a sticky's text is 18 and stays 18 (measured in FigJam's web app: ten lines, then a long paragraph, never changed it; the note kept its width and grew taller). The normalize pass no longer resets a sticky's text to a size by its length (24 down to 11 before), so stickies in saved files keep their size. Size presets (Small to Huge) are still missing. Tests: `a_new_sticky_starts_at_18`, `a_sticky_keeps_its_text_size_as_text_is_added`, `a_sticky_saved_with_another_text_size_keeps_it` | | 2026-11-10 | minor | M12, #2226 (step 1 of 4): mind maps in the document and engine. A mind map node is a board object of its own (`BoardItem::MindNode`: text with no box) and a branch is a connector marked `branch`; the map's shape is read from its branches. `board.mindMap` places a first node with three children and `board.mindMapAdd` adds a child or a sibling, each one undo step. The normalize pass lays a touched map out again from its first node (`board::settle_mind_maps`, `figcraft_doc::mind_layout`): 88 between columns, 48 between siblings, each stack centred on its parent, numbers from a FigJam file saved and decoded. Tests: `board_mindmap_tests` in doc (five) and engine (eight). Numbers unchanged (no toolbar entry yet). | diff --git a/docs/components-parity.md b/docs/components-parity.md index 3d4fa7ddf..3d23800b0 100644 --- a/docs/components-parity.md +++ b/docs/components-parity.md @@ -1,6 +1,6 @@ # Components, variants, styles and variables parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-12 · **Change:** minor (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-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) 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 @@ -66,7 +66,7 @@ updates with overrides kept: `library_tests.rs`, `components_scale_tests.rs`. | Editing a style updates its layers; detach and delete keep values; editing a styled property unlinks that style | done | an edited fill/stroke/effect/grid list or text chars unlink; applying a style replaces variables bound to what it sets; text styles on text layers only | | Organising styles: folders by `/` names, order, duplicate, rename folder, Local styles list | done | `style.move` (into a folder renames), `style.duplicate` (right below), `style.renameFolder`; the page's Local styles list by type and folder (drag to reorder, right-click) | | Variables inside styles (paint, effect, grid and text styles; each user resolves them in its own modes) | done | `style.bind`, `style_vars_tests`; the editor binds paint colours, shadow colours, blur radii, grid sizes and a text style's font, font style (a face name from a string variable, or a numeric weight from a number variable, which picks the nearest face and a variable font's `wght` axis), size, line height and letter spacing, the rest through the command; a bound line height is applied in pixels, as the reference tool does (measured 2026-11-10) | -| Variables: colour, number, string, boolean; collections, modes, aliases, scopes, groups | done | behaviour suite: `variables_behaviour_tests.rs`; aliases same type, no loops (also on create); colour calculations per mode (`{alpha}`: a colour variable with its alpha replaced, `{mix}`: a per-channel blend of two colour variables or literals; they compose, can't loop, and bound layers, modes and undo follow them; REST, CSS, Penpot and `.fig` exports write the colour they show in each of their collection's modes, other collections in their default modes; read-only in the panel, which can swap one for an alias or detach it; `variables_colour_tests.rs`), beyond the incumbent, whose variables only alias; scopes filter pickers only; several variables can be selected in the editor (Shift and Cmd/Ctrl click) and deleted, moved to a group or rescoped at once | +| Variables: colour, number, string, boolean; collections, modes, aliases, scopes, groups | done | behaviour suite: `variables_behaviour_tests.rs`; aliases same type, no loops (also on create); colour calculations per mode (`{alpha}`: a colour variable with its alpha replaced, `{mix}`: a per-channel blend of two colour variables or literals; they compose, can't loop, and bound layers, modes and undo follow them; REST, CSS, Penpot and `.fig` exports write the colour they show in each of their collection's modes, other collections in their default modes; read-only in the panel, which can swap one for an alias or detach it; `variables_colour_tests.rs`), beyond the incumbent, whose variables only alias; scopes filter pickers only; several variables can be selected in the editor (Shift and Cmd/Ctrl click) and deleted, moved to a group or rescoped at once; a group can be duplicated from its row's menu (Duplicate group, one undo step) | | Modes: add, duplicate, rename, delete, set as default / reorder | done | layers on Auto follow a new default; explicit modes stay | | Deleting a bound variable or its collection | done | layers keep their last value and are unbound; aliases to it take its values and colour calculations reading it keep the colour they show | | Code syntax per platform (Web, iOS, Android) | done | generated CSS uses the Web name, SwiftUI the iOS one and Compose the Android one (a variable without one keeps its value there); in the variables JSON; ArkUI and Flutter have no platform of their own and write values | @@ -81,6 +81,7 @@ updates with overrides kept: `library_tests.rs`, `components_scale_tests.rs`. | Date | Change | Summary | |---|---|---| +| 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 | | 2026-11-10 | minor | M7, #2174: a text style binds a number variable to its weight (`style.bind {field: "fontWeight"}`): the style takes the face nearest the number and sets the `wght` axis, so static and variable fonts both follow; a face-name (string) binding and a weight binding replace each other, and the weight wins in a file carrying both. The style editor's weight menu offers number variables beside string ones. A number bound to a line height is applied in pixels, as the reference tool does, which a test now pins. Numbers unchanged. Tests: `style_vars_tests`, `style_picker::tests`. | diff --git a/docs/dev-mode-parity.md b/docs/dev-mode-parity.md index 66ef3a0ae..07e618495 100644 --- a/docs/dev-mode-parity.md +++ b/docs/dev-mode-parity.md @@ -1,6 +1,6 @@ # Dev Mode parity -> **Last reviewed:** 2026-10-24 · **Last updated:** 2026-11-09 · **Change:** patch (the Annotation tool (Shift+T, `tool.annotation {id?}`): with a layer selected (or an `id`) it asks the UI for that layer's note at once, and in the tool a press on a layer selects it and asks for its note, a press on empty canvas does nothing; the Inspect tab then opens (never toggles away) with the caret in that layer's new-note field, and the engine never writes the note itself (#1840); the handoff mode reads Developer Mode in the interface, its ids and saved fields unchanged; class names transliterate non-ASCII layer names (#1235); measurements kept on the canvas; a read-only layers panel in Dev Mode; earlier: import lines in generated layer trees; compare with any saved version; Dev Mode behaviour suite: an inspect-only canvas, Changed in the ready list, statuses only on frames and sections; plugin panels from the Inspect tab) · **Target:** Figma Design Dev Mode (desktop app 126.10.7) +> **Last reviewed:** 2026-10-24 · **Last updated:** 2026-11-12 · **Change:** patch (CSS code export writes several fills as one layered `background`, top first, as the incumbent does (#2271): a solid above another fill becomes a one-colour gradient, the bottom solid stays a plain colour, Tailwind gets one `[background:...]` class; the Annotation tool (Shift+T, `tool.annotation {id?}`): with a layer selected (or an `id`) it asks the UI for that layer's note at once, and in the tool a press on a layer selects it and asks for its note, a press on empty canvas does nothing; the Inspect tab then opens (never toggles away) with the caret in that layer's new-note field, and the engine never writes the note itself (#1840); the handoff mode reads Developer Mode in the interface, its ids and saved fields unchanged; class names transliterate non-ASCII layer names (#1235); measurements kept on the canvas; a read-only layers panel in Dev Mode; earlier: import lines in generated layer trees; compare with any saved version; Dev Mode behaviour suite: an inspect-only canvas, Changed in the ready list, statuses only on frames and sections; plugin panels from the Inspect tab) · **Target:** Figma Design Dev Mode (desktop app 126.10.7) **Breadth ~98%, ready ~78% (estimated).** The inspect surface is broad, components connect to the code components of a repository (with their imports, also inside generated layer trees), @@ -13,7 +13,7 @@ repository, third-party integrations. Remaining: 1–2 h. | 2026-11-07 | patch | Naming: the handoff mode is called Developer Mode in the interface, its shortcut row, its toasts, the control channel's refusal, the board refusal, the measurement parameter doc, the `.fig` export note, the CLI help and every catalog (24 languages, translations awaiting native review), since Figma holds a US registration for Dev Mode (7574348); command ids (`view.devMode`, `devMode.*`), preference keys and saved-document fields are unchanged, and the Actions palette still finds the command by the old name | | Dev Mode toggle (Shift+D), Inspect panel | done | the canvas only inspects: presses select, pan and comment but never move, resize, draw or edit text and vectors; menus and shortcuts refuse design edits with a note (Dev Mode's annotations, statuses, dev resources, measurements, code connections and comments still work); a drawing tool chosen in the toolbar goes back to the design. The layers panel only selects and expands (no renaming, reordering, hiding or locking; a double click says why), and the Pages list only opens pages (no adding, renaming, reordering, duplicating or deleting). Files dropped on the canvas aren't imported (a dropped document still opens as a file of its own), and the Assets panel places, swaps and applies nothing, doesn't change Hide when publishing, and doesn't accept library updates or add, remove or swap libraries; each says why | | Properties with their styles and variables; redlines on hover | done | positions from the frame around the layer (groups aren't frames), rotation, radius (CSS corner order), opacity, blend; colours in hex, RGB, CSS, HSL or HSB (`inspect.properties {colorFormat}`, the Inspect tab's Color format) | -| Code: CSS, iOS (SwiftUI), Android (Compose), Flutter | done | plus HTML, React, Vue and Leptos (ours; Leptos: `#[component]` functions with `#[prop]` defaults, variant enums and `view!` markup; Flutter is ours too: a `StatelessWidget` for a component, a widget tree for a layer); components take properties as parameters, instances are calls; CSS in px or rem (`inspect.code {unit, rootFontSize}`), with rotation, blend modes, gradient directions and kinds (linear, radial, conic), text alignment, case and decoration; class names from layer names transliterate non-ASCII scripts into readable ASCII (로그인 화면 → `rogeuin-hwamyeon`, кнопка → `knopka`, über → `uber`; symbols-only names take the node's kind, `.text`), and the 40-character cut lands on a word boundary (#1235) | +| Code: CSS, iOS (SwiftUI), Android (Compose), Flutter | done | plus HTML, React, Vue and Leptos (ours; Leptos: `#[component]` functions with `#[prop]` defaults, variant enums and `view!` markup; Flutter is ours too: a `StatelessWidget` for a component, a widget tree for a layer); components take properties as parameters, instances are calls; CSS in px or rem (`inspect.code {unit, rootFontSize}`), with rotation, blend modes, several fills as one layered `background` (top first), gradient directions and kinds (linear, radial, conic), text alignment, case and decoration; class names from layer names transliterate non-ASCII scripts into readable ASCII (로그인 화면 → `rogeuin-hwamyeon`, кнопка → `knopka`, über → `uber`; symbols-only names take the node's kind, `.text`), and the 40-character cut lands on a word boundary (#1235) | | Assets list with export | done | layers with export settings, icons (small, vector shapes only: SVG) and images (PNG); the icon rule is ours | | Annotations: pinned properties, categories, coloured callouts, filter | done | the Annotation tool (Shift+T, `tool.annotation`) picks a layer by a click or from the selection and opens its note field in the Inspect tab. Figma's placement, cursor and whether the tool stays selected are unmeasured (Developer Mode is paywalled in the web app); staying selected until V or Escape, like the Comment tool, is inferred, and there is no toolbar button or icon yet | | Ready for dev list, statuses, "Changed" after edits | done | the list filters Ready for dev, Changed, Completed or any, and badges changed ones (`inspect.readyForDev {status: changed}`, `changed` per item); only sections and frames at the top of a page or section take a status (others are refused) | @@ -29,6 +29,7 @@ repository, third-party integrations. Remaining: 1–2 h. | Date | Change | Summary | |---|---|---| +| 2026-11-12 | patch | CSS code export (#2271): a layer with several fills wrote one `background` per fill, so only the last survived. It now writes one `background` with every visible fill as a layer, top fill first, comma-separated: a solid above another fill is `linear-gradient(0deg, c, c)` (CSS allows a plain colour only as the last layer), the bottom solid stays a plain colour (with its variable), images and patterns keep their `url(...)` layers. Tailwind output carries the layered value as one `[background:...]` class. Text keeps one `color` per fill. Native targets unchanged. Percentages and hours unchanged | | 2026-11-09 | patch | The Annotation tool (Shift+T, `tool.annotation {id?}`): selects the layer pressed on (or the selection, or `id`) and asks the UI for its note, which the Inspect tab takes in its new-note field; the engine writes nothing itself, and Developer Mode lets the tool through its gates (#1840). Figma's placement, cursor and whether the tool stays selected are unmeasured (Developer Mode is paywalled in the web app); staying selected until V or Escape, like the Comment tool, is inferred, and there is no toolbar button or icon yet | | 2026-10-30 | minor | Gap 16: `figcraft-cli connect publish [--mappings figcraft.connect.json] [--dry-run]` publishes a code repository's mappings to a design file (as the incumbent's Code Connect CLI publishes a repository's mappings): it links each entry's component or set by name, warns about and skips links that don't fit, saves the file in place through the engine's save (or not, with `--dry-run`) and fails when nothing links. Dev Mode breadth (~98%) and ready (~78%) unchanged at this rounding; hours unchanged | | 2026-10-26 | minor | Class names from layer names transliterate non-ASCII scripts (#1235): `class_name` runs names through `deunicode` (new dependency: pure Rust tables, zero deps, BSD-3-Clause), so Korean, Cyrillic, Latin-diacritic and CJK names become readable ASCII classes in HTML/CSS/React/Leptos output, component roots and `data-*` variant attributes (`rogeuin-hwamyeon`, `knopka`, `uber`, `an-niu`; before, every one of them came out `layer-`); symbols-only names take the node's kind (`.text`, `.frame`) instead of `layer-`, and the 40-character cut lands on a word boundary. ASCII-only names are unchanged. `html_codegen_tests` updated (its diacritics expectation improves from `layer-1-n-code-name` to `layer-1-unicode-name`) and extended. Percentages and hours unchanged | diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 2d62d68d5..979b698cd 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,6 +1,6 @@ # File format parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-12 · **Change:** minor (`.fig` export writes list spacing, hanging punctuation and lists, and vertical trim (#2305); `.fig` import and export read and write a boolean group's corner radius and smoothing (#2222); `.jam` import: stickies come in as native board stickies (#1808); `.fig` import scales per-point vector corner radii with the row that supplies their network and keeps different instance scales separate in the network cache (#2097); `.fig` export preserves scaled-instance lengths reset to their unscaled main values, including nested linked-style overrides (#2097); `.fig` import: the layers of an instance scaled with the Scale tool draw at its scale factor, not at their main's lengths (#2091); a color profile per PNG, JPG and WebP export setting (Same as file, sRGB or Display P3), the pixels converted; a `.jam` connector end with an `AUTO` or `CENTER` magnet leaves the side facing the other end, not the side its stale saved point named (#1909); a FigJam elbow connector saved with its path (`connectorControlPoints`) keeps it on import, as a board connector reshaped by hand does, instead of being routed again (#1910); JPG exports take a quality, 1 to 100 with 90 the default, and embed the file's colour profile when it is sRGB too (#2004); a FigJam connector without a saved snapshot took no stroke and was invisible; its line's paint, weight, cap and dashes now come from the file's generated line record (#1807); a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); imported and pasted text finds an installed family under the other names its fonts give it, and with other case and spacing (#1292); `.fig` export writes colour calculations as the colour they show in each mode and leaves out, with a warning, one that resolves to nothing (#1280); `.fig` import budgets four decoded values per compressed byte instead of one, still within 20M–128M, so dense files within that budget open instead of being refused as having too many values (#574); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); every file a command reads whole by path is a regular file within a cap that fits it: documents 16 GiB, placed images 256 MiB, CLI scripts 1 GiB; folders, devices and pipes are refused before anything is read (#1114); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); a FigJam `.jam` file opens as a board (#1342); FigJam `.jam` files open like `.fig` files: File ▸ Open, drag and drop, `file.import` and the command line (#1342); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); SVG import draws each pattern tile once per scale, within the layer budget (#1080); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); offline Penpot 2.x import/export (#1143); `.sketch` import checked against Sketch's renders: master backgrounds, symbol clipping, tints before Sketch 64, mask opacity, bitmap fills, image overrides on shapes, stretching stacks, blur radii, colour adjustments, OKLab gradients, text growth, shape group borders (#1389); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); image member names are checked on read, and REST image placeholders get archive-safe keys (#1086); Android Vector Drawable (XML) export; `.fig` export: files the incumbent imports, with component set properties, and grid track sizes at its field ids; Save and auto-save don't replace changes another app made to the open file (#1330); `.sketch` import, best effort, Sketch 48 and newer; the PNG row names ignore overlapping layers and where include bounding box is offered; the Fonts table's missing-font row describes the Missing fonts window; `.figcraft` carries the file kind (boards); `.fig` import: resized instances and variable modes by asset key; atomic saves; auto-save; SVG export clip of nested frames; SVG/PDF export depth refusal (#208); `.fig` export: instance sizes, variables with modes, shared styles, variable-width strokes; `.fig` export: written files checked by opening them in other software; experimental `.fig` export; export and inspect behaviour suite and fixes; .fig import: editable vector networks and more layer kinds; embedded image colour profiles; `.fig` import, best effort; animated GIF fills and TIFF images; last major: created, formats from the installed Figma's Info.plist and help center, ours from source; REST import keeps slot layers and instances' slot content (#792); REST import reads grid track sizes (#465); `.fig` import fidelity from the community batches, budgets for large files, the import report, a `.fig` copy from Save as, paste from another design app; instance layers' size and resizing and Hug on import (#731, #732)) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-13 · **Change:** minor (`.fig` import: a numbered list keeps its start only where it starts counting (#2273); `.fig` export writes a page's prototype background (#2326); `.fig` export writes list spacing, hanging punctuation and lists, and vertical trim (#2305); `.fig` import and export read and write a boolean group's corner radius and smoothing (#2222); `.jam` import: stickies come in as native board stickies (#1808); `.fig` import scales per-point vector corner radii with the row that supplies their network and keeps different instance scales separate in the network cache (#2097); `.fig` export preserves scaled-instance lengths reset to their unscaled main values, including nested linked-style overrides (#2097); `.fig` import: the layers of an instance scaled with the Scale tool draw at its scale factor, not at their main's lengths (#2091); a color profile per PNG, JPG and WebP export setting (Same as file, sRGB or Display P3), the pixels converted; a `.jam` connector end with an `AUTO` or `CENTER` magnet leaves the side facing the other end, not the side its stale saved point named (#1909); a FigJam elbow connector saved with its path (`connectorControlPoints`) keeps it on import, as a board connector reshaped by hand does, instead of being routed again (#1910); JPG exports take a quality, 1 to 100 with 90 the default, and embed the file's colour profile when it is sRGB too (#2004); a FigJam connector without a saved snapshot took no stroke and was invisible; its line's paint, weight, cap and dashes now come from the file's generated line record (#1807); a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; pasted layers whose image the clipboard lacks are named and show a placeholder that reads as missing (#1646); paint-style colours on layers pasted from another design app keep their style instead of turning black (#1638); imported and pasted text finds an installed family under the other names its fonts give it, and with other case and spacing (#1292); `.fig` export writes colour calculations as the colour they show in each mode and leaves out, with a warning, one that resolves to nothing (#1280); `.fig` import budgets four decoded values per compressed byte instead of one, still within 20M–128M, so dense files within that budget open instead of being refused as having too many values (#574); `.fig` ZIP image reads share a total byte budget and count skipped images in the import warnings (#1076); every file a command reads whole by path is a regular file within a cap that fits it: documents 16 GiB, placed images 256 MiB, CLI scripts 1 GiB; folders, devices and pipes are refused before anything is read (#1114); files nested 256 levels deep import on the browser's 1 MB stack (#1101); SVG and PDF exports count pattern sources and the renders they embed from the layer's depth, so one cap bounds a whole export (#1082); opening a `.figcraft` file unpacks at most 6 GiB in all (2 GiB in the browser), every area together (#1079); `.fig` instance expansion no longer walks variable nodes for every instance or copies every outer override row into each nested instance (#1077); a FigJam `.jam` file opens as a board (#1342); FigJam `.jam` files open like `.fig` files: File ▸ Open, drag and drop, `file.import` and the command line (#1342); SVG import reads `color()` and `color-mix()` colours, with a note and a grey for those it can't (#1550); SVG import draws each pattern tile once per scale, within the layer budget (#1080); a file's JPEG thumbnail can't crash the home screen (#1491's progressive JPEG check, now shared); `.fig` import: library text styles linked by asset key, and override rows restating a nested level (#1234); `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); Download a missing free font from the Missing fonts window (`font.download`, #754); offline Penpot 2.x import/export (#1143); `.sketch` import checked against Sketch's renders: master backgrounds, symbol clipping, tints before Sketch 64, mask opacity, bitmap fills, image overrides on shapes, stretching stacks, blur radii, colour adjustments, OKLab gradients, text growth, shape group borders (#1389); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); image member names are checked on read, and REST image placeholders get archive-safe keys (#1086); Android Vector Drawable (XML) export; `.fig` export: files the incumbent imports, with component set properties, and grid track sizes at its field ids; Save and auto-save don't replace changes another app made to the open file (#1330); `.sketch` import, best effort, Sketch 48 and newer; the PNG row names ignore overlapping layers and where include bounding box is offered; the Fonts table's missing-font row describes the Missing fonts window; `.figcraft` carries the file kind (boards); `.fig` import: resized instances and variable modes by asset key; atomic saves; auto-save; SVG export clip of nested frames; SVG/PDF export depth refusal (#208); `.fig` export: instance sizes, variables with modes, shared styles, variable-width strokes; `.fig` export: written files checked by opening them in other software; experimental `.fig` export; export and inspect behaviour suite and fixes; .fig import: editable vector networks and more layer kinds; embedded image colour profiles; `.fig` import, best effort; animated GIF fills and TIFF images; last major: created, formats from the installed Figma's Info.plist and help center, ours from source; REST import keeps slot layers and instances' slot content (#792); REST import reads grid track sizes (#465); `.fig` import fidelity from the community batches, budgets for large files, the import report, a `.fig` copy from Save as, paste from another design app; instance layers' size and resizing and Hug on import (#731, #732)) · **Target:** Figma Design (desktop app 126.10.7) Every format Figma reads or writes, with FigCraft's support. Sources: `Info.plist` of `/Applications/Figma.app` (document types only; nothing inside the bundle's code was read), Figma's @@ -17,7 +17,7 @@ and prototype interactions are still unchecked there. | Format | Figma | FigCraft read | FigCraft write | Fidelity / testing | Hours | |---|---|---|---|---|---| -| `.fig` (Figma Design, `com.figma.document`, `application/x-figma`) | native (cloud; "Save local copy") | **yes, best effort** (`file.open`, `file.import`, drop, CLI, MCP) | **experimental** ([below](#export-to-fig-experimental)) | `.fig` files open (best effort): the zip, its deflate/zstd chunks and the kiwi schema are decoded generically and mapped by field name onto the REST importer, so pages, the layer tree, geometry, paints (styles resolved), strokes, effects, text with styled runs, vectors as editable vector networks with region-specific fill paints (points, curved segments, filled areas with their winding, per-point corner radius and handle mirroring, end caps; outlines when the network is missing or damaged), auto layout (grid included; a flow that records no primary-axis sizing hugs on that axis, an instance that records no auto layout has its main's), constraints, ellipse arcs, boolean operations (with their corner radius and smoothing, #2222), components, sets (with their descriptions), instances (expanded from their main with overrides, derived layout and property values; the size and resizing their layers override stay overrides; an instance scaled with the Scale tool, which stores `symbolData.uniformScaleFactor`, draws its layers at the main's lengths times that factor, composed through nested instances: sizes and places, corner radii, stroke weights and dashes, effect radii, spreads and offsets, auto layout gaps and paddings, grid gaps, min and max sizes, layout grids, font sizes, pixel line heights and letter spacings, paragraph spacing and indent, except where an override or derived row gives the value, which is already at the instance's scale; per-point vector corner radii also take their vector-data row's factor; the vector outline paths a layer carries (a network's points follow the layer's size), fixed grid tracks, image tile scales and glass effects are not scaled by the factor, #2091), styles, variables with modes and bindings, prototyping (set-variable, set-variable-mode and conditional actions included) and image fills from the archive come across; sticky notes and shapes with text keep their generated backgrounds, styled text, text paints, saved child bounds and sticky author lines as editable frame children, including saved vector networks without geometry paths, outer fill/stroke outlines when generated geometry is damaged, and outer body text when its generated child is unusable even if an author survives (#1341, #1397); connectors, tables, code blocks, slides and similar layers come in as the closest frames, text layers and vectors, with a warning; anything else is a warning. Since 2026-10-17 (community batches #727, #728): an instance's own identity and the cached library components a file carries, overrides applied by key and order, local text values and instance overrides over a shared text style, grid track sizes (fixed, content-sized, fill), slot content, labels of connectors saved with their drawn path (a static snapshot; the ends aren't live), skip ink, paragraph options and hanging lists, list start numbers, vertical trim, per-point stroke joins, editable text on a path, image adjustments and images carried in the message; since 2026-10-29, style links that name a library style by asset key and version (the file's own copy of it), with override rows above the linking one still winning, and override rows restating a nested level's overrides applied at that level, below the instance's own (#1234), and the line breaks the file saved with a text, followed until an edit or a resize could move one, or where a line would come out more than 3% wider than its box in the fonts at hand (#1236). Budgets come from the file's own size (four decoded values per compressed byte, 20M–128M, lower ceilings on 32-bit targets; the layer cap follows the file's size too), so a 15.4 MB synthetic file with 300,000 layers opens whole; ZIP image reads have a separate total budget of 4 GiB (1 GiB on 32-bit targets) of decompressed ZIP-member bytes containing encoded images, with the 256 MiB per-image cap kept: a member that cannot fit is skipped before its output buffer is allocated, and the import report names the budget and counts skipped images (#1076). Failed reads and invalid image contents still consume the bytes read; a reference used by several layers is read once. This is not a limit on decoded pixels or total import memory; images carried inside the message are unchanged. The file's bytes stay out of the command journal; an import report lists what was left out or changed once the file opens. Elbowed and curved connectors without a saved path are routed as FigCraft's board connectors are (right angles, or one curve, from the sides of the layers they join); an elbowed one saved with its path (`connectorControlPoints`: a point and an axis per run between the first and the last) keeps that path when it leaves and arrives by the ends' sides (#1910), and a curved one's saved `connectorBezierControlPoints` are not read; a connector routed here takes its line's paint, weight, cap and dashes from the file's generated line record, as one with a saved snapshot does (#1807). A connector's label without a saved snapshot is kept as text centred on its line, without its background. Not read: table cells beyond their own layers, live style and variable links for vector region fills, variables bound to fields the editor can't bind, video fills. Tested on fixtures generated in code (`crates/format/src/fig/tests.rs`, `tail_tests.rs` and the per-feature `*_tests.rs` beside them, fuzzed), `crates/engine/src/shapebuilder_region_paints_tests.rs`, and by reading back what the export writes; the FigJam report sample from #1341 checked locally only; no representative real-world corpus yet | read tail 5–10, write: checks against real files 5–15 | +| `.fig` (Figma Design, `com.figma.document`, `application/x-figma`) | native (cloud; "Save local copy") | **yes, best effort** (`file.open`, `file.import`, drop, CLI, MCP) | **experimental** ([below](#export-to-fig-experimental)) | `.fig` files open (best effort): the zip, its deflate/zstd chunks and the kiwi schema are decoded generically and mapped by field name onto the REST importer, so pages, the layer tree, geometry, paints (styles resolved), strokes, effects, text with styled runs, vectors as editable vector networks with region-specific fill paints (points, curved segments, filled areas with their winding, per-point corner radius and handle mirroring, end caps; outlines when the network is missing or damaged), auto layout (grid included; a flow that records no primary-axis sizing hugs on that axis, an instance that records no auto layout has its main's), constraints, ellipse arcs, boolean operations (with their corner radius and smoothing, #2222), components, sets (with their descriptions), instances (expanded from their main with overrides, derived layout and property values; the size and resizing their layers override stay overrides; an instance scaled with the Scale tool, which stores `symbolData.uniformScaleFactor`, draws its layers at the main's lengths times that factor, composed through nested instances: sizes and places, corner radii, stroke weights and dashes, effect radii, spreads and offsets, auto layout gaps and paddings, grid gaps, min and max sizes, layout grids, font sizes, pixel line heights and letter spacings, paragraph spacing and indent, except where an override or derived row gives the value, which is already at the instance's scale; per-point vector corner radii also take their vector-data row's factor; the vector outline paths a layer carries (a network's points follow the layer's size), fixed grid tracks, image tile scales and glass effects are not scaled by the factor, #2091), styles, variables with modes and bindings, prototyping (set-variable, set-variable-mode and conditional actions included) and image fills from the archive come across; sticky notes and shapes with text keep their generated backgrounds, styled text, text paints, saved child bounds and sticky author lines as editable frame children, including saved vector networks without geometry paths, outer fill/stroke outlines when generated geometry is damaged, and outer body text when its generated child is unusable even if an author survives (#1341, #1397); connectors, tables, code blocks, slides and similar layers come in as the closest frames, text layers and vectors, with a warning; anything else is a warning. Since 2026-10-17 (community batches #727, #728): an instance's own identity and the cached library components a file carries, overrides applied by key and order, local text values and instance overrides over a shared text style, grid track sizes (fixed, content-sized, fill), slot content, labels of connectors saved with their drawn path (a static snapshot; the ends aren't live), skip ink, paragraph options and hanging lists, list start numbers (Figma writes a list's start on every line; import keeps it only on the item where the list starts counting, so a list split later restarts at 1, #2273), vertical trim, per-point stroke joins, editable text on a path, image adjustments and images carried in the message; since 2026-10-29, style links that name a library style by asset key and version (the file's own copy of it), with override rows above the linking one still winning, and override rows restating a nested level's overrides applied at that level, below the instance's own (#1234), and the line breaks the file saved with a text, followed until an edit or a resize could move one, or where a line would come out more than 3% wider than its box in the fonts at hand (#1236). Budgets come from the file's own size (four decoded values per compressed byte, 20M–128M, lower ceilings on 32-bit targets; the layer cap follows the file's size too), so a 15.4 MB synthetic file with 300,000 layers opens whole; ZIP image reads have a separate total budget of 4 GiB (1 GiB on 32-bit targets) of decompressed ZIP-member bytes containing encoded images, with the 256 MiB per-image cap kept: a member that cannot fit is skipped before its output buffer is allocated, and the import report names the budget and counts skipped images (#1076). Failed reads and invalid image contents still consume the bytes read; a reference used by several layers is read once. This is not a limit on decoded pixels or total import memory; images carried inside the message are unchanged. The file's bytes stay out of the command journal; an import report lists what was left out or changed once the file opens. Elbowed and curved connectors without a saved path are routed as FigCraft's board connectors are (right angles, or one curve, from the sides of the layers they join); an elbowed one saved with its path (`connectorControlPoints`: a point and an axis per run between the first and the last) keeps that path when it leaves and arrives by the ends' sides (#1910), and a curved one's saved `connectorBezierControlPoints` are not read; a connector routed here takes its line's paint, weight, cap and dashes from the file's generated line record, as one with a saved snapshot does (#1807). A connector's label without a saved snapshot is kept as text centred on its line, without its background. Not read: table cells beyond their own layers, live style and variable links for vector region fills, variables bound to fields the editor can't bind, video fills. Tested on fixtures generated in code (`crates/format/src/fig/tests.rs`, `tail_tests.rs` and the per-feature `*_tests.rs` beside them, fuzzed), `crates/engine/src/shapebuilder_region_paints_tests.rs`, and by reading back what the export writes; the FigJam report sample from #1341 checked locally only; no representative real-world corpus yet | read tail 5–10, write: checks against real files 5–15 | | `.penpot` (Penpot 2.x ZIP export) | — | **yes, offline** (open, import, drop, CLI, MCP) | **yes, offline** (export, CLI convert) | Editable layers, supported flex/grid layout, components, tokens and prototypes using the existing model. Unsupported layouts retain saved positions and bounded metadata; toggle-overlay and embedded font binaries are reported. Font references remain editable; no downloads. Synthetic regression coverage; live Penpot and cross-platform QA remain open. See [Penpot reference](penpot.md). | further live Penpot and cross-platform QA | | `.sketch` (Sketch 48 and newer) | import (file browser ▸ Import or drop, desktop app too; converted to a Figma file, symbols as components; per the help center) | **yes, best effort** (`file.open`, `file.import`, drop, CLI, MCP; Open With from Finder, Explorer and Linux file managers once installed; recent files show its `previews/preview.png`) | no (out of scope) | zip + JSON read from the public format description; Sketch 43–47 (text as binary property lists) and older (SQLite) files are refused with a message to resave them in a newer Sketch. Pages, artboards as frames with their background, groups; Sketch 2025 and newer: frames (clipping or not) with their style, graphics, stacks as auto layout (direction, gap, alignment, padding, wrap, hug/fill sizing, stretching filling every item across, items ignoring the stack), corners in the style (rounded, smooth with its smoothing; angled, inside square and inside arc as paths), pins and sizing, per-side borders, lists of blurs (progressive background blurs, glass), inner shadows in the shadow list, tints (a graphic's, group's or instance's fill colouring its layers, and colour overrides; from Sketch 64, before which a group's fill draws nothing), text colour and visibility overrides, text sized by its sizing; rectangles with corner radii, ovals, stars and polygons while their points are the generated ones, paths as editable vector networks, shape groups as their shape, as one compound path (children without an operation, by the group's winding rule) or as boolean operations (mixed operations nested from the left); operands' own borders ignored as Sketch does; open paths filled as if closed, edited ovals and rectangles as paths, bitmaps (their image under their style's fills; colour adjustments as image filters with Sketch's tone curve, contrast and then brightness added), slices, hotspots; transforms (rotation, flips after it), resizing constraints; fills (solid, gradients with Sketch's geometry, gradients mixed in OKLab or OKLCH as sRGB stops along the same colours, image patterns), borders (the first enabled border's width and position), shadows, inner shadows, layer, motion and background blurs (Sketch's radius is the standard deviation), opacity and blend modes; clipping masks (an outline mask that shows its own style draws a copy under itself, as Sketch does, and its opacity fades it and what it clips together; alpha masks only mask; broken mask chains wrapped), progressive opacity (Fade) as an alpha mask of its gradient; text with styled runs (UTF-16 ranges), paragraph and vertical alignment, lines placed by Sketch's line spacing behaviour, box sizing, fonts found by their PostScript names among the installed ones (else the family read from the name), variable font axes, Sketch's natural line (ascent and descent rounded, no line gap, a fifth more for classic Mac fonts) for text without a fixed line height; symbols as components (library copies on a page of their own) and instances carrying their masters' layers with overrides (text, nested swaps and hiding, images, also on shapes' image fills, layer and text styles, nested paths), clipping only where the master clips (`clippingBehavior` 1), laid out for their size the way Sketch does it (proportional sharing per pins from format 110, scaling before) and still live; master backgrounds in instances only when the master includes them in both instances and exports, as on Sketch's canvas and renders; Apple's system fonts found under the names designs use, with the platform's tracking kept as letter spacing; shared layer styles as paint (fills, border colours) and effect styles, shared text styles as text styles; Color Variables (also library ones) as colour variables with bindings; prototype links, flow starts, export options, layout and square grids (hidden, as Sketch shows them only in its layout view). Instances of a stack laid out at their size and texts an override changed measured again on open, an auto-width one growing from its aligned edge. Warnings: noise fills, OKLab and OKLCH gradients, motion and zoom blurs (drawn as plain blurs), fonts embedded with their data (not used), Smart Layout (kept as laid out), locked overrides, scaled instances. Tested on fixtures built in code (`crates/format/src/sketch/*_tests.rs`, fuzzed) and locally (`FIGCRAFT_SKETCH_SAMPLES`) on one real Sketch 50 file and the public Apache-2.0 IBM Carbon Design Kit saved by Sketch 68 and 83 (70,000 layers open in ~3 s, debug build; its edition saved by Sketch 47 is refused, as it should be); compared artboard by artboard with Sketch 2026's own renders (`FIGCRAFT_SKETCHTOOL`, black-box): the Sketch 50 file's 73 artboards differ in at most 2.3% of their pixels (0.8% on average) (text metrics, fonts FigCraft doesn't find, antialiasing), Carbon 11's 69 1.1% on average and at most 4.4% (text in IBM Plex, which the file embeds and FigCraft doesn't use yet), a Sketch 64 file's 65 artboards 2.1% on average, a Sketch 2026 showcase file's 16 frames 0.9% on average (at most 1.9%); the rules for master backgrounds, symbol clipping, mask opacity, bitmap fills, image overrides, stretching stacks, blur radii, colour adjustments, gradient interpolation and text growth checked against Sketch's renders of files built for each case (black-box, synthetic) | 5–10 (Smart Layout as auto layout, motion and zoom blurs, several borders of different widths; fonts embedded in the file once `.figcraft` documents can carry fonts: until then they would only last the session). Known limitations: a plain group (not a frame) that fills a stack keeps its layers' size where Sketch stretches them; a font Sketch can't find draws in the installed family's own weight (Sketch falls back to a regular face); text in the system SF Pro comes out a few percent narrower than Sketch's; macOS's reserved system fonts (PingFang) aren't found; brightness past about +0.4 is approximated (image filters can't add); OKLab gradients become sRGB stops (FigCraft gradients mix in sRGB) | | `.jam` (whiteboards) | native to FigJam | **yes, best effort** (`file.open`, `file.import`, File ▸ Open, drop, CLI, MCP) | no | the same archive as a `.fig` (its canvas header reads `fig-jam.`) through the same reader (#1342): it opens as a board (the file kind; a `.fig` stays a design file), with stickies as native board stickies (their colour, text and author kept, size as saved, #1808) and generated shape backgrounds and text kept (#1341) as ordinary layers rather than native board objects (see [boards-parity](boards-parity.md)); tables, stamps, code blocks and the like come in as frames with their text and connectors as vectors (an elbowed connector keeps the path it was saved with, #1910), with an import note; a layer type the reader doesn't know is left out with a note naming it; writing `.jam` is not supported | — | @@ -91,7 +91,7 @@ an inherited style link keep their own values and the link; stale copies on the still yield to the style. These cases have synthetic export/import regressions, including nested scales and empty-style clears; they have not been checked in other software. -- **Written:** pages (name, background); frames, groups, sections, rectangles (as rounded +- **Written:** pages (name, background, prototype background as an opaque colour, for every page); frames, groups, sections, rectangles (as rounded rectangles, with their four radii), ellipses (arcs), polygons, stars, lines, vectors (editable network blobs with per-point corner radius, handle mirroring, caps and joins, plus the outline of their filled areas), text, boolean groups, slices; the fill outline of frames and shapes and the @@ -136,7 +136,7 @@ scales and empty-style clears; they have not been checked in other software. text (written as values), variables' publishing, code syntax and inheritance settings, extended collections (written as collections of their own), comments, Developer Mode annotations, statuses, resources, measurements and code links, plugin data, ruler - guides, prototype device settings, slot properties and slot content, brush + guides, a page's prototype device settings (device, rotation, colour, custom size, responsive), the opacity of a page's prototype background (written opaque), slot properties and slot content, brush strokes (written plain), strokes wider on one side of their path (written as filled outlines, or with the width on both sides when the shape has a fill too), pattern fills, WebP export settings (written as PNG), image adjustments, glass settings other than frost, springs other than Gentle (written as ease @@ -195,6 +195,8 @@ scales and empty-style clears; they have not been checked in other software. | Date | Change | Summary | |---|---|---| +| 2026-11-12 | patch | M6, #2273: `.fig` import: a numbered list keeps its start only on the item where it starts counting. Figma writes the start on every line of the list (measured in Figma's web app, 2026-11-12, from a saved .fig: a list started at 5 has `listStartOffset` 4 on all its lines, and after Backspace takes a middle item out of the list, the item after it starts a new list and is written with 0), so reading every line's value restarted the items after a split at the old start. The export is unchanged and a re-import now equals what went in; REST `listStartOffsets` read the same way | +| 2026-11-13 | minor | M6, #2326: `.fig` export writes a page's prototype background (the file's `prototypeBackgroundColor`, field 141, a plain colour, written for every page, so Figma shows the same colour and not its own default for a page at FigCraft's default), measured on a synthetic file saved from Figma's web app. The colour is written opaque, as that file has it and as the importer reads it; a background that isn't opaque gets a warning for its opacity. The device warning now fires only for the page's device settings (device, rotation, colour, custom size, responsive), which stay left out. Checked through the importer only, not in other software. Numbers unchanged. | | 2026-11-12 | minor | M6, #2305: the `.fig` export writes a text's list spacing (`listSpacing`), hanging punctuation (`hangingPunctuation`), hanging lists (`hangingList`) and vertical trim (`leadingTrim`: none or cap height), which the importer already read. A field is written only when it differs from its default (in a design file saved by Figma, a text at the defaults carries none of the four), and an instance override that goes back to the default clears it. The warning narrows to OpenType features, which the importer does not read from a `.fig`. Checked through the importer only, not in other software. | | 2026-11-10 | minor | M4, #2222: a boolean group's corner radius and smoothing are read and written by the `.fig` importer and exporter, and by the REST importer | | 2026-11-07 | patch | Fonts, #2092: a font loaded with `text.loadFont` is the counterpart of a font uploaded to the organization, which Figma's help center ("Manage conflicting fonts") ranks first, ahead of installed fonts and the web fonts. FigCraft chose the first face added for a family and style, so the built-in Inter 4.x kept Regular, SemiBold and Bold after Inter 3.19 was loaded and only Medium refitted. A loaded face now wins over the other faces of its family and style, the latest load over earlier ones; style matching and fallbacks are unchanged, and `refitted` lists the text whose size changes. Installed versus built-in order is not changed here. Test: `fontdb::tests::a_loaded_face_wins_over_the_built_in_one_of_its_family_and_style`. Numbers unchanged. | diff --git a/docs/mcp.md b/docs/mcp.md index 21dfe8ca9..8d03540ba 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -498,7 +498,7 @@ one undo step and returns the ids it made: in the app does both). - `board.mindMap {x?, y?, text?, children?, parent?, edit?}` → `{id, text, children: [{id, text, connector}]}`: a mind map: a first node (`mindNode`, bold 24, no box; `text` defaults to `Topic`, `x`/`y` to the - middle of the view) with up to 20 `children` (texts; default `Idea 1`, `Idea 2`, `Idea 3`) + view's centre, in the parent's coordinates) with up to 20 `children` (texts; default `Idea 1`, `Idea 2`, `Idea 3`) on its right, each joined to it by a curved branch (a connector with `branch: true`: stroke 4, `#757575`, round caps). The map lays itself out: children stand in one column 88 units right of the widest node of their parent's column, 48 apart, centred on their parent; a node is its text, diff --git a/docs/ui-parity.md b/docs/ui-parity.md index f5215a134..0ac8a26f7 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI and interaction parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-13 · **Change:** minor (M1: Paste over selection puts the pasted layers just above the selected layer; M8: Tab while renaming the last layer wraps to the first row, measured in Figma's web app on 2026-11-12; the text caret takes the text's solid fill colour (#2156); the Rotation field shows and sets the rotation on the page, in frames and groups, through node.set absoluteRotation (#2196); the eyedropper picks a magnified image's pixel under the pointer, not a blend with its neighbours (#2189); Selection colors shows from one distinct colour when a selected layer has children, and from two otherwise, measured in Figma's web app on 2026-11-09 on a frame, a group and plain rectangles; the crosshair of the shape and Text tools is drawn dark with a white edge, so it shows on a white frame whatever the system's pointer style (#2198); a boolean group takes a corner radius (and smoothing) that rounds every sharp corner of its result (#2222); the Point section's X and Y in vector edit mode show Mixed and set every selected point of the layer being edited, as in Figma; Preferences ▸ Invert zoom direction reverses wheel zoom, pinch unchanged (#2145); Shift while rotating lands on absolute multiples of 15°, measured in Figma; Flatten bakes a vector's point corner radius into its path (#2195); a click on a fill, stroke or effect row's grip or background highlights it, Cmd/Ctrl+C copies that paint or effect and Cmd/Ctrl+V pastes it onto the selected layers, as the help center's Copy and paste properties between layers says (#1494); wrap style per paragraph and in text styles (#1827); the Annotation tool (Shift+T, `tool.annotation {id?}`): with a layer selected (or an `id`) it asks the UI for that layer's note at once, and in the tool a press on a layer selects it and asks for its note, a press on empty canvas does nothing; the marquee follows Figma's measured rules: a partly covered frame or section gives the layers in it the marquee touches, a rotated shape is touched by its outline, a drag from inside a frame selects that frame only when the marquee also takes another top-level frame (then whole) (`marquee_behaviour_tests`); copy, cut and paste in vector edit mode act on the selected points and segments (#1875); M8, #2146: K focuses the Scale tool's factor field with its text selected, so K, 2, Enter scales the selection by two about the panel's origin (FigCraft's starts at the top left; Figma's grid starts at the centre, left for a follow-up because the origin also sets where a handle drag pivots, which is not measured) in one undo step, after which the tool returns to Move with the selection kept; Escape in the field closes it with the tool back on Move and nothing changed (measured in Figma's web app, 2026-11-09; `pressing_k_focuses_the_scale_field_with_its_text_selected`, `k_two_enter_scales_the_selection_by_two`, `escape_in_the_scale_field_closes_it_and_changes_nothing`); the main menu and its submenus stay inside the window, moving up to fit and scrolling when taller (#2217); locked layers ignore the arrow keys and a locked parent's children can't be locked on their own (#1560); the left rail's and tab strip's icons are larger, 20 pt (#553); pick select: Tab while the keyboard selection box shows (or the chord again) puts a pink outline on a layer and the keys walk the layer tree from it, as Accessibility at Figma says (#1836); scrubbing a field faster or slower by the pointer's height, with a notice of the speed, as the help center's Scrub fields says (#1837); component rows in the Layers panel at AA contrast in the theme's component tint, with the rows inside a selected component in a tone of its row (#1903); Cmd/Ctrl-click on a padding field sets all four sides with the value typed, a documented auto layout shortcut; a fill per region of a vector: with regions selected in edit mode, the Fill section and the fill commands edit those regions' own fills, as Edit vector layers says (#1875); the Fill section of a text whose characters were coloured differently while editing shows mixed content, characters that all share fills the layer doesn't have show those, and a layer-level fill edit reaches every character (#1856); a number field scrubs when dragged with Alt held, as the help center's scrub section says, not only by its label; reuse visible layer selection roots (M8); ; with a shape or frame tool chosen and nothing selected, the arrows show a placement crosshair in the middle of the view and move it, and Enter places there, as Accessibility at Figma says (#1839); text direction per paragraph: Text ▸ Text direction forces a paragraph left to right or right to left, as Add right-to-left text says (#1830), with `text.direction`, `node.set textDirection`, the Type settings control once a right-to-left script is in the text, inspect, the CSS `direction` and the `.fig` lines' `sourceDirectionality`; the boolean operation menu in the Design panel leads each entry with an original icon drawn in code, a filled preview of the result (#2003); a press on the open gradient's handles or stops on the canvas keeps the colour picker open through the drag, as its own control (#1852); a click with the Bend tool on a sharp point curves it, its handles along the line between its neighbours, as Edit vector layers says (#1875); wrap style: Auto, Balance and Pretty on a text layer decide where its lines break, as Explore text properties says (#1827), with the Type settings control, `text.wrapStyle`, `node.set wrapStyle`, inspect and the CSS `text-wrap`; Backspace or Delete at the start of a list item keeps the item's indentation level, as the lists article says; max lines on auto-width text keep it auto width, hugging that many lines, as the text properties article says; superscript and subscript are synthesised where the font has no glyphs for them, from the standard glyphs shrunk and shifted by the font's OS/2 metrics, and a run mixing available and unavailable glyphs is synthesised whole, as Explore text properties says (#1828); Alt+Enter while editing text opens the link at the caret, as the accessibility page documents; Minimize, by its shortcut or the button by the file name, collapses the navigation bar and both sidebars as the help center says, with the right sidebar back while something is selected (#1835); the interface size keys of the help center's accessibility page: Cmd/Ctrl+Shift+Alt with =, - and 0 step the interface through the Preferences sizes and back to the system's size; Cmd/Ctrl+Alt+arrows rotate the selection a degree at a time, 15 with Shift, as the help center's accessibility page says; they resized before; the Layers panel answers Ctrl+1 as well as Alt+1 on Windows and Linux, the two keys the help center gives it; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the keyboard's Menu key opens the context menu, as Shift+F10 does; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; sidebar number and text fields keep their text vertically centered when focused, including typography spacing; with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); colour picker review fixes for text undo, fitted sidebars, moving controls and gradient variables; Corner smoothing: an original icon and the shared number-field drag gesture, preserving fractional baselines; guides snap to layers when dragged; Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); the Design panel's sections on one grid — 16 / 8 margins, 88 + 8 + 88 + 8 + 24 columns, 24 pt rows, 4 pt between a row's buttons (#858); the toolbar on one 32 pt grid, without its Resources button (#1210); colour picker LCH and OKLCH models; an XML (Android Vector Drawable) export format; Context menus: the Menu key reaches egui 0.37 but is unbound (row done → partial); the Text on a path tool; board tool keys pinned; community fixes: the text box by dragging, the font picker keys, the pen path on leaving Design, a still canvas in vector edit mode, a scrolling pages list, colour emoji, readable new text in frames, system theme on first run; the Small caps sample in Type settings drawn from capitals; recent files as cards; vector edit mode: hovering, hatching, selecting and dragging filled regions; home screen: Templates tab, first-run templates and Getting started tips; number fields: scrub rates, arrow steps, arithmetic with brackets, relative edits of mixed values; outline mode's hidden layers and object bounds; Hide when publishing; cursors per tool and modifier; panel widths; dark pages for files made in the dark theme; drag threshold and double-clicks into text in groups; rotation origin on Alt+R and placing with Enter: no documented shortcut missing; keyboard shortcut parity suite and bindings; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and the vector edit tail; canvas navigation, guides and grids behaviour suite and fixes; shapes and vector behaviour suite and fixes; paint and effects behaviour suite and fixes; frames, groups, sections and masks behaviour suite and fixes; layers panel keyboard: F2 rename, Shift+F10 context menu, F8 box selection; selection and transform behaviour suite and fixes; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; boolean hit testing on the result, group drags, frame outlines and slices; outlines for the selection, mask outlines; arc fields, live boolean editing, shape builder on strokes, one-sided widths; fields select their text on focus; Typography spacing icons support scrubbing (#373); CSS colour names in hex fields; a rename selects the whole name, so typing replaces it; Escape or Enter after a pen path stays on the same vector (#760); IME composition kept on through idle frames of a text edit, candidates at the caret (#747); Selection colors for mixed selections and smart-selection spacing (#753); submenus with a hover delay and a safe triangle; the Actions palette's tabs, ranked search, highlight and recents; menu items that ask for a value; editor fixes from the community batches) · **Target:** Figma Design UI3 (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-10 · **Change:** minor (M1: Paste over selection puts the pasted layers just above the selected layer; a mirror mode (angle, or angle and length) on a sharp point turns it smooth, as in Figma (#2110); M8: Tab while renaming the last layer wraps to the first row, measured in Figma's web app on 2026-11-12; the text caret takes the text's solid fill colour (#2156); the Rotation field shows and sets the rotation on the page, in frames and groups, through node.set absoluteRotation (#2196); the eyedropper picks a magnified image's pixel under the pointer, not a blend with its neighbours (#2189); Selection colors shows from one distinct colour when a selected layer has children, and from two otherwise, measured in Figma's web app on 2026-11-09 on a frame, a group and plain rectangles; the crosshair of the shape and Text tools is drawn dark with a white edge, so it shows on a white frame whatever the system's pointer style (#2198); a boolean group takes a corner radius (and smoothing) that rounds every sharp corner of its result (#2222); the Point section's X and Y in vector edit mode show Mixed and set every selected point of the layer being edited, as in Figma; Preferences ▸ Invert zoom direction reverses wheel zoom, pinch unchanged (#2145); Shift while rotating lands on absolute multiples of 15°, measured in Figma; Flatten bakes a vector's point corner radius into its path (#2195); a click on a fill, stroke or effect row's grip or background highlights it, Cmd/Ctrl+C copies that paint or effect and Cmd/Ctrl+V pastes it onto the selected layers, as the help center's Copy and paste properties between layers says (#1494); wrap style per paragraph and in text styles (#1827); the Annotation tool (Shift+T, `tool.annotation {id?}`): with a layer selected (or an `id`) it asks the UI for that layer's note at once, and in the tool a press on a layer selects it and asks for its note, a press on empty canvas does nothing; the marquee follows Figma's measured rules: a partly covered frame or section gives the layers in it the marquee touches, a rotated shape is touched by its outline, a drag from inside a frame selects that frame only when the marquee also takes another top-level frame (then whole) (`marquee_behaviour_tests`); copy, cut and paste in vector edit mode act on the selected points and segments (#1875); M8, #2146: K focuses the Scale tool's factor field with its text selected, so K, 2, Enter scales the selection by two about the panel's origin (FigCraft's starts at the top left; Figma's grid starts at the centre, left for a follow-up because the origin also sets where a handle drag pivots, which is not measured) in one undo step, after which the tool returns to Move with the selection kept; Escape in the field closes it with the tool back on Move and nothing changed (measured in Figma's web app, 2026-11-09; `pressing_k_focuses_the_scale_field_with_its_text_selected`, `k_two_enter_scales_the_selection_by_two`, `escape_in_the_scale_field_closes_it_and_changes_nothing`); the main menu and its submenus stay inside the window, moving up to fit and scrolling when taller (#2217); locked layers ignore the arrow keys and a locked parent's children can't be locked on their own (#1560); the left rail's and tab strip's icons are larger, 20 pt (#553); pick select: Tab while the keyboard selection box shows (or the chord again) puts a pink outline on a layer and the keys walk the layer tree from it, as Accessibility at Figma says (#1836); scrubbing a field faster or slower by the pointer's height, with a notice of the speed, as the help center's Scrub fields says (#1837); component rows in the Layers panel at AA contrast in the theme's component tint, with the rows inside a selected component in a tone of its row (#1903); Cmd/Ctrl-click on a padding field sets all four sides with the value typed, a documented auto layout shortcut; a fill per region of a vector: with regions selected in edit mode, the Fill section and the fill commands edit those regions' own fills, as Edit vector layers says (#1875); the Fill section of a text whose characters were coloured differently while editing shows mixed content, characters that all share fills the layer doesn't have show those, and a layer-level fill edit reaches every character (#1856); a number field scrubs when dragged with Alt held, as the help center's scrub section says, not only by its label; reuse visible layer selection roots (M8); ; with a shape or frame tool chosen and nothing selected, the arrows show a placement crosshair in the middle of the view and move it, and Enter places there, as Accessibility at Figma says (#1839); text direction per paragraph: Text ▸ Text direction forces a paragraph left to right or right to left, as Add right-to-left text says (#1830), with `text.direction`, `node.set textDirection`, the Type settings control once a right-to-left script is in the text, inspect, the CSS `direction` and the `.fig` lines' `sourceDirectionality`; the boolean operation menu in the Design panel leads each entry with an original icon drawn in code, a filled preview of the result (#2003); a press on the open gradient's handles or stops on the canvas keeps the colour picker open through the drag, as its own control (#1852); a click with the Bend tool on a sharp point curves it, its handles along the line between its neighbours, as Edit vector layers says (#1875); wrap style: Auto, Balance and Pretty on a text layer decide where its lines break, as Explore text properties says (#1827), with the Type settings control, `text.wrapStyle`, `node.set wrapStyle`, inspect and the CSS `text-wrap`; Backspace or Delete at the start of a list item keeps the item's indentation level, as the lists article says; max lines on auto-width text keep it auto width, hugging that many lines, as the text properties article says; superscript and subscript are synthesised where the font has no glyphs for them, from the standard glyphs shrunk and shifted by the font's OS/2 metrics, and a run mixing available and unavailable glyphs is synthesised whole, as Explore text properties says (#1828); Alt+Enter while editing text opens the link at the caret, as the accessibility page documents; Minimize, by its shortcut or the button by the file name, collapses the navigation bar and both sidebars as the help center says, with the right sidebar back while something is selected (#1835); the interface size keys of the help center's accessibility page: Cmd/Ctrl+Shift+Alt with =, - and 0 step the interface through the Preferences sizes and back to the system's size; Cmd/Ctrl+Alt+arrows rotate the selection a degree at a time, 15 with Shift, as the help center's accessibility page says; they resized before; the Layers panel answers Ctrl+1 as well as Alt+1 on Windows and Linux, the two keys the help center gives it; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the keyboard's Menu key opens the context menu, as Shift+F10 does; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; sidebar number and text fields keep their text vertically centered when focused, including typography spacing; with the pen out, Enter or a double-click ends the path and edits the vector with the Move tool instead of drawing on (#1430); the Actions palette offers only commands that run from it, and no second row reading like a menu item: Place image opens the file dialog (#1574); Preferences ▸ Scroll wheel zoom: a mouse wheel zooms the canvas about the pointer and Cmd/Ctrl+wheel scrolls (#1390); boolean operations refuse input past their caps, and a boolean group past them draws without its result (#1104); the selection and hover outlines of rounded rectangles and frames follow their corners (#1506); colour picker review fixes for text undo, fitted sidebars, moving controls and gradient variables; Corner smoothing: an original icon and the shared number-field drag gesture, preserving fractional baselines; guides snap to layers when dragged; Crop image: Object ▸ Crop image, the right-click menu and the image fill row enter crop mode (`image.crop`, #1464); the Design panel's sections on one grid — 16 / 8 margins, 88 + 8 + 88 + 8 + 24 columns, 24 pt rows, 4 pt between a row's buttons (#858); the toolbar on one 32 pt grid, without its Resources button (#1210); colour picker LCH and OKLCH models; an XML (Android Vector Drawable) export format; Context menus: the Menu key reaches egui 0.37 but is unbound (row done → partial); the Text on a path tool; board tool keys pinned; community fixes: the text box by dragging, the font picker keys, the pen path on leaving Design, a still canvas in vector edit mode, a scrolling pages list, colour emoji, readable new text in frames, system theme on first run; the Small caps sample in Type settings drawn from capitals; recent files as cards; vector edit mode: hovering, hatching, selecting and dragging filled regions; home screen: Templates tab, first-run templates and Getting started tips; number fields: scrub rates, arrow steps, arithmetic with brackets, relative edits of mixed values; outline mode's hidden layers and object bounds; Hide when publishing; cursors per tool and modifier; panel widths; dark pages for files made in the dark theme; drag threshold and double-clicks into text in groups; rotation origin on Alt+R and placing with Enter: no documented shortcut missing; keyboard shortcut parity suite and bindings; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and the vector edit tail; canvas navigation, guides and grids behaviour suite and fixes; shapes and vector behaviour suite and fixes; paint and effects behaviour suite and fixes; frames, groups, sections and masks behaviour suite and fixes; layers panel keyboard: F2 rename, Shift+F10 context menu, F8 box selection; selection and transform behaviour suite and fixes; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; boolean hit testing on the result, group drags, frame outlines and slices; outlines for the selection, mask outlines; arc fields, live boolean editing, shape builder on strokes, one-sided widths; fields select their text on focus; Typography spacing icons support scrubbing (#373); CSS colour names in hex fields; a rename selects the whole name, so typing replaces it; Escape or Enter after a pen path stays on the same vector (#760); IME composition kept on through idle frames of a text edit, candidates at the caret (#747); Selection colors for mixed selections and smart-selection spacing (#753); submenus with a hover delay and a safe triangle; the Actions palette's tabs, ranked search, highlight and recents; menu items that ask for a value; editor fixes from the community batches) · **Target:** Figma Design UI3 (desktop app 126.10.7) Fine canvas control is what Figma users feel first: handles, snapping, nudging, modifier keys, drag behaviour, numeric precision. This checklist covers the tools, gestures and panels. Status: @@ -74,7 +74,7 @@ interaction feel only partly compared: the interactions measured so far, case by | Drag threshold; double-click into groups and text | done | a press moves or resizes only once the pointer has travelled 3 px on screen, so a click or double-click made with an unsteady hand drags nothing; a double-click goes one level into a group and the next one edits the text under it, wherever on the text it lands, with all of it selected (a double-click in the text being edited selects the word) (`double_click_tests`); Enter on a selected text does the same (all of it selected, typing replaces it) and Escape leaves editing with the layer still selected (`text_enter_tests`) | | Scale tool (K): handles about an anchor, live factor, panel | done | Pressing K opens the Scale section with its factor field focused and its text selected; typing 2 (or 2x, 1.5) then Enter scales the selection by it about the panel's origin (FigCraft's starts at the top left; Figma's grid starts at the centre, left for a follow-up because the origin also sets where a handle drag pivots, which is not measured), as one undo step, then closes the section and returns to Move with the selection kept; Escape in the field closes it, back to Move, nothing changed. Measured in Figma's web app, 2026-11-09. Tests: `pressing_k_focuses_the_scale_field_with_its_text_selected`, `k_two_enter_scales_the_selection_by_two`, `escape_in_the_scale_field_closes_it_and_changes_nothing`. | | Nudge 1 / Shift 10 (preference), Cmd+arrows resize | done | arrows reorder auto layout children | -| Smart guides: edges, centres, equal spacing (between two layers or continuing a row's gap, labelled), spacing labels, parent, layout grid, ruler guides | done | red, `snap.rs`; a guide dragged out of a ruler or moved snaps to layer edges and centres too (Snap to Objects; Cmd/Ctrl suspends), on its own axis only; page guides see the page's top-level layers, frame guides the frame's box, layout grids and every layer in it, along a rotated frame's own axes; thresholds not yet compared with Figma's (`guide_snap_tests`) | +| Smart guides: edges, centres, equal spacing (between two layers or continuing a row's gap, labelled), spacing labels, parent, layout grid, ruler guides | done | red, `snap.rs`; a guide dragged out of a ruler or moved snaps to layer edges and centres too (Snap to Objects; Cmd/Ctrl suspends), on its own axis only; page guides see the page's top-level layers, frame guides the frame's box, layout grids and every layer in it, along a rotated frame's own axes; the object snap threshold is 4.5 screen pixels, measured against Figma (snapped at a gap of 4.4 screen px, not at 4.6, at 100% and 200% zoom, 2026-11-08; the equal-spacing snap shares it), but the ruler-guide and rotation-origin thresholds (5 px), the red guide's look and snapping with Snap to pixel grid off are not yet compared with Figma's (`guide_snap_tests`, `transform_behaviour_tests`) | | Ctrl to suspend snapping while dragging (macOS) | done | Control on macOS (Cmd keeps working), Ctrl elsewhere; moving, resizing and drawing | | Measure (Alt hover, Cmd+Alt nested, Shift+Alt padding/gaps) | done | labels never overlap; the arrows still nudge while measuring (Shift: the big step) and the distances follow; the selection's handles and size label hide while measuring (`measure_nudge_tests`, #894) | | Pixel grid snapping, pixel preview, 2x preview | done | moves, resizes and new shapes land on whole pixels; the pixel grid shows from 400% (`view_behaviour_tests`) | @@ -97,7 +97,7 @@ interaction feel only partly compared: the interactions measured so far, case by | Rectangle, ellipse (arc handles and Design panel arc fields), polygon, star, line, arrow; Shift/Alt | done | Alt draws lines from the centre too (`shapes_behaviour_tests`) | | Corner radius handles (inside each corner of a rectangle or frame, a polygon's or star's top point; Alt: one corner), star ratio handle; Count and Ratio fields | done | handles hide under 48 px on screen; no count handle on the canvas (the Count field instead); corner smoothing rounds rectangles and frames only | | Pen: vector networks, branch, close, bend; pencil | done | pen pressure on Windows and from browser styluses only; outside edit mode the Pen closes on its first point, connects to its other points and continues a selected open path from an end point (`vector_multi_behaviour_tests`); Escape ends the path and keeps its layer in edit mode with the pen, so the next path joins the same vector and another Escape leaves edit mode (#760, `pen_end_tests`); Enter or a double-click ends the path (at the double-click's point, added once) and edits the vector with the Move tool, a double-click with the idle pen edits the layer under it, and in edit mode the pen's Enter or double-click takes the Move tool (#1430, `pen_vector_edit_tests`); switching from Design to Prototype or Inspect ends the path and returns to Move (#308) | -| Vector edit mode: bend, paint bucket, lasso, cut, eraser, transform box, point snapping, mirroring | done | a double-click a few pixels off a thin stroke enters edit mode (#646); entering edit mode and picking a region keep the canvas still (#322); a point dropped on another point merges with it, and dropping one end of an open path on the other closes it (a 2-point line's end just moves, #401); Flatten keeps open paths open (#377), and bakes a vector's point corner radius into its path (each rounded point becomes the arc's end points joined by curves, the layer stays a vector and its box fits the real geometry, #2195); paint bucket drags across areas; cut drags divide a shape into layers; delete and heal follows the curve; rounded points are drawn; Shift-click deselects a point at a corner of the box (`vector_behaviour_tests`); several vectors edited at once, Shift-click handles to drag them together, a cap and join per point, rounded points beside curves (`vector_multi_behaviour_tests`); filled regions with the Move tool: the area under the pointer is hatched ("/" lines in the selection colour, clipped by the area's own fill rule, holes left out, gone 3.5 px from a point or 2 px from a segment at any zoom), the line spacing follows octave folding (fitted to measurements at several zoom levels: 8 px at every power-of-two zoom, growing with the zoom and stepping back at √2 · 2ⁿ) and stays fixed to the shape when panning; a click selects the area and its points (moved with it but drawn unselected), Shift adds or removes an area, a press on a selected area drags the whole selection, no hover hatch during drags, a click on an empty spot (a hole) clears it and stays in edit mode; `vector.edit.select {regions}` (`regions_tests`, `vector_regions_tests`); a Bend click on a sharp point between two segments curves it (handles along the line between its neighbours, a third of the way to each, `ops::auto_smooth`), on a curved one sharpens it, a drag sets the handles by hand (#1875); with regions selected, the Fill section (its rows and the colour picker) and `fill.set`, `fill.add`, `fill.remove`, `fill.move` and `fill.paste` edit those regions' own fills, the layer's untouched, or the regions named by `regions: [index, ...]`; Copy fill takes the region's paint, the colour picker and its canvas gradient and crop handles edit it (an image from Upload from computer included; a file dropped on the picker goes to the canvas instead), what belongs to the layer (its fill style, a variable bound to its fill, the image crop button) stays off a region's rows, and `fill.pattern` sets the layer's fill (#1875); the Point section's X and Y show the value the selected points share, or Mixed, and a typed value sets every selected point's own coordinate, in the layer being edited (measured in Figma on 2026-11-08); Copy and Cut with points or segments selected take just those (a lone point: the segments touching it) as a vector with the layer's look, at their own place, so a paste outside edit mode is a new layer in place; Cut removes them as Delete does, the path splitting in the same layer with edit mode staying on; Paste while editing adds the clipboard's segments, or a copied shape's or boolean's outline, to the edited network in place with the new points selected, skipping layers with no outline (text, frames, groups; named in `skipped`) and refusing when none has one, as measured in Figma (`vector_clipboard_tests`, #1875). Not yet: areas of other layers edited at once; the Point section's X and Y over points of several edited layers | +| Vector edit mode: bend, paint bucket, lasso, cut, eraser, transform box, point snapping, mirroring | done | a mirror mode on a sharp point turns it smooth by the measured rule (#2110); a double-click a few pixels off a thin stroke enters edit mode (#646); entering edit mode and picking a region keep the canvas still (#322); a point dropped on another point merges with it, and dropping one end of an open path on the other closes it (a 2-point line's end just moves, #401); Flatten keeps open paths open (#377), and bakes a vector's point corner radius into its path (each rounded point becomes the arc's end points joined by curves, the layer stays a vector and its box fits the real geometry, #2195); paint bucket drags across areas; cut drags divide a shape into layers; delete and heal follows the curve; rounded points are drawn; Shift-click deselects a point at a corner of the box (`vector_behaviour_tests`); several vectors edited at once, Shift-click handles to drag them together, a cap and join per point, rounded points beside curves (`vector_multi_behaviour_tests`); filled regions with the Move tool: the area under the pointer is hatched ("/" lines in the selection colour, clipped by the area's own fill rule, holes left out, gone 3.5 px from a point or 2 px from a segment at any zoom), the line spacing follows octave folding (fitted to measurements at several zoom levels: 8 px at every power-of-two zoom, growing with the zoom and stepping back at √2 · 2ⁿ) and stays fixed to the shape when panning; a click selects the area and its points (moved with it but drawn unselected), Shift adds or removes an area, a press on a selected area drags the whole selection, no hover hatch during drags, a click on an empty spot (a hole) clears it and stays in edit mode; `vector.edit.select {regions}` (`regions_tests`, `vector_regions_tests`); a Bend click on a sharp point between two segments curves it (handles along the line between its neighbours, a third of the way to each, `ops::auto_smooth`), on a curved one sharpens it, a drag sets the handles by hand (#1875); with regions selected, the Fill section (its rows and the colour picker) and `fill.set`, `fill.add`, `fill.remove`, `fill.move` and `fill.paste` edit those regions' own fills, the layer's untouched, or the regions named by `regions: [index, ...]`; Copy fill takes the region's paint, the colour picker and its canvas gradient and crop handles edit it (an image from Upload from computer included; a file dropped on the picker goes to the canvas instead), what belongs to the layer (its fill style, a variable bound to its fill, the image crop button) stays off a region's rows, and `fill.pattern` sets the layer's fill (#1875); the Point section's X and Y show the value the selected points share, or Mixed, and a typed value sets every selected point's own coordinate, in the layer being edited (measured in Figma on 2026-11-08); Copy and Cut with points or segments selected take just those (a lone point: the segments touching it) as a vector with the layer's look, at their own place, so a paste outside edit mode is a new layer in place; Cut removes them as Delete does, the path splitting in the same layer with edit mode staying on; Paste while editing adds the clipboard's segments, or a copied shape's or boolean's outline, to the edited network in place with the new points selected, skipping layers with no outline (text, frames, groups; named in `skipped`) and refusing when none has one, as measured in Figma (`vector_clipboard_tests`, #1875). Not yet: areas of other layers edited at once; the Point section's X and Y over points of several edited layers | | Shape builder (Shift+M) on fills, strokes and open paths; variable width (Shift+W), one side with Alt | done | | | Boolean groups: clicked where the result is, double-click or Cmd/Ctrl-click into operands, live results while dragging or editing points, per-operand operations | done | a group past the path operations' caps (250 000 segments, 2 million possible crossings, 4 million segments swept over a fold) draws without its result, with a warning, and Flatten refuses it (#1104); the Design panel's Boolean groups menu leads Union, Subtract, Intersect and Exclude with their own icons, two offset squares with the result filled at reduced alpha (#2003) | | Text: point, auto height, fixed; caret, words, lines, IME | done | Backspace or Delete at the start of a list item takes its marker and keeps its level, the paragraph starting where the item's text did ("delete the counter, but keep the same level of indentation", Create bulleted and numbered lists; `text_tail_tests::list_keys_at_list_items`, text crate `behaviour_tests`); max lines on auto-width text keep it auto width, hugging up to that many lines and growing with its longest line ("Text resizing is set to auto height or auto width", Explore text properties; `text_behaviour_tests::max_lines_on_auto_width_text_keeps_auto_width_and_hugs_that_many_lines`); Alt+Enter while editing opens the link at the caret, web and mail links only (`text.openLink`; "press ⌥Option Return/Alt Enter to activate a focused link", Accessibility at Figma; `text_link_tests`); the font picker previews a family on the canvas while hovered (no undo step; Escape restores, #653) and Up/Down step through it (#352); a selection highlight after a line break starts at that line's start and an empty last line shows its mark (#665); carets step over whole emoji and accented letters; colour emoji draw from their colour tables (#300); IME composition replayed in tests as macOS sends it, not yet checked on a Mac (#747); CJK words by script run (no dictionary); vertical trim in Type settings; the caret takes the text's solid fill colour, measured in Figma's web app, 2026-11-09; gradient and image fills (not measured) give a black caret on a light surface and a white one on a dark one (the nearest layer around the text whose top visible fill is a solid at least half opaque as drawn, counting layer opacity, else the page; a layer whose top fill is a gradient or an image is passed over), not the interface's text colour, which is white in the dark theme and vanished on the default light page (#2190) (#2156; `caret_tests`); no spell check | @@ -216,6 +216,8 @@ This audit records candidates for subsequent fixes; their behaviour is unchanged | Date | Change | Summary | |---|---|---| | 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-08 | patch | Smart guides: the object snap threshold is 4.5 screen pixels, measured against Figma (a dragged edge snapped at a gap of 4.4 screen px and not at 4.6, at 100% and at 200% zoom, Snap to pixel grid on); FigCraft used 5. Equal spacing shares the move's threshold so it follows; ruler-guide and rotation-origin snapping keep 5, unmeasured (`transform_behaviour_tests`) | +| 2026-11-11 | patch | M4, #2110: in vector edit mode, choosing Mirror angle or Mirror angle and length for a sharp point (two segments, no handles) makes it smooth, as measured in Figma: both handles on one line through the point, along `(B - A) / \|BA\|^2 + (C - B) / \|BC\|^2` (A and C the far ends of its segments), each 0.3905 x its own segment for angle, both 0.3905 x the shorter segment for angle and length (the factor is known to about three digits; the length rule is medium confidence); several selected points each become smooth. Open-path ends, points that already have a handle, points with a coincident neighbour, and points whose two far ends coincide (A = C, so the direction is zero) keep the old behaviour. Evidence: tests in `crates/engine/src/canvas/vectoredit/ops.rs` and `tests.rs` | | 2026-11-12 | patch | M8: Tab while renaming the last layer in the Layers panel commits and opens the first row's rename, as measured in Figma's web app on 2026-11-12 (it ended the rename before); Shift+Tab on the first row is unchanged, not measured; Tab and Shift+Tab now move only the rename and leave the selection on the layer first renamed, as measured in Figma's web app on 2026-11-12 (it followed the rename before) (`tab_on_the_last_row_commits_and_wraps_to_the_first`, `tab_while_renaming_leaves_the_selection_on_the_first_layer`), Rename row | | 2026-11-09 | patch | M3, #2156: the text caret takes the text's solid fill colour (red text, red caret; light grey on a dark frame, light grey, one colour and no inversion), measured in Figma's web app: the fill of the character before the caret (the first one's at the start); FigCraft draws it opaque (how Figma treats a translucent fill was not measured); gradient, image and hidden fills (not measured) give a black caret on a light surface and a white one on a dark one (the nearest layer around the text whose top visible fill is a solid at least half opaque as drawn, counting layer opacity, else the page; a layer whose top fill is a gradient or an image is passed over), not the interface's text colour (white in the dark theme, invisible on the default light page, #2190). Width and height unchanged; collaborators' carets unchanged. Tests: `caret_tests` | | 2026-11-10 | minor | The Rotation field shows and sets the layer's rotation on the page (its own angle plus its parents' when no ancestor is flipped; with a flipped ancestor FigCraft reads the composed angle, which flips the sign of the layer's own angle, and Figma's behaviour there was not measured), in frames and groups alike, as measured in Figma's web app for rotated, unflipped parents (#2196) | @@ -253,6 +255,7 @@ This audit records candidates for subsequent fixes; their behaviour is unchanged | 2026-11-06 | patch | M7, #2032: closing a tab whose file has unsaved changes, by its X, a middle click, File ▸ Close tab or its shortcut, only showed a toast ("save first, or close again with Alt to discard") and left the tab open, so closing seemed not to work. It now asks the unsaved-changes question the window asks (`windows::TabClose`): Don't Save closes the tab, Cancel or Escape keeps it, Save saves the file and then closes it (a file without a path, or saved as .fig, asks where with Save as first and stays open if that is cancelled); Alt+close still drops the changes at once, and `file.close`'s `dialog.unsaved` request asks too. The three toasts left the catalogs. Tests: `titlebar_tests::closing_a_tab_with_unsaved_changes_asks`, `titlebar_tests::save_in_the_tab_question_saves_then_closes`. Reordering tabs by dragging, the issue's other half, landed on 2026-10-19 (`dragging_a_tab_along_the_bar_reorders_it_without_detaching`) | | 2026-11-05 | minor | M4, #1830: a paragraph's base direction can be forced (`TextDirection`: Auto, Ltr, Rtl on `ParaList`): Text ▸ Text direction ▸ Auto / Left to right / Right to left (`text.directionAuto` / `Ltr` / `Rtl`) and `text.direction {direction, ids?}` set the edited paragraphs while editing, else the layer's; `node.set textDirection`; the Type settings control once a right-to-left script is in the text; inspect `textDirection` / `lineDirections`; CSS `direction`; `.fig` lines' `sourceDirectionality` in and out. Layout gives each paragraph its base level (`Bidi::of` runs the algorithm per paragraph, as it starts over at each). Before, direction came from the letters only ("controls are available to override text direction per paragraph", Add right-to-left text). Tests: `text_behaviour_tests::text_direction_is_forced_per_paragraph`, `fig::text_direction_tests::a_lines_source_directionality_is_its_paragraphs_direction_both_ways`. | | 2026-11-02 | minor | M1, #1836: pick select. Tab while the keyboard selection box shows, or Alt/Ctrl+Space again, puts 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 as the Layers panel lists them, Enter into a frame's top child, Shift+Enter out to the parent (never the page), Space selects the layer under it, Escape or a press on the canvas ends it; the chord again while the pick cursor shows brings the box back (Accessibility at Figma). The control channel's `ui.key` sends the box's and the pick cursor's keys to them too. One documented row more (135, 134 bound); four gesture rows. Tests: `layers_keyboard_tests::tab_switches_the_selection_box_to_pick_select`. | +| 2026-11-12 | patch | M8, #2238: every 24 pt icon button outside the Design panel draws its glyph at 16 pt through `widgets::icon_glyph_rect`, not 14 pt: the Layers panel's Minimize, search and add page buttons, the Assets back button, the Versions panel's row menus, the Dev Mode status button, the Prototype panel's flow buttons, the preview pane's bar buttons, Home's Online row menus and the style picker's 24 pt buttons. The popover's 24 pt close button draws its cross at 16 pt too. Smaller buttons (the picker's 22 and 20 pt ones) keep their smaller glyphs. Tests: `icon_button_size_tests` and the `icon_size_tests` beside the panels. Numbers unchanged. | | 2026-11-10 | patch | M10, #2227: the Design panel's section header buttons (Appearance, Typography, Fill, Stroke, Effects) draw their icons at the size of the panel's other 24 pt icon buttons, 16 pt (the icons' native size, as a fill row's eye), not 12 pt; `icon_button_at` goes from 14 to 16 pt with them; the Close and Swap buttons of the assets and prototype panels and the Design panel's Swap orientation and quick-action buttons share the inset. Test: `header_icon_size_tests`. Numbers unchanged. | | 2026-11-05 | patch | M1, #2003: the Design panel's boolean operation menu leads Union, Subtract, Intersect and Exclude with original icons drawn in code (two offset squares, the result filled at reduced alpha). Numbers unchanged. | | 2026-11-02 | minor | M8, #1875: a fill per region. With regions of a vector selected in edit mode (a press inside one with the Move tool, `vector.edit.select {regions}`), the Fill section lists the regions' own fills (the layer's for a region that has none; mixed content when they differ) and its rows and the colour picker edit them: `fill.set`, `fill.add`, `fill.remove`, `fill.move` and `fill.paste` on the edited layer go to the selected regions' stacks (`Region.fills`, what the renderer already draws), the layer's fills and fill style untouched; `regions: [index, ...]` names them on any vector layer (Edit vector layers). Tests: `regions_tests::the_fill_commands_edit_the_selected_regions`. Numbers unchanged. | diff --git a/sonar-project.properties b/sonar-project.properties index 5f58f42ae..7bd9e8ce6 100644 --- a/sonar-project.properties +++ b/sonar-project.properties @@ -1,6 +1,9 @@ sonar.projectKey=storytold_figcraft sonar.organization=storytold +# Pinned integration-test fonts are data, not source code for analysis. +sonar.exclusions=craft-fonts/** + # S4790 (weak hash): a .fig file names each image by the SHA-1 of its bytes (20 bytes, the only # length readers accept). It is an identifier the format fixes, not a security choice. sonar.issue.ignore.multicriteria=fig_image_sha1