Merge main into #2304

This commit is contained in:
bflatastic committed 2026-11-13 23:18:03 +07:00
commit 956e9c1642
10 files changed
+322 -19

No files matched your search

+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"));
}
+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));
+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…).