mirror of
https://github.com/storytold/figcraft.git
synced 2026-11-19 16:46:45 +00:00
Merge main into #2331
This commit is contained in:
commit
953383fff8
63 files changed
+1169
-106
No files matched your search
@@ -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:?}");
|
||||
}
|
||||
@@ -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");
|
||||
}
|
||||
|
||||
@@ -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());
|
||||
|
||||
@@ -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
|
||||
),
|
||||
|
||||
@@ -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}))
|
||||
}
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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)?;
|
||||
|
||||
@@ -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))
|
||||
});
|
||||
|
||||
@@ -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())
|
||||
}
|
||||
|
||||
|
||||
@@ -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;
|
||||
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -124,9 +124,62 @@ pub fn move_handles(net: &mut VectorNetwork, hs: &[(usize, bool)], d: Vec2, inde
|
||||
}
|
||||
}
|
||||
|
||||
/// Each handle of a sharp point turned smooth by a mirror mode is this fraction of the length of its
|
||||
/// own segment. Measured in the incumbent (0.3905 and 0.390 at two angles): known to about 3 digits only.
|
||||
const MIRROR_SMOOTH_FACTOR: f64 = 0.3905;
|
||||
|
||||
/// Give a sharp point (two segments, no handles) the handles a mirror mode makes in the incumbent.
|
||||
/// Both lie on one line through the point, along `(B - A) / |BA|^2 + (C - B) / |BC|^2` (A, C: the far
|
||||
/// ends of the two segments). "Angle": each is [`MIRROR_SMOOTH_FACTOR`] x its own segment.
|
||||
/// "Angle and length": both are that factor x the shorter segment (medium confidence: the
|
||||
/// measurement could not separate this from other rules). Open-path ends, points with a handle
|
||||
/// already and coincident neighbours are left alone. Returns whether handles were made.
|
||||
fn smooth_sharp_point(net: &mut VectorNetwork, vi: usize, mode: HandleMirroring) -> bool {
|
||||
if mode == HandleMirroring::None {
|
||||
return false;
|
||||
}
|
||||
let inc = net.incident(vi);
|
||||
let [(s1, a1), (s2, a2)] = inc.as_slice() else { return false };
|
||||
let (Some(h1), Some(h2)) = (net.handle(*s1, *a1), net.handle(*s2, *a2)) else { return false };
|
||||
if tvec(h1).hypot() > 1e-9 || tvec(h2).hypot() > 1e-9 {
|
||||
return false;
|
||||
}
|
||||
let far = |s: usize, st: bool| net.segments.get(s).and_then(|x| net.vertices.get(if st { x.b } else { x.a })).map(|v| v.point());
|
||||
let (Some(b), Some(a), Some(c)) = (net.vertices.get(vi).map(|v| v.point()), far(*s1, *a1), far(*s2, *a2)) else { return false };
|
||||
let (ab, bc) = (b - a, c - b);
|
||||
let (la, lc) = (ab.hypot(), bc.hypot());
|
||||
if !(la > 1e-9 && lc > 1e-9 && la.is_finite() && lc.is_finite()) {
|
||||
return false;
|
||||
}
|
||||
let d = ab / (la * la) + bc / (lc * lc);
|
||||
if !finite(d) || d.hypot() < 1e-12 {
|
||||
return false;
|
||||
}
|
||||
let d = d.normalize();
|
||||
let (l_in, l_out) = if mode == HandleMirroring::AngleAndLength {
|
||||
let l = MIRROR_SMOOTH_FACTOR * la.min(lc);
|
||||
(l, l)
|
||||
} else {
|
||||
(MIRROR_SMOOTH_FACTOR * la, MIRROR_SMOOTH_FACTOR * lc)
|
||||
};
|
||||
let (in_h, out_h) = (-d * l_in, d * l_out);
|
||||
if !(finite(in_h) && finite(out_h)) {
|
||||
return false;
|
||||
}
|
||||
net.set_handle(*s1, *a1, (in_h.x, in_h.y));
|
||||
net.set_handle(*s2, *a2, (out_h.x, out_h.y));
|
||||
true
|
||||
}
|
||||
|
||||
/// Set the mirroring of vertices and make their handles agree with it.
|
||||
pub fn set_mirroring(net: &mut VectorNetwork, verts: &[usize], mode: HandleMirroring) {
|
||||
for &vi in verts {
|
||||
if smooth_sharp_point(net, vi, mode) {
|
||||
if let Some(v) = net.vertices.get_mut(vi) {
|
||||
v.mirror = Some(mode);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let inc = net.incident(vi);
|
||||
if let [(s1, a1), (s2, a2)] = inc.as_slice()
|
||||
&& let (Some(h1), Some(h2)) = (net.handle(*s1, *a1), net.handle(*s2, *a2))
|
||||
@@ -949,6 +1002,72 @@ mod tests {
|
||||
assert!((a + b).hypot() < 1e-9, "made symmetric: {a:?} {b:?}");
|
||||
}
|
||||
|
||||
/// An open path A, B, C (the measured triangle of #2110) with B sharp.
|
||||
fn triangle_path() -> VectorNetwork {
|
||||
VectorNetwork::from_points(&[Point::new(-250.0, -174.0), Point::new(117.0, -174.0), Point::new(-67.0, 194.0)], false)
|
||||
}
|
||||
|
||||
fn handles_at_b(n: &VectorNetwork) -> (Vec2, Vec2) {
|
||||
(tvec(n.segments[0].tb), tvec(n.segments[1].ta))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mirror_modes_smooth_a_sharp_point_as_measured() {
|
||||
// Mirror angle and length: both handles 0.3905 x the shorter segment (367), opposite.
|
||||
let mut n = triangle_path();
|
||||
set_mirroring(&mut n, &[1], HandleMirroring::AngleAndLength);
|
||||
let (i, o) = handles_at_b(&n);
|
||||
assert!((o - Vec2::new(86.24, 114.47)).hypot() < 0.1, "{o:?}");
|
||||
assert!((i + o).hypot() < 1e-9, "{i:?} {o:?}");
|
||||
assert!((o.hypot() - 143.3).abs() < 0.1, "{}", o.hypot());
|
||||
// Mirror angle: each handle 0.3905 x its own segment; still collinear.
|
||||
let mut n = triangle_path();
|
||||
set_mirroring(&mut n, &[1], HandleMirroring::Angle);
|
||||
let (i, o) = handles_at_b(&n);
|
||||
assert!((i - Vec2::new(-86.24, -114.47)).hypot() < 0.1, "{i:?}");
|
||||
assert!((o - Vec2::new(96.69, 128.33)).hypot() < 0.1, "{o:?}");
|
||||
assert!((i.x * o.y - i.y * o.x).abs() < 1e-6, "collinear");
|
||||
assert!((i.hypot() - 143.3).abs() < 0.1 && (o.hypot() - 160.7).abs() < 0.1);
|
||||
assert_eq!(n.mirroring(1), HandleMirroring::Angle);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mirror_modes_smooth_other_angles_and_several_points() {
|
||||
// A right angle at B with legs 100 and 50: d = (1,0)/100 + (0,1)/50, so the line leans to +y.
|
||||
let mut n = VectorNetwork::from_points(&[Point::new(0.0, 0.0), Point::new(100.0, 0.0), Point::new(100.0, 50.0)], false);
|
||||
set_mirroring(&mut n, &[1], HandleMirroring::Angle);
|
||||
let (i, o) = handles_at_b(&n);
|
||||
let want = Vec2::new(0.01, 0.02).normalize();
|
||||
assert!((o.normalize() - want).hypot() < 1e-9, "{o:?}");
|
||||
assert!((o.hypot() - 19.525).abs() < 1e-9 && (i.hypot() - 39.05).abs() < 1e-9, "{i:?} {o:?}");
|
||||
// Two sharp points of a closed square, both selected: both become smooth.
|
||||
let mut sq = square();
|
||||
set_mirroring(&mut sq, &[0, 2], HandleMirroring::AngleAndLength);
|
||||
for v in [0, 2] {
|
||||
assert!(sq.incident(v).iter().all(|(s, st)| sq.handle(*s, *st).is_some_and(|h| tvec(h).hypot() > 1.0)), "vertex {v}");
|
||||
assert_eq!(sq.mirroring(v), HandleMirroring::AngleAndLength);
|
||||
}
|
||||
assert!(sq.segments.iter().all(|s| tvec(s.ta).x.is_finite() && tvec(s.tb).y.is_finite()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mirror_modes_leave_unmeasured_points_alone() {
|
||||
// Open-path ends have only one segment.
|
||||
let mut n = open_line();
|
||||
set_mirroring(&mut n, &[0, 2], HandleMirroring::Angle);
|
||||
assert!(n.segments.iter().all(|s| s.is_straight()));
|
||||
// A zero-length neighbour: stays sharp, finite.
|
||||
let mut z = VectorNetwork::from_points(&[Point::new(5.0, 5.0), Point::new(5.0, 5.0), Point::new(60.0, 0.0)], false);
|
||||
set_mirroring(&mut z, &[1], HandleMirroring::AngleAndLength);
|
||||
assert!(z.segments.iter().all(|s| s.is_straight()));
|
||||
// One handle already: the old behaviour (the lone handle stays, the other mirrors it).
|
||||
let mut h = open_line();
|
||||
h.segments[1].ta = (10.0, 5.0);
|
||||
set_mirroring(&mut h, &[1], HandleMirroring::Angle);
|
||||
assert_eq!(h.segments[1].ta, (10.0, 5.0));
|
||||
assert_eq!(h.segments[0].tb, (-10.0, -5.0));
|
||||
}
|
||||
|
||||
fn loop_is_continuous(n: &VectorNetwork, lp: &[usize]) -> bool {
|
||||
let ends: Vec<(usize, usize)> = n
|
||||
.loop_walk(lp)
|
||||
|
||||
@@ -407,6 +407,24 @@ fn mirroring_position_and_join_commands() {
|
||||
assert!(s.execute("vector.join", &json!({"ids": [id]})).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mirror_mode_on_sharp_points_is_one_undo_step() {
|
||||
// #2110: a mirror mode turns sharp points smooth; the whole command undoes in one step.
|
||||
let mut s = Session::new();
|
||||
let r = ex(&mut s, "vector.create", json!({"points": [[-250, -174], [117, -174], [-67, 194]], "closed": false}));
|
||||
let id = crate::params::id_of(&r["id"]).unwrap();
|
||||
ex(&mut s, "vector.edit.begin", json!({"id": id}));
|
||||
ex(&mut s, "vector.edit.select", json!({"vertices": [1]}));
|
||||
ex(&mut s, "vector.edit.mirroring", json!({"mode": "angleAndLength"}));
|
||||
let n = net(&s, id);
|
||||
let (i, o) = (n.segments[0].tb, n.segments[1].ta);
|
||||
assert!((o.0 - 86.24).abs() < 0.1 && (o.1 - 114.47).abs() < 0.1, "{o:?}");
|
||||
assert!((i.0 + o.0).abs() < 1e-9 && (i.1 + o.1).abs() < 1e-9, "{i:?}");
|
||||
s.undo().unwrap();
|
||||
let n = net(&s, id);
|
||||
assert!(n.segments.iter().all(|x| x.is_straight()), "one undo restores the sharp point");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_point_dropped_on_another_merges_into_it() {
|
||||
// #401: an open path's end dragged onto its start closes the path at that point.
|
||||
|
||||
@@ -184,7 +184,10 @@ fn duplicate(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "variable.duplicate";
|
||||
let v = req_string(cmd, p, "variable")?;
|
||||
let doc = s.doc_mut()?;
|
||||
let pos = doc.variables.variables.iter().position(|x| x.id == v || x.name == v).ok_or_else(|| bad(cmd, "no such variable"))?;
|
||||
// An exact id first, then a name: an earlier variable named like another's id must not be the
|
||||
// one copied.
|
||||
let vars = &doc.variables.variables;
|
||||
let pos = vars.iter().position(|x| x.id == v).or_else(|| vars.iter().position(|x| x.name == v)).ok_or_else(|| bad(cmd, "no such variable"))?;
|
||||
let mut copy = doc.variables.variables.get(pos).cloned().ok_or_else(|| bad(cmd, "no such variable"))?;
|
||||
let taken = |n: &str| doc.variables.variables.iter().any(|x| x.collection == copy.collection && x.name == n);
|
||||
let name = (1..1000)
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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"));
|
||||
|
||||
@@ -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(['[', ']']))),
|
||||
|
||||
@@ -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());
|
||||
}
|
||||
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -47,6 +47,18 @@ fn rename_describe_scope_and_duplicate() {
|
||||
assert_eq!(vars.get(&id).unwrap().scopes, brand.scopes);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn duplicate_by_id_copies_that_variable_even_when_an_earlier_one_is_named_like_its_id() {
|
||||
let mut s = Session::new();
|
||||
tokens(&mut s);
|
||||
let brand = s.doc().unwrap().variables.get("brand").unwrap().id.clone();
|
||||
// The first variable in the list takes the later one's id as its name.
|
||||
ex(&mut s, "variable.update", json!({"variable": "space/sm", "name": brand.clone()}));
|
||||
let id = ex(&mut s, "variable.duplicate", json!({"variable": brand.clone()}))["id"].as_str().unwrap().to_string();
|
||||
let vars = &s.doc().unwrap().variables;
|
||||
assert_eq!(vars.get(&id).unwrap().name, "brand copy");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn modes_and_collections_rename_and_delete() {
|
||||
let mut s = Session::new();
|
||||
|
||||
@@ -215,9 +215,12 @@ fn corner_radius_mirroring_and_delete(s: &mut Session, a: NodeId, b: NodeId, atl
|
||||
|
||||
fn bend_select_all_pen_and_clicks(s: &mut Session, a: NodeId, b: NodeId) {
|
||||
// The Bend tool (held with Cmd/Ctrl) bends the segment under the pointer, in its own layer.
|
||||
// (The earlier mirroring step already turned the selected corners smooth, #2110.)
|
||||
let a_before = net(s, a).segments;
|
||||
let b_before = net(s, b).segments;
|
||||
drag(s, (250.0, 100.0), (250.0, 130.0), CMD);
|
||||
assert!(net(s, b).segments.iter().any(|sg| !sg.is_straight()), "the bend lands on the layer under the pointer");
|
||||
assert!(net(s, a).segments.iter().all(|sg| sg.is_straight()), "other layers keep their segments");
|
||||
assert!(net(s, b).segments != b_before, "the bend lands on the layer under the pointer");
|
||||
assert!(net(s, a).segments == a_before, "other layers keep their segments");
|
||||
// Select all takes every edited layer's points.
|
||||
let r = ex(s, "vector.edit.selectAll", json!({}));
|
||||
assert_eq!(r["count"], json!(8), "silent: select all takes the points of every edited layer (pinned)");
|
||||
|
||||
Reference in new issue
Block a user