Merge upstream/main into fix/layers-icon-double-click-zooms

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Model-Effort: Opus 5.5 drove; Opus 5.5 briefed; Sonnet 5.5 wrote at medium
This commit is contained in:
Trevor Brown
2026-11-13 11:39:35 -05:00
co-authored by Claude Sonnet 5.5
53 changed files with 1923 additions and 134 deletions
+22 -3
View File
@@ -2,15 +2,21 @@
//! `--no-system-fonts` or `FIGCRAFT_NO_SYSTEM_FONTS=1` opts out.
use std::process::Command;
use std::sync::atomic::{AtomicU64, Ordering};
use serde_json::{Value, json};
/// The result of one `figcraft-cli run` step (script file `name`); `opt_out` sets the environment
/// variable.
fn run_one(name: &str, step: Value, args: &[&str], opt_out: bool) -> Value {
static NEXT_SCRIPT: AtomicU64 = AtomicU64::new(0);
let d = std::env::temp_dir().join(format!("figcraft-cli-fonts-{}", std::process::id()));
std::fs::create_dir_all(&d).unwrap();
let script = d.join(format!("{name}.json"));
// Tests in this binary run concurrently. `sketch_imports_keep_to_no_system_fonts` also calls
// `families`, so a shared `families.json` could be truncated while another child reads it;
// an empty script is valid and makes the CLI exit successfully without printing result JSON.
let sequence = NEXT_SCRIPT.fetch_add(1, Ordering::Relaxed);
let script = d.join(format!("{name}-{sequence}.json"));
std::fs::write(&script, json!([step]).to_string()).unwrap();
let mut cmd = Command::new(env!("CARGO_BIN_EXE_figcraft-cli"));
cmd.arg("run").arg(&script).args(args);
@@ -20,8 +26,21 @@ fn run_one(name: &str, step: Value, args: &[&str], opt_out: bool) -> Value {
cmd.env_remove("FIGCRAFT_NO_SYSTEM_FONTS");
}
let out = cmd.output().unwrap();
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
let line: Value = serde_json::from_slice(&out.stdout).unwrap();
assert!(
out.status.success(),
"{name}: CLI status {:?}; stdout={:?}; stderr={}",
out.status.code(),
String::from_utf8_lossy(&out.stdout),
String::from_utf8_lossy(&out.stderr),
);
let line: Value = serde_json::from_slice(&out.stdout).unwrap_or_else(|error| {
panic!(
"{name} {:?}: CLI returned success without JSON: {error}; stdout={:?}; stderr={}",
args,
String::from_utf8_lossy(&out.stdout),
String::from_utf8_lossy(&out.stderr),
)
});
line["result"].clone()
}
+78
View File
@@ -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<bool> {
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<ParaList>, Vec<u32>, &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<u32> = (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)]
+38
View File
@@ -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:?}");
}
+59 -9
View File
@@ -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");
}
+1 -1
View File
@@ -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());
+7 -2
View File
@@ -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<CommandSpec> {
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<CommandSpec> {
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
),
+12 -3
View File
@@ -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<Value> {
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}))
}
+16 -10
View File
@@ -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<Value> {
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<Value> {
"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<Value> {
}
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 {
+6 -2
View File
@@ -168,9 +168,13 @@ pub(super) fn mind_map_cmd(s: &mut Session, p: &Value) -> Result<Value> {
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)?;
+2 -2
View File
@@ -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))
});
+3 -3
View File
@@ -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<f64> {
// 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())
}
+1 -1
View File
@@ -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;
+7 -2
View File
@@ -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.
+11 -3
View File
@@ -329,14 +329,22 @@ pub(super) fn paste_over(s: &mut Session, _p: &Value) -> Result<Value> {
let sel = s.selection();
let page = s.page()?;
let doc = s.doc()?;
let (parent, at) = match sel.first() {
let (parent, at, above) = match sel.first() {
Some(i) => {
let parent = doc.node(*i).and_then(|n| n.parent).unwrap_or(page);
(parent, doc.world_bounds(*i).map(|b| (b.x0, b.y0)))
(parent, doc.world_bounds(*i).map(|b| (b.x0, b.y0)), doc.index_in_parent(*i).map(|ix| ix + 1))
}
None => (page, None),
None => (page, None, None),
};
let ids = paste_into(s, parent, at)?;
if let Some(above) = above {
let doc = s.doc_mut()?;
for (k, i) in
ids.iter().filter(|i| doc.node(**i).is_some_and(|n| n.parent == Some(parent))).copied().collect::<Vec<_>>().into_iter().enumerate()
{
doc.reorder(i, above + k)?;
}
}
s.set_selection(ids.clone());
Ok(json!({"ids": ids}))
}
+24 -15
View File
@@ -283,25 +283,34 @@ pub fn specs() -> Vec<CommandSpec> {
spec!("view.zoomSelection", "Zoom to selection", "{}", false, |s, _| {
let ds = s.ds_mut()?;
if let Some(b) = ds.doc.bounds_of(&ds.selection) {
ds.view.fit(b, 256.0);
ds.view.fit_selection(b, 256.0);
}
Ok(json!({"zoom": ds.view.zoom}))
}),
spec!("view.set", "Set view", "{zoom?, cx?, cy? (page coordinate at the centre), vw?, vh? (viewport size)}", false, |s, p| {
let v = view(s)?;
if let Some(z) = num(p, "zoom") {
v.zoom = z.clamp(ViewState::MIN_ZOOM, ViewState::MAX_ZOOM);
spec!(
"view.set",
"Set view",
"{zoom?, cx?, cy? (page coordinate at the centre), vw?, vh? (viewport size), bottomInset? (height of the strip the bottom toolbar covers)}",
false,
|s, p| {
let v = view(s)?;
if let Some(z) = num(p, "zoom") {
v.zoom = z.clamp(ViewState::MIN_ZOOM, ViewState::MAX_ZOOM);
}
v.cx = num_or(p, "cx", v.cx);
v.cy = num_or(p, "cy", v.cy);
if let Some(w) = num(p, "vw") {
v.vw = w.clamp(10.0, 20000.0);
}
if let Some(h) = num(p, "vh") {
v.vh = h.clamp(10.0, 20000.0);
}
if let Some(i) = num(p, "bottomInset") {
v.bottom_inset = i.clamp(0.0, 20000.0);
}
Ok(serde_json::to_value(&*v).unwrap_or(Value::Null))
}
v.cx = num_or(p, "cx", v.cx);
v.cy = num_or(p, "cy", v.cy);
if let Some(w) = num(p, "vw") {
v.vw = w.clamp(10.0, 20000.0);
}
if let Some(h) = num(p, "vh") {
v.vh = h.clamp(10.0, 20000.0);
}
Ok(serde_json::to_value(&*v).unwrap_or(Value::Null))
}),
),
spec!(
"view.zoomAt",
"Zoom tool",
+59
View File
@@ -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();
+41 -10
View File
@@ -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<String> = 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) {
+1 -1
View File
@@ -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"));
+19
View File
@@ -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(['[', ']']))),
+3 -3
View File
@@ -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());
}
+16
View File
@@ -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) {
+18
View File
@@ -345,6 +345,24 @@ fn copy_paste_and_duplicate() {
assert_eq!(d["ids"].as_array().unwrap().len(), 1);
}
#[test]
fn paste_over_puts_the_copies_just_above_the_selected_layer() {
let mut s = sess();
let frame = id(&s.execute("frame.create", &json!({"x": 0, "y": 0, "width": 200, "height": 200})).unwrap());
let layer =
|s: &mut Session, x: f64| id(&s.execute("shape.rectangle", &json!({"x": x, "y": 10, "width": 10, "height": 10, "parent": frame})).unwrap());
let (a, b, c) = (layer(&mut s, 10.0), layer(&mut s, 30.0), layer(&mut s, 50.0));
let kids = |s: &Session| s.doc().unwrap().node(frame).unwrap().children.clone();
assert_eq!(kids(&s), vec![a, b, c]);
s.execute("edit.copy", &json!({"ids": [b, c]})).unwrap();
s.set_selection(vec![a]);
let pasted: Vec<NodeId> = s.execute("edit.pasteOver", &json!({})).unwrap()["ids"].as_array().unwrap().iter().filter_map(params::id_of).collect();
assert_eq!(pasted.len(), 2);
assert_eq!(kids(&s), vec![a, pasted[0], pasted[1], b, c], "in the selected layer's frame, just above it, in the copied order");
assert_eq!(s.doc().unwrap().world_bounds(pasted[0]).unwrap().x0, 10.0, "at the selected layer's position");
assert_eq!(s.selection(), pasted);
}
#[test]
fn boolean_and_flatten() {
let mut s = sess();
+26
View File
@@ -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.");
}
@@ -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.
+150 -2
View File
@@ -131,7 +131,7 @@ fn zoom_to_fit_selection_and_frames() {
// (command, selection before, zoom, centre, selection after, derivation)
let rows: Vec<(&str, Vec<NodeId>, f64, (f64, f64), Vec<NodeId>, &str)> = vec![
("view.zoomFit", vec![], fit(content), (470.0, 300.0), vec![], "Shift+1 fits everything on the page into the view"),
("view.zoomSelection", vec![r], fit(Rect::new(0.0, 0.0, 40.0, 40.0)), (920.0, 20.0), vec![r], "Shift+2 zooms to the selection"),
("view.zoomSelection", vec![r], (800.0 - 80.0) / 40.0, (920.0, 20.0), vec![r], "Shift+2 zooms to the selection, with a 40-point margin"),
(
"view.nextFrame",
vec![],
@@ -225,7 +225,7 @@ fn view_shortcuts_follow_the_documented_keys() {
(Platform::Other, "-", m(true, false, false, false), "view.zoomOut", "Shift and - zooms out"),
(Platform::Mac, "0", m(true, false, false, false), "view.zoom100", "Shift+0 zooms to 100%"),
(Platform::Other, "1", m(true, false, false, false), "view.zoomFit", "Shift+1 zooms to fit"),
(Platform::Mac, "2", m(true, false, false, false), "view.zoomSelection", "Shift+2 zooms to the selection"),
(Platform::Mac, "2", m(true, false, false, false), "view.zoomSelection", "Shift+2 zooms to the selection, with a 40-point margin"),
(Platform::Mac, "N", m(false, false, false, false), "view.nextFrame", "N zooms to the next frame"),
(Platform::Other, "N", m(true, false, false, false), "view.prevFrame", "Shift+N zooms to the previous frame"),
(Platform::Mac, "R", m(true, false, false, false), "view.rulers", "Shift+R shows and hides the rulers"),
@@ -771,3 +771,151 @@ fn view_toggles_are_kept_for_the_next_launch() {
}
assert!(!view.outlines && !view.outlines_selection && !view.proof_srgb, "{view:?}");
}
/// Select a fresh rectangle at the origin, set the view and run `cmd`; the rect's screen box is
/// returned as (left, top, right, bottom).
fn zoom_on(cmd: &str, inset: f64, w: f64, h: f64) -> (ViewState, (f64, f64, f64, f64)) {
let mut s = Session::new();
let r = rect(&mut s, 0.0, 0.0, w, h, None);
ex(&mut s, "view.set", json!({"vw": 1389, "vh": 903, "bottomInset": inset}));
ex(&mut s, "select.set", json!({"ids": [r]}));
ex(&mut s, cmd, json!({}));
let v = view(&s);
let (l, t) = v.page_to_screen(0.0, 0.0);
let (rr, b) = v.page_to_screen(w, h);
(v, (l, t, rr, b))
}
#[test]
fn zoom_to_selection_leaves_forty_points_and_clears_the_toolbar() {
// Measured in Figma's web app, 2026-11-09: 40 points on every side of the canvas above the toolbar.
let (v, (l, t, r, b)) = zoom_on("view.zoomSelection", 58.0, 100.0, 100.0);
assert!((v.zoom - 7.65).abs() < 0.01, "{}", v.zoom);
assert!((t - 40.0).abs() < 0.5 && (b - (845.0 - 40.0)).abs() < 0.5, "top {t}, bottom {b}");
assert!((l - (1389.0 - r)).abs() < 0.5, "left {l}, right {r}");
}
#[test]
fn zoom_to_selection_on_a_wide_layer_is_limited_by_the_width() {
let (v, (l, _, r, _)) = zoom_on("view.zoomSelection", 58.0, 1000.0, 200.0);
assert!((v.zoom - (1389.0 - 80.0) / 1000.0).abs() < 0.001, "{}", v.zoom);
assert!((l - 40.0).abs() < 0.5 && ((1389.0 - r) - 40.0).abs() < 0.5, "left {l}, right {r}");
}
#[test]
fn zoom_to_selection_without_a_toolbar_inset_uses_the_whole_height() {
let (v, _) = zoom_on("view.zoomSelection", 0.0, 100.0, 100.0);
assert!((v.zoom - (903.0 - 80.0) / 100.0).abs() < 1e-6, "{}", v.zoom);
let (_, top) = v.page_to_screen(0.0, 0.0);
let (_, bottom) = v.page_to_screen(100.0, 100.0);
assert!((top - 40.0).abs() < 1e-6 && (bottom - 863.0).abs() < 1e-6, "top {top}, bottom {bottom}");
}
#[test]
fn zoom_to_selection_in_a_short_canvas_still_ends_above_the_toolbar() {
// A canvas 130 points high with the 60-point toolbar strip leaves 70 above it: too short for
// 40 points a side, so the margin shrinks and the selection stays clear of the toolbar.
let mut s = Session::new();
let r = rect(&mut s, 0.0, 0.0, 100.0, 100.0, None);
ex(&mut s, "view.set", json!({"vw": 1389, "vh": 130, "bottomInset": 60}));
ex(&mut s, "select.set", json!({"ids": [r]}));
ex(&mut s, "view.zoomSelection", json!({}));
let v = view(&s);
let (_, top) = v.page_to_screen(0.0, 0.0);
let (_, bottom) = v.page_to_screen(100.0, 100.0);
assert!(top >= 0.0 && bottom <= 70.0 + 1e-6, "top {top}, bottom {bottom}");
assert!((top - (70.0 - bottom)).abs() < 1e-6, "centred above the toolbar: top {top}, bottom {bottom}");
// The margin shrinks to a quarter of the 70 points (17.5) and the zoom is the exact fit, not the floor.
assert!((v.zoom - 0.35).abs() < 1e-9, "{}", v.zoom);
assert!((top - 17.5).abs() < 1e-6 && (bottom - 52.5).abs() < 1e-6, "top {top}, bottom {bottom}");
}
/// A canvas narrower than 160 points keeps a quarter of its width on each side.
#[test]
fn zoom_to_selection_in_a_narrow_canvas_shrinks_the_side_margins() {
let mut s = Session::new();
let r = rect(&mut s, 0.0, 0.0, 100.0, 100.0, None);
ex(&mut s, "view.set", json!({"vw": 100, "vh": 903, "bottomInset": 0}));
ex(&mut s, "select.set", json!({"ids": [r]}));
ex(&mut s, "view.zoomSelection", json!({}));
let v = view(&s);
let (left, _) = v.page_to_screen(0.0, 0.0);
let (right, _) = v.page_to_screen(100.0, 100.0);
assert!((v.zoom - 0.5).abs() < 1e-9, "{}", v.zoom);
assert!((left - 25.0).abs() < 1e-6 && (right - 75.0).abs() < 1e-6, "left {left}, right {right}");
}
/// A view 1000 by 800 with a 100-point toolbar strip, for the edge cases of the fit.
fn strip_view() -> ViewState {
ViewState { vw: 1000.0, vh: 800.0, bottom_inset: 100.0, ..ViewState::default() }
}
#[test]
fn fitting_a_selection_survives_points_lines_extremes_and_junk() {
// A point: the zoom stays, and it lands in the middle of the area above the toolbar (y = 350).
let mut v = strip_view();
v.zoom = 2.0;
v.fit_selection(Rect::new(10.0, 20.0, 10.0, 20.0), 32.0);
assert_eq!(v.zoom, 2.0);
let (x, y) = v.page_to_screen(10.0, 20.0);
assert!((x - 500.0).abs() < 1e-9 && (y - 350.0).abs() < 1e-9, "{x}, {y}");
// A zero-width line is limited by its height, a zero-height one by its width.
let mut v = strip_view();
v.fit_selection(Rect::new(0.0, 0.0, 0.0, 100.0), 32.0);
assert!((v.zoom - (700.0 - 80.0) / 100.0).abs() < 1e-9, "{}", v.zoom);
let mut v = strip_view();
v.fit_selection(Rect::new(0.0, 0.0, 100.0, 0.0), 32.0);
assert!((v.zoom - (1000.0 - 80.0) / 100.0).abs() < 1e-9, "{}", v.zoom);
// A tiny one stops at the maximum zoom, a huge one at the minimum.
let mut v = strip_view();
v.fit_selection(Rect::new(0.0, 0.0, 0.001, 0.001), 32.0);
assert_eq!(v.zoom, 32.0);
v.fit_selection(Rect::new(0.0, 0.0, 1e12, 1e12), 32.0);
assert_eq!(v.zoom, ViewState::MIN_ZOOM);
// A rectangle with any coordinate that is not a finite number changes nothing.
for bad in [
Rect::new(0.0, f64::NAN, 10.0, 10.0),
Rect::new(0.0, 0.0, f64::INFINITY, 10.0),
Rect::new(0.0, 0.0, 10.0, f64::NAN),
Rect::new(f64::NAN, 0.0, 10.0, 10.0),
] {
let mut v = strip_view();
let before = (v.zoom, v.cx, v.cy);
v.fit_selection(bad, 32.0);
assert_eq!((v.zoom, v.cx, v.cy), before, "{bad:?}");
}
}
#[test]
fn the_bottom_inset_is_clamped_and_never_saved() {
let mut s = Session::new();
ex(&mut s, "view.set", json!({"bottomInset": -5}));
assert_eq!(view(&s).bottom_inset, 0.0);
ex(&mut s, "view.set", json!({"bottomInset": 1e12}));
assert_eq!(view(&s).bottom_inset, 20000.0);
// Larger than the viewport: the fit still leaves a sliver of canvas and a finite centre.
ex(&mut s, "view.set", json!({"vw": 400, "vh": 300, "bottomInset": 5000}));
let r = rect(&mut s, 0.0, 0.0, 10.0, 10.0, None);
ex(&mut s, "select.set", json!({"ids": [r]}));
ex(&mut s, "view.zoomSelection", json!({}));
let v = view(&s);
assert!(v.zoom.is_finite() && v.cx.is_finite() && v.cy.is_finite(), "{v:?}");
// It is not part of what the view saves.
let saved = serde_json::to_string(&v).unwrap();
assert!(!saved.to_lowercase().contains("inset"), "{saved}");
let back: ViewState = serde_json::from_str(&saved).unwrap();
assert_eq!(back.bottom_inset, 0.0);
}
#[test]
fn zoom_to_fit_is_unchanged() {
// Left alone on purpose: its 64-point margin is not measured against Figma yet.
let mut s = Session::new();
rect(&mut s, 0.0, 0.0, 100.0, 100.0, None);
ex(&mut s, "view.set", json!({"vw": 1389, "vh": 903, "bottomInset": 58}));
ex(&mut s, "view.zoomFit", json!({}));
let v = view(&s);
assert!((v.zoom - (903.0 - 128.0) / 100.0).abs() < 1e-6);
// No toolbar offset: the rectangle's own centre stays in the middle of the whole viewport.
assert_eq!((v.cx, v.cy), (50.0, 50.0));
}
+31
View File
@@ -12,6 +12,10 @@ pub struct ViewState {
/// Viewport size in logical pixels (set by the UI; used by zoom-to-fit).
pub vw: f64,
pub vh: f64,
/// Height in screen points of the strip the floating bottom toolbar covers (from its top edge to
/// the canvas's bottom edge); set by the UI every frame, 0 when it's hidden. Never saved.
#[serde(skip)]
pub bottom_inset: f64,
pub pixel_grid: bool,
pub layout_grids: bool,
pub rulers: bool,
@@ -51,6 +55,7 @@ impl Default for ViewState {
zoom: 1.0,
vw: 1200.0,
vh: 800.0,
bottom_inset: 0.0,
pixel_grid: true,
layout_grids: true,
rulers: false,
@@ -105,6 +110,32 @@ impl ViewState {
self.cx = r.center().x;
self.cy = r.center().y;
}
/// Fit a page rectangle for Zoom to selection: a 40 point margin on all four sides of the area
/// above the bottom toolbar (`vw` by `vh - bottom_inset`), centred in that area.
pub fn fit_selection(&mut self, r: figcraft_geom::Rect, max_zoom: f64) {
// A rectangle that isn't all finite numbers leaves the view as it is.
if ![r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite()) {
return;
}
let inset = if self.bottom_inset.is_finite() { self.bottom_inset.clamp(0.0, (self.vh - 1.0).max(0.0)) } else { 0.0 };
let area_h = (self.vh - inset).max(1.0);
// A point (nothing to fit) is centred in the area above the toolbar at the zoom it has.
if !(r.width() > 0.0 || r.height() > 0.0) {
self.cx = r.center().x;
self.cy = r.center().y + (self.vh - area_h) / 2.0 / self.zoom.max(1e-6);
return;
}
// 40 points as measured; a canvas too small for that keeps a quarter of its size on each
// side instead, so the selection still ends above the toolbar.
let mx = (self.vw / 4.0).clamp(0.0, 40.0);
let my = (area_h / 4.0).clamp(0.0, 40.0);
let zx = (self.vw - mx * 2.0).max(1.0) / r.width().max(1e-6);
let zy = (area_h - my * 2.0).max(1.0) / r.height().max(1e-6);
self.zoom = zx.min(zy).clamp(Self::MIN_ZOOM, max_zoom);
// The rect's centre lands at screen y = area_h / 2, the page centre `(vh - area_h) / 2` below it.
self.cx = r.center().x;
self.cy = r.center().y + (self.vh - area_h) / 2.0 / self.zoom;
}
/// The zoom from which the pixel grid shows (400%).
pub const PIXEL_GRID_ZOOM: f64 = 4.0;
/// Whether the pixel grid draws: it's on and the canvas is zoomed in to 400% or more.
+172 -1
View File
@@ -9,7 +9,7 @@ fn board_schema() -> Schema {
/// [`board_schema`] over another base schema.
fn board_schema_of(base: &str) -> Schema {
Schema::parse(&base.replace(
Schema::parse(&base.replace("enum ShapeWithTextType SQUARE ELLIPSE", "enum ShapeWithTextType SQUARE ROUNDED_RECTANGLE ELLIPSE DIAMOND TRIANGLE_UP TRIANGLE_DOWN PARALLELOGRAM_RIGHT PARALLELOGRAM_LEFT TRAPEZOID PENTAGON HEXAGON OCTAGON STAR PLUS ARROW_LEFT ARROW_RIGHT CHEVRON SPEECH_BUBBLE ENG_DATABASE DOCUMENT_SINGLE PREDEFINED_PROCESS MANUAL_INPUT INTERNAL_STORAGE ENG_QUEUE ENG_FILE ENG_FOLDER SHIELD DOCUMENT_MULTIPLE SUMMING_JUNCTION OR").replace(
"\nmessage Blob ",
", GeneratedData nodeGenerationData, GeneratedData derivedImmutableFrameData, string textAlignHorizontal, string textAlignVertical\nmessage GeneratedData NodeChange[] overrides, uint version\nmessage Blob ",
))
@@ -549,3 +549,174 @@ fn a_fig_sticky_stays_a_design_frame() {
assert!(frame.board.is_none());
assert_eq!(frame.children.len(), 3);
}
/// `board_node("SHAPE_WITH_TEXT")` of one FigJam kind.
fn shape_node(kind: &'static str) -> Kv<'static> {
let mut layer = board_node("SHAPE_WITH_TEXT");
set(&mut layer, "shapeWithTextType", e(kind));
layer
}
/// On a whiteboard a diamond is a native shape: FigCraft draws its outline and its text sits inside.
#[test]
fn a_jam_diamond_is_a_native_shape_drawn_by_figcraft() {
let (doc, warnings) = jam(shape_node("DIAMOND"));
let frame = named(&doc, "Board object");
assert_eq!(frame.board, Some(figcraft_doc::BoardItem::Shape { shape: figcraft_doc::BoardShape::Diamond }));
assert!(frame.fills.is_empty());
assert_eq!((frame.width, frame.height), (240.0, 240.0));
assert_eq!(frame.layout.as_ref().expect("shape auto layout").padding, [0.25 * 240.0; 4]);
assert_eq!(
(frame.child_layout.sizing_h, frame.child_layout.sizing_v),
(figcraft_doc::Sizing::Fixed, figcraft_doc::Sizing::Fixed),
"a fixed box, as a shape made here: it must not hug its text"
);
assert_eq!(frame.children.len(), 2, "the outline and the text: {warnings:?}");
let outline = doc.node(frame.children[0]).unwrap();
let NodeKind::Vector { network } = &outline.kind else { panic!("{:?}", outline.kind) };
assert_eq!(*network, figcraft_doc::VectorNetwork::from_path(&figcraft_doc::BoardShape::Diamond.path(240.0, 240.0)));
assert_eq!(outline.fills[0].solid_color().unwrap().to_rgba8(), [255, 191, 64, 255]);
assert!(outline.child_layout.absolute);
assert_eq!(outline.constraints.horizontal, figcraft_doc::HConstraint::Scale);
assert_eq!(outline.constraints.vertical, figcraft_doc::VConstraint::Scale);
let label = doc.node(frame.children[1]).unwrap().kind.text().unwrap();
assert_eq!(label.characters, "Olá\nIdea");
assert_eq!(label.align_h, figcraft_doc::TextAlignH::Center);
}
/// A shape past the importer's size cap is drawn at the capped size, so its outline stays inside
/// its frame.
#[test]
fn a_jam_shape_past_the_size_cap_draws_its_outline_at_the_cap() {
let mut layer = shape_node("DIAMOND");
set(&mut layer, "size", xy(2_000_000.0, 2_000_000.0));
let (doc, warnings) = jam(layer);
let frame = named(&doc, "Board object");
assert_eq!(frame.board, Some(figcraft_doc::BoardItem::Shape { shape: figcraft_doc::BoardShape::Diamond }), "{warnings:?}");
assert_eq!((frame.width, frame.height), (1e6, 1e6));
let outline = doc.node(frame.children[0]).unwrap();
let NodeKind::Vector { network } = &outline.kind else { panic!("{:?}", outline.kind) };
assert_eq!(*network, figcraft_doc::VectorNetwork::from_path(&figcraft_doc::BoardShape::Diamond.path(1e6, 1e6)));
}
/// 23 of FigJam's 30 shape kinds have a FigCraft outline; the other 7 stay frames and say which.
#[test]
fn every_figjam_shape_kind_maps_or_stays_a_frame() {
let kinds = [
"SQUARE",
"ROUNDED_RECTANGLE",
"ELLIPSE",
"DIAMOND",
"TRIANGLE_UP",
"TRIANGLE_DOWN",
"PARALLELOGRAM_RIGHT",
"PARALLELOGRAM_LEFT",
"TRAPEZOID",
"PENTAGON",
"HEXAGON",
"OCTAGON",
"STAR",
"PLUS",
"ARROW_LEFT",
"ARROW_RIGHT",
"CHEVRON",
"SPEECH_BUBBLE",
"ENG_DATABASE",
"DOCUMENT_SINGLE",
"PREDEFINED_PROCESS",
"MANUAL_INPUT",
"INTERNAL_STORAGE",
"ENG_QUEUE",
"ENG_FILE",
"ENG_FOLDER",
"SHIELD",
"DOCUMENT_MULTIPLE",
"SUMMING_JUNCTION",
"OR",
];
assert_eq!(kinds.len(), 30);
let mut mapped = 0;
for kind in kinds {
let table = super::map::board_shape(kind);
let (doc, warnings) = jam(shape_node(kind));
let frame = named(&doc, "Board object");
if let Some(shape) = table {
mapped += 1;
assert_eq!(frame.board, Some(figcraft_doc::BoardItem::Shape { shape }), "{kind}");
} else {
assert!(frame.board.is_none(), "{kind}");
assert!(warnings.iter().any(|w| w.contains(kind) && w.contains("no FigCraft outline")), "{kind}: {warnings:?}");
}
}
assert_eq!(mapped, 23);
}
/// A square keeps the paints and weight the file gave it, as read.
#[test]
fn a_square_keeps_its_paints_and_weight() {
let mut layer = shape_node("SQUARE");
let background =
record(0, vec![("fillPaints", arr(vec![solid(1.0, 1.0, 1.0)])), ("strokePaints", arr(vec![solid(0.5, 0.5, 0.5)])), ("strokeWeight", f(4.0))]);
set(&mut layer, "nodeGenerationData", o(vec![("overrides", arr(vec![background, record(1, text("Olá", 16.0))]))]));
let (doc, _) = jam(layer);
let frame = named(&doc, "Board object");
assert_eq!(frame.board, Some(figcraft_doc::BoardItem::Shape { shape: figcraft_doc::BoardShape::Rectangle }));
let outline = doc.node(frame.children[0]).unwrap();
assert_eq!(outline.fills[0].solid_color().unwrap().to_rgba8(), [255, 255, 255, 255]);
assert_eq!(outline.strokes[0].solid_color().unwrap().to_rgba8(), [128, 128, 128, 255]);
assert_eq!(outline.stroke.weight, 4.0);
}
/// A shape record that isn't complete keeps today's generated layers and no board item.
#[test]
fn a_damaged_shape_record_keeps_the_generated_layers() {
let mut cases = Vec::new();
let mut a = shape_node("DIAMOND");
set(&mut a, "derivedImmutableFrameData", o(vec![("version", u(2))]));
cases.push(a);
let mut b = shape_node("DIAMOND");
set(&mut b, "nodeGenerationData", o(vec![("overrides", arr(vec![record(1, text("Olá", 16.0))]))]));
cases.push(b);
let mut c = shape_node("DIAMOND");
let background = record(0, vec![("fillPaints", arr(vec![solid(1.0, 1.0, 1.0)]))]);
set(&mut c, "nodeGenerationData", o(vec![("overrides", arr(vec![background]))]));
cases.push(c);
for (i, layer) in cases.into_iter().enumerate() {
let (as_fig, fig_warnings) = imported(layer.clone());
let (doc, warnings) = jam(layer);
let frame = named(&doc, "Board object");
assert!(frame.board.is_none(), "case {i}");
assert_eq!(frame.children.len(), named(&as_fig, "Board object").children.len(), "case {i}: the generated layers, as in a .fig");
let sorted = |mut w: Vec<String>| {
w.sort();
w
};
assert_eq!(sorted(warnings), sorted(fig_warnings), "case {i}: today's warnings");
}
}
/// A shape with no text yet is still a native shape (an empty one).
#[test]
fn a_jam_shape_without_text_is_still_a_native_shape() {
let mut layer = shape_node("SQUARE");
let background = record(0, vec![("fillPaints", arr(vec![solid(1.0, 1.0, 1.0)]))]);
set(&mut layer, "nodeGenerationData", o(vec![("overrides", arr(vec![background, record(1, text("", 16.0))]))]));
let (doc, _) = jam(layer);
let frame = named(&doc, "Board object");
assert_eq!(frame.board, Some(figcraft_doc::BoardItem::Shape { shape: figcraft_doc::BoardShape::Rectangle }));
assert_eq!(doc.node(frame.children[1]).unwrap().kind.text().unwrap().characters, "");
}
/// Blank generated text must not hide text the outer node still carries (#1397): on a whiteboard
/// too, such a shape keeps the generated layers.
#[test]
fn a_jam_shape_whose_text_only_the_outer_node_carries_keeps_it() {
let mut layer = shape_node("SQUARE");
set(&mut layer, "textData", o(vec![("characters", s("Outer saved text"))]));
let background = record(0, vec![("fillPaints", arr(vec![solid(1.0, 1.0, 1.0)]))]);
set(&mut layer, "nodeGenerationData", o(vec![("overrides", arr(vec![background, record(1, text(" ", 24.0))]))]));
let (doc, _) = jam(layer);
let frame = named(&doc, "Board object");
assert!(frame.board.is_none(), "the generated layers keep the outer text");
assert!(frame.children.iter().filter_map(|id| doc.node(*id)?.kind.text()).any(|t| t.characters == "Outer saved text"));
}
+5 -3
View File
@@ -72,7 +72,7 @@ const AUX: u32 = 2;
pub(super) const SCHEMA: &str = "
enum MessageType JOIN_START=0 NODE_CHANGES=1
enum NodePhase CREATED=0 REMOVED=1
enum NodeType NONE=0 DOCUMENT=1 CANVAS=2 GROUP=3 FRAME=4 BOOLEAN_OPERATION=5 VECTOR=6 STAR=7 LINE=8 ELLIPSE=9 RECTANGLE=10 REGULAR_POLYGON=11 ROUNDED_RECTANGLE=12 TEXT=13 SLICE=14 SYMBOL=15 INSTANCE=16 SECTION=25 VARIABLE=28 VARIABLE_SET=31
enum NodeType NONE=0 DOCUMENT=1 CANVAS=2 GROUP=3 FRAME=4 BOOLEAN_OPERATION=5 VECTOR=6 STAR=7 LINE=8 ELLIPSE=9 RECTANGLE=10 REGULAR_POLYGON=11 ROUNDED_RECTANGLE=12 TEXT=13 SLICE=14 SYMBOL=15 INSTANCE=16 SECTION=25 VARIABLE=28 VARIABLE_SET=31 TEXT_PATH=41
enum BlendMode PASS_THROUGH=0 NORMAL=1 DARKEN=2 MULTIPLY=3 LINEAR_BURN=4 COLOR_BURN=5 LIGHTEN=6 SCREEN=7 LINEAR_DODGE=8 COLOR_DODGE=9 OVERLAY=10 SOFT_LIGHT=11 HARD_LIGHT=12 DIFFERENCE=13 EXCLUSION=14 HUE=15 SATURATION=16 COLOR=17 LUMINOSITY=18
enum PaintType SOLID=0 GRADIENT_LINEAR=1 GRADIENT_RADIAL=2 GRADIENT_ANGULAR=3 GRADIENT_DIAMOND=4 IMAGE=5
enum ImageScaleMode STRETCH=0 FIT=1 FILL=2 TILE=3
@@ -142,7 +142,8 @@ message StyleId GUID guid=1
message VariableID GUID guid=1
message VariableSetID GUID guid=1
message ColorStopVar Color color=1, VariableData colorVar=2, float position=3
message Paint PaintType type=1, Color color=2, float opacity=3, bool visible=4, BlendMode blendMode=5, ColorStop[] stops=6, Matrix transform=7, Image image=8, ImageScaleMode imageScaleMode=10, float rotation=11, float scale=12, VariableData colorVar=21, ColorStopVar[] stopsVar=23
message PaintFilterMessage float tint=1, float shadows=2, float highlights=3, float exposure=5, float temperature=7, float vibrance=8, float contrast=9
message Paint PaintType type=1, Color color=2, float opacity=3, bool visible=4, BlendMode blendMode=5, ColorStop[] stops=6, Matrix transform=7, Image image=8, ImageScaleMode imageScaleMode=10, float rotation=11, float scale=12, PaintFilterMessage paintFilter=14, VariableData colorVar=21, ColorStopVar[] stopsVar=23
message Effect EffectType type=1, Color color=2, Vector offset=3, float radius=4, bool visible=5, BlendMode blendMode=6, float spread=7, bool showShadowBehindNode=8, BlurOpType blurOpType=19, float startRadius=21, Vector startOffset=20, Vector endOffset=28, NoiseType noiseType=26, Vector noiseSize=22, float density=25, float opacity=27, Color secondaryColor=24, bool clipToShape=23, VariableData radiusVar=9, VariableData colorVar=10, VariableData spreadVar=11, VariableData xVar=12, VariableData yVar=13, VariableData startRadiusVar=45
struct FontName string family, string style, string postscript
struct Number float value, NumberUnits units
@@ -151,6 +152,7 @@ message TextLineData LineType lineType=1, int styleId=10, int indentationLevel=2
message TextData string characters=1, uint[] characterStyleIDs=2, NodeChange[] styleOverrideTable=3, TextLineData[] lines=12
message Path WindingRule windingRule=1, uint commandsBlob=2, uint styleID=3
message VectorData uint vectorNetworkBlob=1, Vector normalizedSize=2, NodeChange[] styleOverrideTable=3
message TextPathStart float tValue=1, bool forward=2
message ArcData float startingAngle=1, float endingAngle=2, float innerRadius=3
message OptionalVector Vector value=1
message LayoutGrid LayoutGridType type=1, Axis axis=2, bool visible=3, int numSections=4, float offset=5, float sectionSize=6, float gutterSize=7, Color color=8, LayoutGridPattern pattern=9, VariableData numSectionsVar=10, VariableData offsetVar=11, VariableData sectionSizeVar=12, VariableData gutterSizeVar=13
@@ -190,7 +192,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, Color prototypeBackgroundColor=141
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, TextPathStart textPathStart=432, 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
";
+16 -1
View File
@@ -74,6 +74,11 @@ impl<'d> Exporter<'d> {
}
_ => None,
};
// A text on a path is its own layer kind, written only when its path fields were built.
let on_path = match &n.kind {
NodeKind::Text(td) => self.text_path(n, td, nested),
_ => None,
};
let ty = match &n.kind {
NodeKind::Page { .. } | NodeKind::Frame | NodeKind::Group | NodeKind::ComponentSet { .. } => "FRAME",
NodeKind::Instance { .. } if main.is_none() => "FRAME",
@@ -84,6 +89,7 @@ impl<'d> Exporter<'d> {
NodeKind::Star { .. } => "STAR",
NodeKind::Line => "LINE",
NodeKind::Vector { .. } => "VECTOR",
NodeKind::Text(_) if on_path.is_some() => "TEXT_PATH",
NodeKind::Text(_) => "TEXT",
NodeKind::BooleanOp { .. } => "BOOLEAN_OPERATION",
NodeKind::Component { .. } => "SYMBOL",
@@ -107,7 +113,16 @@ impl<'d> Exporter<'d> {
NodeKind::Polygon { count } => f.push(("count", u(*count))),
NodeKind::Star { count, inner_ratio } => f.extend([("count", u(*count)), ("starInnerScale", fl(*inner_ratio))]),
NodeKind::Vector { network } => self.vector(n, network, f),
NodeKind::Text(td) => self.text(td, &n.fills, f),
NodeKind::Text(td) => {
self.text(td, &n.fills, f);
if let Some(path) = on_path {
// Text on a path has no box to align in: it is written as top, which is how it draws.
if let Some(entry) = f.iter_mut().find(|(k, _)| *k == "textAlignVertical") {
entry.1 = e("TOP");
}
f.extend(path);
}
}
NodeKind::BooleanOp { op } => {
let name = match op {
BoolOp::Union => "UNION",
+15 -2
View File
@@ -76,8 +76,21 @@ impl<'d> Exporter<'d> {
if let (ImageScaleMode::Crop, Some(c)) = (img.scale_mode, img.crop) {
f.push(("transform", matrix(Affine::new(c))));
}
if img.filters != Default::default() {
self.warn("image adjustments (exposure, contrast, …) were left out");
let x = img.filters.sanitized();
if !x.is_identity() {
// The file's tint is positive towards magenta, ours towards green; `0.0 -` keeps zero positive.
f.push((
"paintFilter",
o(vec![
("exposure", fl(f64::from(x.exposure))),
("contrast", fl(f64::from(x.contrast))),
("vibrance", fl(f64::from(x.saturation))),
("temperature", fl(f64::from(x.temperature))),
("tint", fl(0.0 - f64::from(x.tint))),
("highlights", fl(f64::from(x.highlights))),
("shadows", fl(f64::from(x.shadows))),
]),
));
}
}
PaintKind::Pattern(_) => {
+232 -3
View File
@@ -173,9 +173,6 @@ impl<'d> Exporter<'d> {
if styles.clone().any(|st| unsupported_decoration_look(st) || !st.variations.is_empty()) {
self.warn("text decoration looks and variable font settings were left out");
}
if td.path.is_some() {
self.warn("text on a path was written as plain text");
}
if !td.features.is_empty() {
self.warn("OpenType features were left out");
}
@@ -374,4 +371,236 @@ impl<'d> Exporter<'d> {
self.blobs.insert(bytes, i);
Some(i)
}
/// The fields of a text on a path (its start and its path as a vector network), or `None` when the text stays plain text
/// (with the warning that says why). `nested`: for an instance's override row, which follows its main's layer.
pub(super) fn text_path(&mut self, n: &Node, td: &TextData, nested: bool) -> Option<Fields> {
let doc = self.doc;
let own = text_path_net(td, n.width, n.height);
let main = if nested { n.source.and_then(|s| doc.node(s)) } else { None };
if let Some(main) = main {
let main_ok = matches!(&main.kind, NodeKind::Text(m) if text_path_net(m, main.width, main.height).is_ok());
if main_ok != own.is_ok() {
// An override can't take its layer off the main's path. So an instance text of
// more than one line, on a main that is on a path, stays on that path in the file:
// say so rather than the general mismatch (FigCraft's import reads it as plain text).
let lines = main_ok && matches!(own, Err(TEXT_PATH_LINES));
self.warn(if lines { TEXT_PATH_INSTANCE_LINES } else { TEXT_PATH_INSTANCE });
return None;
}
}
let tp = td.path.as_deref()?;
let made = match own {
Ok(made) => made,
Err(why) => {
self.warn(why);
return None;
}
};
let Some(index) = self.blob(network::encode(&made.net)) else {
self.warn(TEXT_PATH_CANT);
return None;
};
if made.later_parts {
self.warn(TEXT_PATH_PARTS);
}
Some(vec![
("textPathStart", o(vec![("tValue", fl(made.t)), ("forward", b(!tp.flip))])),
("vectorData", o(vec![("vectorNetworkBlob", u(index)), ("normalizedSize", xy(n.width, n.height))])),
])
}
}
/// The style id the format gives the segment a text on a path starts on.
const TEXT_PATH_MARK: u32 = 0x01ff_ffff;
const TEXT_PATH_LINES: &str = "text on a path with more than one line was written as plain text";
const TEXT_PATH_CANT: &str = "text on a path the format can't hold was written as plain text";
const TEXT_PATH_PARTS: &str = "the parts of a text's path after the first were left out";
const TEXT_PATH_INSTANCE: &str =
"text on a path in an instance but not in its main component, or the other way round, was written as the main has it";
const TEXT_PATH_INSTANCE_LINES: &str =
"an instance's text of more than one line stays on its main component's text path in the file, as an override can't take it off";
/// A text's path as the format holds it: one chain (or cycle) of a vector network with the
/// segment the text starts on marked, and the start as that segment's own parameter.
struct PathNet {
net: network::Network,
t: f64,
later_parts: bool,
}
/// The tangent-to-control-point cubic of a network segment, as the import reads it.
fn net_cubic(net: &network::Network, s: &network::Segment) -> Option<(figcraft_doc::geom::kurbo::CubicBez, bool)> {
use figcraft_doc::geom::kurbo::CubicBez;
let (a, b) = (net.vertices.get(s.a)?, net.vertices.get(s.b)?);
let line = s.ta == (0.0, 0.0) && s.tb == (0.0, 0.0);
let cubic = CubicBez::new((a.x, a.y), (a.x + s.ta.0, a.y + s.ta.1), (b.x + s.tb.0, b.y + s.tb.1), (b.x, b.y));
Some((cubic, line))
}
/// The length of a segment, as the import measures it.
fn net_length(net: &network::Network, s: &network::Segment) -> f64 {
use figcraft_doc::geom::kurbo::{Line, ParamCurveArclen};
match net_cubic(net, s) {
Some((c, true)) => Line::new(c.p0, c.p3).arclen(1e-9),
Some((c, false)) => c.arclen(1e-9),
None => 0.0,
}
}
/// The part of a path (a move and what follows it) as a chain of the network, and whether it is
/// a cycle; `None` without a segment longer than a billionth.
fn path_chain(part: &[figcraft_doc::geom::kurbo::PathEl]) -> Option<(network::Network, bool)> {
use figcraft_doc::geom::kurbo::{PathEl, Point, QuadBez};
let r = |x: f64| f64::from(finite(x) as f32);
let rp = |p: Point| (r(p.x), r(p.y));
let mut net = network::Network::default();
let mut closed = false;
let mut cur = (0.0, 0.0);
let add = |net: &mut network::Network, c1: Option<(f64, f64)>, c2: Option<(f64, f64)>, end: (f64, f64)| {
let Some(last) = net.vertices.last() else { return };
let (a, index) = ((last.x, last.y), net.vertices.len() - 1);
let tangent = |c: Option<(f64, f64)>, from: (f64, f64)| c.map_or((0.0, 0.0), |c| (r(c.0 - from.0), r(c.1 - from.1)));
let seg = network::Segment { style: 0, a: index, ta: tangent(c1, a), b: index + 1, tb: tangent(c2, end) };
net.vertices.push(network::Vertex { style: 0, x: end.0, y: end.1 });
if net_length(net, &seg) > 1e-9 {
net.segments.push(seg);
} else {
net.vertices.pop();
}
};
for el in part {
match el {
PathEl::MoveTo(p) => {
cur = rp(*p);
net.vertices.push(network::Vertex { style: 0, x: cur.0, y: cur.1 });
}
PathEl::LineTo(p) => {
cur = rp(*p);
add(&mut net, None, None, cur);
}
PathEl::QuadTo(c, p) => {
let q = QuadBez::new(Point::new(cur.0, cur.1), Point::new(r(c.x), r(c.y)), Point::new(r(p.x), r(p.y))).raise();
cur = rp(*p);
add(&mut net, Some((q.p1.x, q.p1.y)), Some((q.p2.x, q.p2.y)), cur);
}
PathEl::CurveTo(a, b, p) => {
cur = rp(*p);
// The control points are not rounded on their own: the format holds each as its offset from the end
// point, and taken from the point as read that is the offset the file had.
add(&mut net, Some((finite(a.x), finite(a.y))), Some((finite(b.x), finite(b.y))), cur);
}
PathEl::ClosePath => closed = true,
}
}
if net.segments.is_empty() {
return None;
}
let first = net.vertices.first().map(|v| (v.x, v.y))?;
let last = net.vertices.last().map(|v| (v.x, v.y))?;
let near = |p: (f64, f64), q: (f64, f64)| (p.0 - q.0).hypot(p.1 - q.1) <= 1e-6;
let mut cycle = false;
if closed || near(last, first) {
if near(last, first) {
// The last segment ends on the first vertex. A single segment stays an open chain of
// two vertices at one place: the import refuses a segment from a vertex to itself.
if net.segments.len() > 1 {
net.vertices.pop();
if let Some(s) = net.segments.last_mut() {
s.b = 0;
s.tb = (r(last.0 + s.tb.0 - first.0), r(last.1 + s.tb.1 - first.1));
cycle = true;
}
}
} else {
net.segments.push(network::Segment { style: 0, a: net.vertices.len() - 1, ta: (0.0, 0.0), b: 0, tb: (0.0, 0.0) });
cycle = true;
}
}
Some((net, cycle))
}
/// A text on a path as the format holds it, or the warning for why it stays plain text.
fn text_path_net(td: &TextData, w: f64, h: f64) -> Result<PathNet, &'static str> {
use figcraft_doc::geom::kurbo::{ParamCurveArclen, PathEl};
let Some(tp) = td.path.as_deref() else { return Err(TEXT_PATH_CANT) };
if td.characters.contains(['\n', '\r']) {
return Err(TEXT_PATH_LINES);
}
let path = tp.path();
let mut parts: Vec<Vec<PathEl>> = Vec::new();
for el in path.elements() {
if matches!(el, PathEl::MoveTo(_)) {
parts.push(Vec::new());
}
if let Some(part) = parts.last_mut() {
part.push(*el);
}
}
let mut chains = parts.iter().filter_map(|p| path_chain(p));
let (mut net, cycle) = chains.next().ok_or(TEXT_PATH_CANT)?;
let later_parts = chains.next().is_some();
if net.vertices.len() + net.segments.len() > MAX_NETWORK {
return Err(TEXT_PATH_CANT);
}
// The import scales the coordinates by size over normalized size, which are the same number
// here; an axis of no extent holds nothing but zeros.
let size = |x: f64| f64::from(finite(x) as f32);
for (extent, axis) in [(size(w), 0), (size(h), 1)] {
let at = |p: (f64, f64)| if axis == 0 { p.0 } else { p.1 };
let flat = net.vertices.iter().all(|v| at((v.x, v.y)) == 0.0) && net.segments.iter().all(|s| at(s.ta) == 0.0 && at(s.tb) == 0.0);
if extent < 0.0 || (extent <= 1e-9 && (extent != 0.0 || !flat)) {
return Err(TEXT_PATH_CANT);
}
}
let lengths: Vec<f64> = net.segments.iter().map(|s| net_length(&net, s)).collect();
let total: f64 = lengths.iter().sum();
if !total.is_finite() || total <= 1e-10 {
return Err(TEXT_PATH_CANT);
}
// The path the import builds from it must be one the text renderer can measure.
let mut shape = figcraft_doc::geom::BezPath::new();
for (i, s) in net.segments.iter().enumerate() {
let Some((c, line)) = net_cubic(&net, s) else { return Err(TEXT_PATH_CANT) };
if i == 0 {
shape.move_to(c.p0);
}
if line {
shape.line_to(c.p3);
} else {
shape.curve_to(c.p1, c.p2, c.p3);
}
}
if cycle {
shape.close_path();
}
let measured = figcraft_doc::geom::measure::polylines(&shape);
if measured.as_ref().and_then(|l| l.first()).is_none_or(|l| l.length() <= 1e-9) {
return Err(TEXT_PATH_CANT);
}
// The start, by length, as a parameter of the segment it falls on.
let start = tp.start();
let at = (if tp.flip { 1.0 - start } else { start }) * total;
let mut before = 0.0;
let mut k = lengths.len().saturating_sub(1);
for (i, len) in lengths.iter().enumerate() {
if before + len >= at {
k = i;
break;
}
before += len;
}
if k + 1 == lengths.len() && before + lengths[k] < at {
before = total - lengths[k];
}
let local = (at - before).clamp(0.0, lengths[k]);
let t = match net.segments.get(k).and_then(|s| net_cubic(&net, s)) {
Some((_, true)) | None => local / lengths[k],
Some((c, false)) => c.inv_arclen(local, 1e-9),
};
let t = if t.is_finite() { t.clamp(0.0, 1.0) } else { 0.0 };
if let Some(s) = net.segments.get_mut(k) {
s.style = TEXT_PATH_MARK;
}
Ok(PathNet { net, t, later_parts })
}
+81 -3
View File
@@ -16,8 +16,8 @@ fn image_filter_schema() -> Schema {
Schema::parse(&text).unwrap()
}
#[test]
fn image_filters_import_from_current_container_and_skip_ambiguous_data() {
/// A file with one image rectangle per filter case (current container, legacy, both, neutral, unknown fields).
fn image_filter_fixture() -> Vec<u8> {
let filter = |fields: Vec<(&'static str, Kv<'static>)>| o(fields);
let image_paint = |id: u64, name: &'static str, mut extra: Vec<(&'static str, Kv<'static>)>| {
let mut paint = vec![("type", e("IMAGE")), ("image", o(vec![("hash", Kv::Bytes(HASH.to_vec()))]))];
@@ -54,7 +54,12 @@ fn image_filters_import_from_current_container_and_skip_ambiguous_data() {
vec![("paintFilter", filter(vec![("brightness", f(0.4)), ("detail", f(-0.2)), ("vignette", f(0.3)), ("mystery", f(0.1))]))],
),
];
let bytes = zip_file(&canvas(&image_filter_schema(), &o(vec![("nodeChanges", arr(nodes))])));
zip_file(&canvas(&image_filter_schema(), &o(vec![("nodeChanges", arr(nodes))])))
}
#[test]
fn image_filters_import_from_current_container_and_skip_ambiguous_data() {
let bytes = image_filter_fixture();
let (doc, warnings) = import(&bytes, "ImageFilters.fig").unwrap();
let get = |name: &str| {
let node = doc.nodes().find(|node| node.name == name).unwrap();
@@ -102,3 +107,76 @@ fn warnings_naming_unknown_filter_fields_are_capped() {
let named = warnings.iter().filter(|w| w.contains("unsupported image filter")).count();
assert!((100..=crate::rest::MAX_WARNINGS).contains(&named), "{named} of {} warnings", warnings.len());
}
#[test]
fn image_adjustments_survive_a_fig_export() {
let (mut doc, _) = import(&image_filter_fixture(), "ImageFilters.fig").unwrap();
let filters_of = |doc: &figcraft_doc::Document, name: &str| {
let node = doc.nodes().find(|node| node.name == name).unwrap();
let figcraft_doc::color::PaintKind::Image(image) = &node.fills[0].kind else { panic!("{name} is not an image fill") };
image.filters
};
// Values a document can hold and the file can't: out of range, and not a number.
let ids: Vec<figcraft_doc::NodeId> = doc.ids().collect();
for id in ids {
let Some(node) = doc.node_mut(id) else { continue };
let name = node.name.clone();
let Some(figcraft_doc::color::PaintKind::Image(image)) = node.fills.first_mut().map(|p| &mut p.kind) else { continue };
match name.as_str() {
"Legacy" => image.filters.exposure = 5.0,
"Explicit neutral" => image.filters.contrast = f32::NAN,
_ => {}
}
}
let (bytes, warnings) = export::export(&doc, None).unwrap();
assert!(!warnings.iter().any(|w| w.contains("image adjustments")), "{warnings:?}");
let (back, _) = import(&bytes, "Back.fig").unwrap();
for name in ["Current", "Negative tint", "Neutral"] {
let (a, b) = (filters_of(&doc, name), filters_of(&back, name));
for (x, y) in [
(a.exposure, b.exposure),
(a.contrast, b.contrast),
(a.saturation, b.saturation),
(a.temperature, b.temperature),
(a.tint, b.tint),
(a.highlights, b.highlights),
(a.shadows, b.shadows),
] {
assert!((x - y).abs() < 1e-6, "{name}: {a:?} came back as {b:?}");
}
}
assert!(filters_of(&back, "Neutral").is_identity());
assert!(!filters_of(&back, "Current").is_identity());
// What is written: the file's names and signs.
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 fill_of = |name: &str| {
let nc = msg.get("nodeChanges").unwrap().list().iter().find(|nc| nc.get("name").and_then(Kv::str) == Some(name)).unwrap();
nc.get("fillPaints").unwrap().list()[0].clone()
};
let current = fill_of("Current");
let written = |paint: &Kv, field: &str| paint.get("paintFilter").and_then(|f| f.get(field)).and_then(Kv::f64);
assert!((written(&current, "vibrance").unwrap() + 0.4).abs() < 1e-6);
assert!((written(&current, "tint").unwrap() - 1.0).abs() < 1e-6);
assert!((written(&current, "shadows").unwrap() - 0.7).abs() < 1e-6);
assert!(fill_of("Neutral").get("paintFilter").is_none());
assert!((written(&fill_of("Legacy"), "exposure").unwrap() - 1.0).abs() < 1e-6, "written within the file's range");
assert!(fill_of("Explicit neutral").get("paintFilter").is_none(), "not a number is no adjustment");
let partly = fill_of("Negative tint");
for field in ["exposure", "contrast", "vibrance", "temperature", "tint", "highlights", "shadows"] {
assert!(written(&partly, field).is_some(), "{field} is written");
}
assert!((written(&partly, "tint").unwrap() + 1.0).abs() < 1e-6);
// The numbers the format uses.
let s = Schema::parse(export::SCHEMA).unwrap();
let def = |n: &str| s.defs.iter().find(|d| d.name == n).unwrap();
let id = |d: &str, f: &str| def(d).fields.iter().find(|x| x.name == f).unwrap().value;
assert_eq!(id("Paint", "paintFilter"), 14);
assert_eq!(
["tint", "shadows", "highlights", "exposure", "temperature", "vibrance", "contrast"].map(|f| id("PaintFilterMessage", f)),
[1, 2, 3, 5, 7, 8, 9]
);
}
+3
View File
@@ -28,6 +28,9 @@ mod proto;
mod text;
mod variables;
#[cfg(test)]
pub(super) use board::board_shape;
use component::OverrideScope;
#[cfg(test)]
use paint::paint;
+128
View File
@@ -5,6 +5,7 @@
use super::layer::{own_text, valid_size};
use super::paint::paint;
use super::{Affine, Kv, MAX_DEPTH, Mapper, Obj, Value, View, generated_record, json, num};
use figcraft_doc::BoardShape;
impl<'a> Mapper<'a> {
/// A sticky as a native board sticky: its frame (size, place, opacity and shadows as saved,
@@ -86,3 +87,130 @@ impl<'a> Mapper<'a> {
Some(kids)
}
}
impl<'a> Mapper<'a> {
/// A sticky or shape with text as a native board item, or `None` with the note that it is
/// a frame with its generated layers.
pub(super) fn native_board_item(&mut self, own: &str, o: &mut Obj, v: &View<'a>, rest_id: &str, depth: usize) -> Option<Vec<Value>> {
let native = if own == "STICKY" { self.native_sticky(o, v, rest_id, depth) } else { self.native_shape(o, v, rest_id, depth) };
if native.is_none() && own == "STICKY" {
self.warn("sticky layers import as frames with their text");
} else if native.is_none() {
self.warn("shape with text layers import as frames with their text");
}
native
}
}
impl<'a> Mapper<'a> {
/// A shape with text as a native board shape: an empty frame holding FigCraft's own outline
/// (the file's paints and weight) and the text, centred. `None` (nothing changed) when the kind
/// has no FigCraft outline or a generated record is damaged: then the caller keeps the
/// generated layers.
pub(super) fn native_shape(&mut self, o: &mut Obj, v: &View<'a>, rest_id: &str, depth: usize) -> Option<Vec<Value>> {
let kind = v.str("shapeWithTextType").unwrap_or("SQUARE");
let Some(shape) = board_shape(kind) else {
self.warn(format!("shape with text kind {} has no FigCraft outline; kept as a frame", crate::rest::props::clip_str(kind)));
return None;
};
if v.get("nodeGenerationData").is_none() || v.get("derivedImmutableFrameData").and_then(|d| num(d, "version")) != Some(1.0) {
return None;
}
let record = |id: u32| {
let (style, bounds) = (generated_record(v, "nodeGenerationData", id)?, generated_record(v, "derivedImmutableFrameData", id)?);
let view = View::of(style).with([(bounds, 1.0)]);
(valid_size(view.get("size")).is_some() && view.transform().is_some()).then_some(view)
};
let background = record(0)?;
let body = record(1)?;
// Blank generated text must not hide text the outer node still carries (#1397): the
// generated layers keep it.
if own_text(&body).is_none() && own_text(v).is_some() {
return None;
}
if depth >= MAX_DEPTH || self.count.saturating_add(2) > self.budget() {
return None;
}
let (w, h) = v.size().or_else(|| o.get("size").and_then(|s| Some((s.get("x")?.as_f64()?, s.get("y")?.as_f64()?))))?;
if !(w.is_finite() && h.is_finite() && w > 0.0 && h > 0.0) {
return None;
}
// The REST reader caps every size; the outline is drawn at the capped size too, so it
// stays inside its frame.
let (w, h) = (w.min(crate::rest::props::MAX_SIZE), h.min(crate::rest::props::MAX_SIZE));
// Everything is valid: build the outline from the record's paints, then the frame.
let mut outline = Obj::new();
outline.insert("id".into(), json!(format!("{rest_id};generated0")));
outline.insert("type".into(), json!("VECTOR"));
outline.insert("name".into(), json!("Outline"));
self.common(&mut outline, &background, "VECTOR", Affine::IDENTITY, None);
outline.insert("size".into(), json!({"x": w, "y": h}));
outline.insert("relativeTransform".into(), json!([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0]]));
outline.insert("vectorNetwork".into(), serde_json::to_value(figcraft_doc::VectorNetwork::from_path(&shape.path(w, h))).ok()?);
outline.insert("layoutPositioning".into(), json!("ABSOLUTE"));
outline.insert("constraints".into(), json!({"horizontal": "SCALE", "vertical": "SCALE"}));
outline.remove("cornerRadius");
let mut label = Obj::new();
label.insert("id".into(), json!(format!("{rest_id};generated1")));
label.insert("type".into(), json!("TEXT"));
label.insert("name".into(), json!(own_text(&body).map_or_else(|| "Text".to_string(), |c| c.chars().take(40).collect())));
self.common(&mut label, &body, "TEXT", Affine::IDENTITY, None);
self.text(&mut label, &body);
if let Some(Value::Object(style)) = label.get_mut("style") {
style.insert("textAutoResize".into(), json!("HEIGHT"));
style.insert("textAlignHorizontal".into(), json!("CENTER"));
}
label.insert("layoutSizingHorizontal".into(), json!("FILL"));
o.insert("fills".into(), json!([]));
o.insert("strokes".into(), json!([]));
o.insert("clipsContent".into(), json!(false));
o.remove("cornerRadius");
let [top, right, bottom, left] = shape.text_insets();
for (k, val) in [
("layoutMode", json!("VERTICAL")),
("primaryAxisAlignItems", json!("CENTER")),
("counterAxisAlignItems", json!("CENTER")),
("primaryAxisSizingMode", json!("FIXED")),
("counterAxisSizingMode", json!("FIXED")),
("paddingTop", json!(top * h)),
("paddingRight", json!(right * w)),
("paddingBottom", json!(bottom * h)),
("paddingLeft", json!(left * w)),
] {
o.insert(k.into(), val);
}
self.count += 2;
o.insert("board".into(), json!({"type": "shape", "shape": shape.id()}));
Some(vec![Value::Object(outline), Value::Object(label)])
}
}
/// FigJam's `shapeWithTextType` as the outline FigCraft draws for it; `None` for the kinds it has none for.
pub(in crate::fig) fn board_shape(kind: &str) -> Option<BoardShape> {
Some(match kind {
"SQUARE" => BoardShape::Rectangle,
"ROUNDED_RECTANGLE" => BoardShape::RoundedRectangle,
"ELLIPSE" => BoardShape::Ellipse,
"DIAMOND" => BoardShape::Diamond,
"TRIANGLE_UP" => BoardShape::Triangle,
"TRIANGLE_DOWN" => BoardShape::TriangleDown,
"PARALLELOGRAM_RIGHT" => BoardShape::ParallelogramRight,
"PARALLELOGRAM_LEFT" => BoardShape::ParallelogramLeft,
"TRAPEZOID" => BoardShape::Trapezoid,
"PENTAGON" => BoardShape::Pentagon,
"HEXAGON" => BoardShape::Hexagon,
"OCTAGON" => BoardShape::Octagon,
"STAR" => BoardShape::Star,
"PLUS" => BoardShape::Plus,
"ARROW_LEFT" => BoardShape::ArrowLeft,
"ARROW_RIGHT" => BoardShape::ArrowRight,
"CHEVRON" => BoardShape::Chevron,
"SPEECH_BUBBLE" => BoardShape::SpeechBubble,
"ENG_DATABASE" => BoardShape::Database,
"DOCUMENT_SINGLE" => BoardShape::Document,
"PREDEFINED_PROCESS" => BoardShape::PredefinedProcess,
"MANUAL_INPUT" => BoardShape::ManualInput,
"INTERNAL_STORAGE" => BoardShape::InternalStorage,
_ => return None,
})
}
+4 -7
View File
@@ -174,9 +174,9 @@ impl<'a> Mapper<'a> {
// A label without a snapshot: the connector becomes a frame holding its line and its label.
let connector_label = own == "CONNECTOR" && !connector_snapshot && self.connector_label_fits(&view, depth);
let ty = if connector_label { "FRAME" } else { Self::mapped_type(own, &view, connector_snapshot, connector_terminal, stand)? };
// A whiteboard's sticky says it imports as a frame only when it can't be a native one.
let native_sticky = self.board && own == "STICKY";
if let Some((_, what)) = stand.filter(|_| own != "TEXT_PATH" && !native_sticky) {
// A whiteboard's sticky or shape with text says it imports as a frame only when it can't be a native one.
let native_board = self.board && matches!(own, "STICKY" | "SHAPE_WITH_TEXT");
if let Some((_, what)) = stand.filter(|_| own != "TEXT_PATH" && !native_board) {
self.warn(format!("{} layers import as {what}", own.to_ascii_lowercase().replace('_', " ")));
}
if connector_snapshot {
@@ -264,7 +264,7 @@ impl<'a> Mapper<'a> {
});
kids.splice(0..0, connector_kids);
if stand.is_some_and(|s| s.0 == "FRAME") {
let native = if native_sticky { self.native_sticky(&mut o, &view, &rest_id, depth) } else { None };
let native = if native_board { self.native_board_item(own, &mut o, &view, &rest_id, depth) } else { None };
if let Some(native) = native {
kids.splice(0..0, native);
} else if let Some(snapshot) = self.board_snapshot(&mut o, &view, own, &rest_id, depth) {
@@ -273,9 +273,6 @@ impl<'a> Mapper<'a> {
kids.splice(0..0, self.shape_with_text(&mut o, &view, own, &rest_id));
kids.extend(self.inner_text(&o, &view, &rest_id, own == "STICKY"));
}
if native_sticky && !o.contains_key("board") {
self.warn("sticky layers import as frames with their text");
}
}
if !kids.is_empty() {
o.insert("children".into(), Value::Array(kids));
+20 -2
View File
@@ -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");
}
+380 -1
View File
@@ -83,8 +83,11 @@ fn blob() -> Vec<u8> {
}
fn canvas() -> Vec<u8> {
canvas_of(message(true))
}
fn canvas_of(message: Kv<'static>) -> Vec<u8> {
let schema = super::kiwi::Schema::parse(SCHEMA).unwrap();
let message = message(true);
let message = super::kiwi::encode::message(&schema, schema.find("Message").unwrap(), &message).unwrap();
let mut out = b"fig-kiwi\0\0\0\0".to_vec();
for raw in [super::kiwi::encode::schema(&schema), message] {
@@ -262,3 +265,379 @@ fn a_text_on_a_path_in_a_scaled_instance_has_its_path_scaled() {
assert_eq!(path_of("Main"), "M0,0 L100,0");
assert_eq!(path_of("Half"), "M0,0 L50,0");
}
// The `.fig` export writes text on a path.
use figcraft_doc::geom::kurbo::PathEl;
use figcraft_doc::{Document, NodeId, TextAlignV};
const W1: &str = "text on a path with more than one line was written as plain text";
const W2: &str = "text on a path the format can't hold was written as plain text";
const W3: &str = "the parts of a text's path after the first were left out";
const W4: &str = "text on a path in an instance but not in its main component, or the other way round, was written as the main has it";
const W4_LINES: &str =
"an instance's text of more than one line stays on its main component's text path in the file, as an override can't take it off";
const MARK: u32 = 0x01ff_ffff;
/// What an export wrote: its warnings, the layer records and the blobs.
struct Written {
warnings: Vec<String>,
records: Vec<Kv<'static>>,
blobs: Vec<Vec<u8>>,
}
impl Written {
fn of(doc: &Document) -> (Vec<u8>, Written) {
let (bytes, warnings) = super::export(doc, None).unwrap();
let archive = super::Archive::open(&bytes).unwrap();
let (schema, message) = super::decode_canvas(&archive.canvas).unwrap();
let schema: &'static super::kiwi::Schema = Box::leak(Box::new(schema));
let msg = schema.decode_message(schema.find("Message").unwrap(), &message).unwrap();
let records = msg.get("nodeChanges").unwrap().list().to_vec();
let blobs = msg
.get("blobs")
.map(|b| b.list().iter().filter_map(|x| x.get("bytes").and_then(Kv::bytes).map(<[u8]>::to_vec)).collect())
.unwrap_or_default();
(bytes, Written { warnings, records, blobs })
}
fn record(&self, name: &str) -> &Kv<'static> {
self.records.iter().find(|r| r.get("name").and_then(Kv::str) == Some(name)).unwrap_or_else(|| panic!("no record {name}"))
}
/// The network in the blob a record's `vectorData` names.
fn network(&self, record: &Kv<'static>) -> super::network::Network {
let i = record.get("vectorData").unwrap().get("vectorNetworkBlob").and_then(Kv::f64).unwrap() as usize;
super::network::decode(self.blobs.get(i).unwrap()).unwrap()
}
fn warned(&self, text: &str) -> bool {
self.warnings.iter().any(|w| w == text)
}
}
fn ty<'a>(r: &'a Kv<'static>) -> &'a str {
r.get("type").and_then(Kv::str).unwrap()
}
fn start_of(r: &Kv<'static>) -> (f64, bool) {
let s = r.get("textPathStart").unwrap_or_else(|| panic!("no textPathStart"));
(s.get("tValue").and_then(Kv::f64).unwrap(), s.get("forward").and_then(Kv::bool).unwrap())
}
/// A page holding one text per `(name, characters, d, start, flip, width, height)`.
fn doc_of(texts: &[(&str, &str, &str, f64, bool, f64, f64)]) -> Document {
let mut doc = Document::new("paths");
let page = doc.first_page().unwrap();
for (name, chars, d, start, flip, w, h) in texts {
let id = doc.create(page, NodeKind::Text(Default::default()), name, 0.0, 0.0, *w, *h).unwrap();
let td = doc.node_mut(id).unwrap().kind.text_mut().unwrap();
td.characters = (*chars).into();
if !d.is_empty() || !chars.is_empty() {
td.path = Some(Box::new(TextPath { d: (*d).into(), start: *start, flip: *flip }));
}
}
doc
}
fn text_of<'a>(doc: &'a Document, name: &str) -> &'a figcraft_doc::TextData {
let node = doc.nodes().find(|n| n.name == name).unwrap_or_else(|| panic!("no layer {name}"));
let NodeKind::Text(td) = &node.kind else { panic!("{name} is not text") };
td
}
fn elements(d: &str) -> Vec<(char, Vec<(f64, f64)>)> {
figcraft_doc::geom::svg_path(d)
.unwrap()
.elements()
.iter()
.map(|el| match el {
PathEl::MoveTo(p) => ('M', vec![(p.x, p.y)]),
PathEl::LineTo(p) => ('L', vec![(p.x, p.y)]),
PathEl::QuadTo(a, b) => ('Q', vec![(a.x, a.y), (b.x, b.y)]),
PathEl::CurveTo(a, b, c) => ('C', vec![(a.x, a.y), (b.x, b.y), (c.x, c.y)]),
PathEl::ClosePath => ('Z', vec![]),
})
.collect()
}
fn same_path(a: &str, b: &str) {
let (x, y) = (elements(a), elements(b));
assert_eq!(x.len(), y.len(), "{a} / {b}");
for ((ka, pa), (kb, pb)) in x.iter().zip(&y) {
assert_eq!(ka, kb, "{a} / {b}");
for (p, q) in pa.iter().zip(pb) {
assert!((p.0 - q.0).abs() < 1e-3 && (p.1 - q.1).abs() < 1e-3, "{a} / {b}");
}
}
}
fn no_text_path_warning(warnings: &[String]) {
assert!(!warnings.iter().any(|w| w.contains("text path") || w.contains("text off its path")), "{warnings:?}");
}
#[test]
fn a_text_on_a_path_survives_a_fig_export() {
let (doc, _) = super::import(&canvas(), "Text path").unwrap();
let (bytes, warnings) = super::export(&doc, None).unwrap();
assert!(!warnings.iter().any(|w| w.contains("text on a path")), "{warnings:?}");
let (_, w) = Written::of(&doc);
let r = w.record("alpha path");
assert_eq!(ty(r), "TEXT_PATH");
assert_eq!(start_of(r), (0.5, true));
assert_eq!(r.get("textAlignVertical").and_then(Kv::str), Some("TOP"));
let normalized = r.get("vectorData").unwrap().get("normalizedSize").unwrap();
let size = r.get("size").unwrap();
for k in ["x", "y"] {
assert_eq!(normalized.get(k).and_then(Kv::f64), size.get(k).and_then(Kv::f64));
}
assert_eq!((size.get("x").and_then(Kv::f64), size.get("y").and_then(Kv::f64)), (Some(100.0), Some(0.0)));
let net = w.network(r);
assert_eq!(net.vertices.iter().map(|v| (v.x, v.y)).collect::<Vec<_>>(), [(0.0, 0.0), (100.0, 0.0)]);
assert_eq!(net.segments.len(), 1);
assert_eq!((net.segments[0].style, net.segments[0].ta, net.segments[0].tb), (MARK, (0.0, 0.0), (0.0, 0.0)));
assert!(net.regions.is_empty());
let (back, import_warnings) = super::import(&bytes, "Back").unwrap();
no_text_path_warning(&import_warnings);
let td = text_of(&back, "alpha path");
assert_eq!(td.path.as_deref(), Some(&TextPath { d: "M0,0 L100,0".into(), start: 0.5, flip: false }));
assert_eq!(td.characters, "alpha");
assert_eq!((td.runs.len(), td.runs[0].start, td.runs[0].end), (1, 3, 5));
}
#[test]
fn the_start_is_written_by_length_from_either_side() {
const CURVE: &str = "M0,82.5 C70,-27.5 230,-27.5 300,82.5 C370,192.5 530,192.5 600,82.5";
let mut doc = doc_of(&[
("far", "alpha", CURVE, 0.7490379757, false, 600.0, 165.0),
("near", "alpha", CURVE, 0.004744078, false, 600.0, 165.0),
("flipped", "alpha", "M0,0 L600,0", 0.16013986, true, 600.0, 0.0),
]);
let page = doc.first_page().unwrap();
doc.create(page, NodeKind::Text(Default::default()), "plain", 0.0, 0.0, 50.0, 20.0).unwrap();
let (bytes, w) = Written::of(&doc);
let marked = |name: &str| -> (usize, f64, bool) {
let r = w.record(name);
let net = w.network(r);
let at: Vec<usize> = net.segments.iter().enumerate().filter(|(_, s)| s.style == MARK).map(|(i, _)| i).collect();
assert_eq!(at.len(), 1, "{name}");
let (t, forward) = start_of(r);
(at[0], t, forward)
};
let (i, t, forward) = marked("far");
assert_eq!((i, forward), (1, true));
assert!((t - 0.49800667).abs() < 1e-5, "{t}");
let (i, t, forward) = marked("near");
assert_eq!((i, forward), (0, true));
assert!((t - 0.0086954795).abs() < 1e-5, "{t}");
assert!((t - 0.009488156).abs() > 5e-4, "{t}");
let (i, t, forward) = marked("flipped");
assert_eq!((i, forward), (0, false));
assert!((t - 0.83986014).abs() < 1e-6, "{t}");
let plain = w.record("plain");
assert_eq!(ty(plain), "TEXT");
assert!(plain.get("textPathStart").is_none() && plain.get("vectorData").is_none());
let (back, _) = super::import(&bytes, "Back").unwrap();
for (name, d, start, flip) in
[("far", CURVE, 0.7490379757, false), ("near", CURVE, 0.004744078, false), ("flipped", "M0,0 L600,0", 0.16013986, true)]
{
let path = text_of(&back, name).path.as_deref().unwrap_or_else(|| panic!("{name} lost its path"));
same_path(&path.d, d);
assert!((path.start - start).abs() < 1e-6, "{name}: {}", path.start);
assert_eq!(path.flip, flip, "{name}");
}
}
#[test]
fn a_closed_path_is_written_as_a_cycle() {
let doc = doc_of(&[("square", "alpha", "M0,0 L100,0 L100,100 L0,100 Z", 0.3, false, 100.0, 100.0)]);
let (bytes, w) = Written::of(&doc);
let r = w.record("square");
let net = w.network(r);
assert_eq!((net.vertices.len(), net.segments.len()), (4, 4));
assert_eq!(net.segments.iter().map(|s| (s.a, s.b)).collect::<Vec<_>>(), [(0, 1), (1, 2), (2, 3), (3, 0)]);
assert_eq!(net.segments.iter().map(|s| s.style).collect::<Vec<_>>(), [0, MARK, 0, 0]);
assert!((start_of(r).0 - 0.2).abs() < 1e-6);
let come_back = |bytes: &[u8]| {
let (back, warnings) = super::import(bytes, "Back").unwrap();
no_text_path_warning(&warnings);
text_of(&back, "square").path.as_deref().unwrap().clone()
};
let once = come_back(&bytes);
same_path(&once.d, "M100,0 L100,100 L0,100 L0,0 L100,0 Z");
assert!((once.start - 0.05).abs() < 1e-6, "{}", once.start);
let (back, _) = super::import(&bytes, "Back").unwrap();
let (again, _) = super::export(&back, None).unwrap();
let twice = come_back(&again);
same_path(&twice.d, &once.d);
assert!((twice.start - once.start).abs() < 1e-6);
let open_end = doc_of(&[("tri", "alpha", "M0,0 L100,0 L100,100 L0,0", 0.5, false, 100.0, 100.0)]);
let (_, w) = Written::of(&open_end);
let net = w.network(w.record("tri"));
assert_eq!(net.vertices.len(), 3);
assert_eq!(net.segments.iter().map(|s| (s.a, s.b)).collect::<Vec<_>>(), [(0, 1), (1, 2), (2, 0)]);
}
#[test]
fn paths_the_format_cant_hold_fall_back_with_their_own_warning() {
let plain = |doc: &Document, warning: &str| {
let (bytes, w) = Written::of(doc);
assert!(w.warned(warning), "{:?}", w.warnings);
let r = w.record("t");
assert_eq!(ty(r), "TEXT");
assert!(r.get("textPathStart").is_none() && r.get("vectorData").is_none());
let (back, warnings) = super::import(&bytes, "Back").unwrap();
assert!(text_of(&back, "t").path.is_none());
assert!(!warnings.iter().any(|x| x.contains("text path")), "{warnings:?}");
};
plain(&doc_of(&[("t", "al\npha", "M0,0 L100,0", 0.5, false, 100.0, 0.0)]), W1);
plain(&doc_of(&[("t", "alpha", "M0,5 L100,5", 0.5, false, 100.0, 0.0)]), W2);
let mut empty = doc_of(&[("t", "alpha", "", 0.5, false, 100.0, 20.0)]);
let id = empty.nodes().find(|n| n.name == "t").unwrap().id;
empty.node_mut(id).unwrap().kind.text_mut().unwrap().path = Some(Box::new(TextPath { d: String::new(), start: 0.5, flip: false }));
plain(&empty, W2);
// Vertical alignment: written as top, still on its path.
let mut middle = doc_of(&[("t", "alpha", "M0,0 L100,0", 0.5, false, 100.0, 0.0)]);
let id = middle.nodes().find(|n| n.name == "t").unwrap().id;
middle.node_mut(id).unwrap().kind.text_mut().unwrap().align_v = TextAlignV::Middle;
let (bytes, w) = Written::of(&middle);
assert!(!w.warnings.iter().any(|x| x.contains("text on a path")), "{:?}", w.warnings);
assert_eq!(w.record("t").get("textAlignVertical").and_then(Kv::str), Some("TOP"));
let (back, _) = super::import(&bytes, "Back").unwrap();
assert!(text_of(&back, "t").path.is_some());
// Several parts: the first.
let (bytes, w) = Written::of(&doc_of(&[("t", "alpha", "M0,0 L100,0 M0,50 L100,50", 0.5, false, 100.0, 50.0)]));
assert!(w.warned(W3), "{:?}", w.warnings);
let (back, _) = super::import(&bytes, "Back").unwrap();
let path = text_of(&back, "t").path.as_deref().unwrap();
same_path(&path.d, "M0,0 L100,0");
assert!((path.start - 0.5).abs() < 1e-6);
// A zero-length segment is dropped.
let (bytes, w) = Written::of(&doc_of(&[("t", "alpha", "M0,0 L0,0 L100,0", 0.5, false, 100.0, 0.0)]));
assert!(!w.warnings.iter().any(|x| x.contains("text on a path")), "{:?}", w.warnings);
let (back, _) = super::import(&bytes, "Back").unwrap();
same_path(&text_of(&back, "t").path.as_deref().unwrap().d, "M0,0 L100,0");
// A closed path of one segment.
let (bytes, w) = Written::of(&doc_of(&[("t", "alpha", "M0,0 C100,-100 -100,-100 0,0 Z", 0.5, false, 100.0, 100.0)]));
assert!(!w.warnings.iter().any(|x| x.contains("text on a path")), "{:?}", w.warnings);
let (back, _) = super::import(&bytes, "Back").unwrap();
let els = elements(&text_of(&back, "t").path.as_deref().unwrap().d);
assert_eq!(els.first().map(|e| e.1[0]), Some((0.0, 0.0)));
let last = els.iter().rev().find(|e| e.0 != 'Z').unwrap();
assert_eq!(last.1.last().copied(), Some((0.0, 0.0)));
}
#[test]
fn an_instance_layer_on_a_path_survives_a_fig_export() {
let (doc, _) = super::import(&canvas_of(scaled_instance_message()), "Scaled path").unwrap();
let (bytes, warnings) = super::export(&doc, None).unwrap();
assert!(!warnings.iter().any(|w| w.contains("text on a path")), "{warnings:?}");
let (back, _) = super::import(&bytes, "Back").unwrap();
let path_of = |doc: &Document, parent: &str| {
let parent = doc.nodes().find(|n| n.name == parent).unwrap();
let node = doc.node(parent.children[0]).unwrap();
let NodeKind::Text(text) = &node.kind else { panic!("expected text") };
text.path.as_deref().map(|p| p.d.clone())
};
assert_eq!(path_of(&back, "Main").as_deref(), Some("M0,0 L100,0"));
assert_eq!(path_of(&back, "Half").as_deref(), Some("M0,0 L50,0"));
// A layer in an instance that isn't on a path where its main's layer is: it comes back on the main's path.
let off = |parent: &str| {
let mut doc = doc.clone();
let id: NodeId = doc.nodes().find(|n| n.name == parent).unwrap().children[0];
doc.node_mut(id).unwrap().kind.text_mut().unwrap().path = None;
doc
};
let (bytes, w) = Written::of(&off("Half"));
assert!(w.warned(W4), "{:?}", w.warnings);
let (back, _) = super::import(&bytes, "Back").unwrap();
assert_eq!(path_of(&back, "Half").as_deref(), Some("M0,0 L50,0"));
// An instance's text of two lines on a main that is on a path: the override can't leave the
// path, so the warning names that case, not the general mismatch.
let mut two = doc.clone();
let id: NodeId = two.nodes().find(|n| n.name == "Half").unwrap().children[0];
two.node_mut(id).unwrap().kind.text_mut().unwrap().characters = "al\npha".into();
let (_, w) = Written::of(&two);
assert!(w.warned(W4_LINES), "{:?}", w.warnings);
assert!(!w.warned(W4), "{:?}", w.warnings);
// The other way round: the main's layer is plain text, and so is the instance's.
let (bytes, w) = Written::of(&off("Main"));
assert!(w.warned(W4), "{:?}", w.warnings);
assert_eq!(ty(w.record("arc")), "TEXT");
let (back, _) = super::import(&bytes, "Back").unwrap();
assert_eq!((path_of(&back, "Main"), path_of(&back, "Half")), (None, None));
}
#[test]
fn the_schema_numbers_text_on_a_path() {
let s = super::kiwi::Schema::parse(super::export::SCHEMA).unwrap();
let def = |n: &str| s.defs.iter().find(|d| d.name == n).unwrap();
assert_eq!(def("NodeType").fields.iter().find(|x| x.name == "TEXT_PATH").map(|x| x.value), Some(41));
assert_eq!(def("NodeChange").fields.iter().find(|x| x.name == "textPathStart").map(|x| x.value), Some(432));
let start = def("TextPathStart");
assert!(matches!(start.kind, super::kiwi::Kind::Message));
let fields: Vec<_> = start.fields.iter().map(|x| (x.name.as_str(), x.value)).collect();
assert_eq!(fields, [("tValue", 1), ("forward", 2)]);
}
/// A text on a path of two curves whose coordinates 32-bit floats hold while their control points (a point plus its
/// tangent) need more digits, as the curves of a saved file do.
fn uneven_curve_canvas() -> Vec<u8> {
let mut blob = Vec::new();
let u32le = |out: &mut Vec<u8>, n: u32| out.extend_from_slice(&n.to_le_bytes());
let f32le = |out: &mut Vec<u8>, n: f32| out.extend_from_slice(&n.to_le_bytes());
for n in [3, 2, 0] {
u32le(&mut blob, n);
}
for (x, y) in [(0.1, 82.3), (300.7, 82.9), (600.3, 81.7)] {
u32le(&mut blob, 0);
f32le(&mut blob, x);
f32le(&mut blob, y);
}
for (style, a, ta, b, tb) in [(0, 0, (70.7, -110.3), 1, (-70.9, -110.1)), (MARK, 1, (70.3, 110.7), 2, (-70.1, 110.9))] {
u32le(&mut blob, style);
u32le(&mut blob, a);
f32le(&mut blob, ta.0);
f32le(&mut blob, ta.1);
u32le(&mut blob, b);
f32le(&mut blob, tb.0);
f32le(&mut blob, tb.1);
}
let identity = o(vec![("m00", f(1.0)), ("m01", f(0.0)), ("m02", f(0.0)), ("m10", f(0.0)), ("m11", f(1.0)), ("m12", f(0.0))]);
let text = node(
2,
Some(1),
"TEXT_PATH",
vec![
("name", s("curve")),
("size", point(600.5, 221.25)),
("transform", identity),
("textData", o(vec![("characters", s("alpha"))])),
("fontSize", f(24.0)),
("fontName", o(vec![("family", s("Inter")), ("style", s("Regular"))])),
("textPathStart", o(vec![("tValue", f(0.4)), ("forward", Kv::Bool(true))])),
("vectorData", o(vec![("vectorNetworkBlob", u(0)), ("normalizedSize", point(600.5, 221.25))])),
],
);
let nodes = vec![node(0, None, "DOCUMENT", vec![]), node(1, Some(0), "CANVAS", vec![]), text];
canvas_of(o(vec![("nodeChanges", a(nodes)), ("blobs", a(vec![o(vec![("bytes", Kv::Bytes(blob))])]))]))
}
#[test]
fn a_curve_read_from_a_file_is_written_back_as_it_was() {
let (doc, _) = super::import(&uneven_curve_canvas(), "Curve").unwrap();
let read = text_of(&doc, "curve").path.as_deref().unwrap().clone();
let (bytes, _) = super::export(&doc, None).unwrap();
let (back, warnings) = super::import(&bytes, "Back").unwrap();
no_text_path_warning(&warnings);
// The file holds a control point as its offset from the end point: taken from the point as read, it is the same offset.
assert_eq!(text_of(&back, "curve").path.as_deref(), Some(&read));
}
+1 -1
View File
@@ -13,7 +13,7 @@ use serde_json::Value;
use super::Ctx;
/// Largest width/height/stroke/radius/spacing value taken from the file.
pub(super) const MAX_SIZE: f64 = 1e6;
pub(crate) const MAX_SIZE: f64 = 1e6;
/// Largest coordinate taken from the file.
pub(super) const MAX_COORD: f64 = 1e7;
/// Most entries read from any one list (paints, effects, dashes, grids…).
+20 -1
View File
@@ -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<u32> = (0..t.paragraph_count()).map(|p| t.para_list(p).start_offset).collect();
assert_eq!(offsets, [4, 0, 0]);
}
+3
View File
@@ -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
+12 -2
View File
@@ -376,9 +376,19 @@ fn font_bytes_load_into_the_db() {
let families = load_font_bytes(f.bytes.to_vec());
assert_eq!(families.len(), 1);
assert!(families.iter().all(|f| has_family(f)));
let faces = db().read().unwrap().face_count();
// The global face count can grow here when another test finishes the concurrent system
// font scan. Count explicitly loaded faces from this family so the idempotency assertion
// stays isolated from unrelated installed fonts.
let loaded_faces = || {
let db = db().read().unwrap();
families
.iter()
.map(|family| db.faces.iter().filter(|face| face.loaded > 0 && face.family.eq_ignore_ascii_case(family)).count())
.collect::<Vec<_>>()
};
let faces = loaded_faces();
assert_eq!(load_font_bytes(f.bytes.to_vec()), families);
assert_eq!(db().read().unwrap().face_count(), faces);
assert_eq!(loaded_faces(), faces);
}
}
+10 -8
View File
@@ -1469,25 +1469,27 @@ pub(crate) fn list_markers(lists: &[ParaList]) -> Vec<String> {
// "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(),
}
})
+6
View File
@@ -1579,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"
@@ -1884,6 +1889,7 @@ name = "English"
"set-variable actions without a value were skipped" = "set-variable actions without a value were skipped"
"set-variable-mode actions on collections or modes that aren't in the variables JSON were skipped" = "set-variable-mode actions on collections or modes that aren't in the variables JSON were skipped"
"shape generated outline is missing or damaged; using its rectangle" = "shape generated outline is missing or damaged; using its rectangle"
"shape with text layers import as frames with their text" = "shape with text layers import as frames with their text"
"slot content assignment target is missing or is not slot content" = "slot content assignment target is missing or is not slot content"
"slot content assignment uses the empty GUID sentinel and was skipped" = "slot content assignment uses the empty GUID sentinel and was skipped"
"slot layers without a matching slot property were imported as frames" = "slot layers without a matching slot property were imported as frames"
+6
View File
@@ -379,6 +379,12 @@ impl FigApp {
let worker = self.worker.take();
let mut worker = worker.unwrap_or_else(|| render_worker::Worker::new(ctx.clone()));
canvas::show(self, ui, &mut worker);
// The strip the floating bottom toolbar covers, for Zoom to selection (0 when it's hidden).
let inset =
if !hidden && mobile.is_none() { f64::from(self.canvas.rect.max.y - toolbar::pill_rect(self.canvas.rect, 0.0).min.y) } else { 0.0 };
if let Ok(ds) = self.session.ds_mut() {
ds.view.bottom_inset = inset;
}
self.worker = Some(worker);
if !hidden && mobile.is_none() {
ui.scope_builder(egui::UiBuilder::new().id_salt("toolbar"), |ui| {
+26
View File
@@ -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");
}
+56 -2
View File
@@ -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<BoardShape>,
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<f64>,
connector: Option<Line>,
/// 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<Has> {
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.
+21 -1
View File
@@ -90,7 +90,14 @@ fn shift_digits_zoom() {
press(&mut u, Key::Num2, Modifiers::SHIFT);
assert!(zoom(&u) > fit, "Shift+2 fits the smaller selection");
let v = &u.app.session.ds().unwrap().view;
assert_eq!((v.cx, v.cy), (110.0, 40.0), "centred on it");
// Centred in the canvas above the bottom toolbar: the page centre sits half the toolbar's strip lower.
// The strip is the canvas's bottom edge less the pill's top, worked out here, not read back.
let strip = f64::from(u.app.canvas.rect.max.y - crate::toolbar::pill_rect(u.app.canvas.rect, 0.0).min.y);
assert!(strip > 20.0 && strip < 200.0, "the pill is a toolbar's height: {strip}");
assert!((v.bottom_inset - strip).abs() < 1e-3, "the app gives the engine the pill's strip: {} vs {strip}", v.bottom_inset);
let expect_cy = 40.0 + strip / 2.0 / v.zoom;
assert_eq!(v.cx, 110.0, "centred on it");
assert!((v.cy - expect_cy).abs() < 1e-9, "centred above the toolbar: {} vs {expect_cy}", v.cy);
// `+` and `-` step the zoom.
let z = zoom(&u);
press(&mut u, Key::Minus, Modifiers::NONE);
@@ -201,3 +208,16 @@ fn shortcuts_panel_does_not_show_on_the_home_screen() {
u.frame(vec![]);
assert!(!u.app.ui.shortcuts_panel, "the panel closes on the home screen");
}
/// The strip the bottom toolbar covers is given to the engine while the toolbar shows and is zero
/// when the interface is hidden.
#[test]
fn the_toolbar_strip_is_zero_when_the_interface_is_hidden() {
let (mut u, _, _) = setup();
u.frame(vec![]);
u.frame(vec![]);
assert!(u.app.session.ds().unwrap().view.bottom_inset > 0.0, "shown");
u.app.session.ds_mut().unwrap().view.ui_hidden = true;
u.frame(vec![]);
assert_eq!(u.app.session.ds().unwrap().view.bottom_inset, 0.0, "hidden");
}
+7 -5
View File
@@ -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 `.jam` file's shapes with text come in as native board shapes for the 23 kinds FigCraft draws, the other 7 as frames (#1808); 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) |
@@ -66,16 +66,18 @@ all end with the same geometry.
| Audio and huddles | missing | |
| AI features (summaries, sorting stickies, generating boards) | missing | |
| Grid on the page | done | the canvas render draws it after the page colour and before the layers (`figcraft_render::Dots`), so objects cover it. Dots by default, or lines, graph paper (a strong line every 2–12 cells over fainter ones, like Japanese section paper) or none; spacing (4–512), mark size and contrast are settings kept with the preferences (`board.grid`; Preferences ▸ Board grid). Zoomed out it thins out (dots and lines by halves, graph paper down to its strong lines) until the marks are at least 14 points apart (10 for lines), the marks the next step drops fading out first; dots stay about a point and a half across on screen (1 to 3 points), scaled by the size setting. Dark marks on a light page, light ones on a dark page, from the theme's ink; written straight into the image, no allocation per mark, a crossing of two lines blended once; never in exports. FigCraft's own settings: the incumbent's board grid has none |
| `.jam` import and export | **partial**: a `.jam` opens as a board, best effort (#1342): its stickies come in as native stickies (their colour, text and author kept; size as saved), its shapes with text as frames with their generated layers and its connectors as vectors, not yet as native board objects (an elbowed connector keeps the path it was saved with, #1910); no export | see [`file-format-parity.md`](file-format-parity.md) |
| `.jam` import and export | **partial**: a `.jam` opens as a board, best effort (#1342): its stickies come in as native stickies (their colour, text and author kept; size as saved), its shapes with text as native shapes for the 23 kinds FigCraft draws (the file's paints and weight kept, the outline FigCraft's own; the 7 others stay frames with their generated layers) and its connectors as vectors, not yet as native board objects (an elbowed connector keeps the path it was saved with, #1910); no export | see [`file-format-parity.md`](file-format-parity.md) |
## Revision history
| 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). |
| 2026-11-03 | minor | M12, #1919: as the quick create help says ("Click to select and create the next shape in that direction, or drag the preview to any location on your board"; "A new shape is created with a connector and its text field active"), a "+" beside the selected sticky or shape can be dragged: the preview follows the pointer and, let go on empty board, the next one is made there, centred on the pointer, and joined by a connector leaving by the handle's side and arriving by the side facing it (`board.addConnected` gains `at: [x, y]`, a point of the page placed in the parent's coordinates); let go on another sticky or shape, inside a section or frame too (`board::sticky_or_shape_at`), a connector joins the two instead (`board.connector`), that object outlined while the pointer is over it; let go off the canvas or over the toolbar, nothing, and the bar above the selection stays away meanwhile, as for any drag. The click is as before. A shape picker on drop and choosing the connector type are not done (the help doesn't describe them). Tests: `board_connect_tests` (the drag ones), engine `board_connected_tests::the_next_one_goes_where_it_is_dropped`. Numbers unchanged. |
| 2026-11-12 | minor | M9, #1808: `.jam` import: a FigJam shape with text comes in as a native board shape (`BoardItem::Shape`) for the 23 kinds FigCraft draws (square, rounded rectangle, ellipse, diamond, triangles, parallelograms, trapezoid, pentagon, hexagon, octagon, star, plus, arrows, chevron, speech bubble, database, document, predefined process, manual input, internal storage). The frame is empty and a fixed size, as a shape made here, with centred auto layout and the kind's text insets; it holds an `Outline` vector drawn by FigCraft (`BoardShape::path`, so FigJam's 3 pt corner on a square is lost, and `board.setShape` and resizing treat it as FigCraft's own) with the file's paints, weight and dashes as read, and the text, centred. The 7 kinds FigCraft has no outline for (ENG_QUEUE, ENG_FILE, ENG_FOLDER, SHIELD, DOCUMENT_MULTIPLE, SUMMING_JUNCTION, OR) stay frames with their generated layers and a warning naming the kind; so does a shape whose generated records are damaged, or whose generated text is blank while the outer layer still carries text (#1397), and the same shape in a `.fig`; a shape with no text at all is still native, with an empty text layer. Tests: `board_import_tests.rs` (six). Numbers unchanged. |
| 2026-11-10 | minor | M9, #1808: a `.jam` sticky imports as a native board sticky (`BoardItem::Sticky`): its frame keeps the saved size (240 pt, not FigCraft's 200), place, opacity and shadows, the saved colour is kept as it is (not snapped to the board colours), the note and the author line are its text layers, and it lays out like one made here (vertical, space between, hugging the height down to the saved size, the saved inset as padding). The importer reads a `board` field on the REST JSON (a FigCraft extension) for this; a sticky whose generated records are damaged, or the same sticky in a `.fig`, keeps the generated layers as before. Shapes, connectors, stamps and tables are unchanged; the note's text keeps the file's size until it is edited. Tests: `board_import_tests.rs` (native sticky, no author, damaged records, `.fig` unchanged), `import_regression_tests.rs` (the `board` field and junk values). Numbers unchanged. |
| 2026-11-04 | minor | M12, #1916: a connector end attached to a side starts 4 pt outside the border (`board_route::END_GAP`), as FigJam's do (the issue's screenshots: the line starts a few pixels outside, with a round cap), so the stroke never lies on the fill; elbows leaving one side share their first run along its normal, curves leave tangent to it and straight ones fan out from the same point; the `.jam` importer's routes, re-attached ends, path handles and labels follow the route's points; an end placed by hand with Cmd/Ctrl held keeps its exact point. Tests: `board_route_tests` (three). Numbers unchanged. |
| 2026-11-04 | patch | M6, #1910: a `.jam` elbowed connector saved with its path (FigJam's `connectorControlPoints`) keeps it on import: the points become the `ConnectorPath::Runs` a connector reshaped by hand has and the line is walked along them, so a connector drawn around a layer stays around it; one whose points don't make a path from its ends' sides is routed as before. Still a vector, not a native board object. Details in [`file-format-parity.md`](file-format-parity.md). |
+3 -2
View File
@@ -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 <file.figcraft> [--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 |
File diff suppressed because one or more lines are too long
+1 -1
View File
@@ -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,
+2 -2
View File
@@ -126,7 +126,7 @@ Breadth: does it exist. Ready: depth, correctness and fidelity for real projects
| Dimension | Weight | Ready | Hours | Evidence | Doc |
|---|---|---|---|---|---|
| Features (depth) | 35 | 63% | 28–67 (areas 1–13, 15, 16, 20) | The table above; core editor ~72% | this file |
| UI/UX fidelity | 15 | 58% | 40–60 | Look & feel compared side by side with UI3 (~65% by the builders); tool-by-tool interaction (modifiers while dragging, hover states, popovers) not yet compared (a cursor for every tool and modifier, number fields and panel widths built from the documentation, not compared); accessibility names and keyboard navigation landed | [ui-parity](ui-parity.md) |
| UI/UX fidelity | 15 | 58% | 40–60 | Look & feel compared side by side with UI3 (~65% by the builders); tool-by-tool interaction not yet compared (move and resize modifiers compared in Figma's web app on 2026-11-08 and matching, Ctrl/Cmd not measured; hover states and popovers not compared) (a cursor for every tool and modifier, number fields and panel widths built from the documentation, not compared); accessibility names and keyboard navigation landed | [ui-parity](ui-parity.md) |
| File formats | 12 | 61% | 5–10 | `.sketch` read (Sketch 48 and newer, best effort; 2026-10-21): live symbols, shared styles, Sketch 2025 frames and stacks, checked on three real files against Sketch's own renders (0.8–2% of pixels differ on average); `.fig` read, best effort, with editable vector networks and (2026-10-17) more fidelity, budgets for large files and an import report (tested on generated fixtures, not real files); layers copied from another design app paste the same way (tested only with clipboard HTML made from our own export), `.fig` write experimental (round trips through our own importer; written files open and draw in other software); REST JSON import, SVG in/out, PNG/JPG/WebP/PDF export solid, with a behaviour suite from the documentation | [file-format-parity](file-format-parity.md) |
| Collaboration | 10 | 13% | 52–104 | Local comments, version history and branches with review and merge; the multiplayer core (sync model, server ordering, client reconciliation, convergence tests) landed in #103, and live sessions (preview) co-edit a file hosted by a desktop app or kept on a self-hosted `figcraft-server` with edit and view links, joined from the app or the browser, with cursor chat and spotlight (`docs/collab-protocol.md`) | [collaboration-parity](collaboration-parity.md) |
| Stability | 8 | 55% | 20–40 | Never-crash lints, command guard with rollback, recovery copies, 963 tests incl. junk-parameter sweeps and a seeded retained-render walk; but two days old, one release (v0.2.0), no field reports, QA mostly on macOS | [gaps](gaps.md) |
@@ -196,7 +196,7 @@ and is left out as an area, but its effect on working with Figma users is counte
| Discount | Factor | Evidence |
|---|---|---|
| Interaction fidelity | ×0.90 | UI3 look compared side by side (~65% by the builders); no tool-by-tool comparison of cursors, modifier keys while dragging, snapping thresholds or popovers yet; Ctrl to suspend snapping on macOS missing ([ui-parity](ui-parity.md)) |
| Interaction fidelity | ×0.90 | UI3 look compared side by side (~65% by the builders); no tool-by-tool comparison of cursors, snapping thresholds or popovers yet (move and resize modifiers were compared in Figma's web app on 2026-11-08 and match, Ctrl/Cmd not measured); Ctrl to suspend snapping on macOS missing ([ui-parity](ui-parity.md)) |
| Stability on real machines | ×0.90 | Never-crash lints, command guard with rollback, recovery copies and 963 tests, but no field record at all: the repository is private, v0.2.0 has had no outside users or issue reports, CI tests run on Linux only and hands-on QA is on macOS. Harsher than VectorCraft's ×0.92 because there is no outside evidence either way |
| File exchange with Figma users | ×0.85 | A Figma designer's work lives in shared Figma files. FigCraft opens a `.fig` (best effort, not yet checked on real files) and writes an experimental one (written files open and draw in other software; effects, images and prototypes unchecked there); incoming work can come through the REST API JSON (one way, needs an access token), outgoing only as SVG, PDF, PNG or code. Teammates, reviewers and developers would all need FigCraft ([file-format-parity](file-format-parity.md), [collaboration-parity](collaboration-parity.md)) |
+10 -7
View File
File diff suppressed because one or more lines are too long