mirror of
https://github.com/storytold/figcraft.git
synced 2026-11-17 23:58:24 +00:00
Merge main into #2291
This commit is contained in:
commit
35aa524f8a
53 files changed
+1923
-134
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.
|
||||
|
||||
@@ -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}))
|
||||
}
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
@@ -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.
|
||||
|
||||
Reference in new issue
Block a user