Merge remote-tracking branch 'origin/main' into HEAD

This commit is contained in:
bflatastic committed 2026-11-27 15:20:57 +07:00
commit d3782ee702
113 files changed
+8079 -392

No files matched your search

+2
View File
@@ -338,6 +338,8 @@ pub fn prop_default_value(d: &PropDef) -> Value {
}
}
#[cfg(test)]
mod nested_binding_tests;
#[cfg(test)]
mod rebase_source_tests;
@@ -35,6 +35,38 @@ pub(super) fn bindings_of<'a>(n: &'a Node, g: &'a str) -> impl Iterator<Item = (
n.bound.iter().filter(move |(k, _)| binding_group(k) == Some(g))
}
/// Whether `n` binds group `g` to other variables than `src` does. Keys are compared by what they
/// bind, so `fill` and `fills/0/color` are the same binding.
pub(super) fn bound_differently(n: &Node, src: &Node, g: &str) -> bool {
let canonical = |m: &Node| -> std::collections::BTreeSet<(String, String)> {
bindings_of(m, g)
.map(|(k, v)| {
let key = crate::cmd::lists::list_binding(k).map_or_else(|| k.clone(), |(l, i, f)| format!("{}/{i}/{f}", l.prefix()));
(key, v.clone())
})
.collect()
};
canonical(n) != canonical(src)
}
/// The property groups whose variable bindings differ between layer `n` and its main layer `src`:
/// overrides even where both resolve to the same value.
pub(super) fn rebound_groups(n: &Node, src: &Node) -> Vec<&'static str> {
let mut compared = Vec::new();
let mut out = Vec::new();
for k in n.bound.keys().chain(src.bound.keys()) {
let Some(g) = binding_group(k) else { continue };
if compared.contains(&g) {
continue;
}
compared.push(g);
if bound_differently(n, src, g) {
out.push(g);
}
}
out
}
/// Property groups that differ between two versions of a node.
pub fn diff_groups(a: &Node, b: &Node) -> Vec<&'static str> {
let mut out = Vec::new();
@@ -0,0 +1,51 @@
use serde_json::json;
use super::rebase_instance;
use super::tests::{button, copy_of, ex, fill, idv, node};
use crate::{NodeId, Session};
fn bound_shape_in_button() -> (Session, NodeId, NodeId, NodeId, NodeId) {
let mut s = Session::new();
let (_, shape, button, nested) = button(&mut s);
ex(&mut s, "variable.createCollection", json!({"name": "T"}));
ex(&mut s, "variable.create", json!({"collection": "T", "name": "ink", "type": "color", "value": "#111111"}));
let inner = copy_of(&s, nested, shape);
ex(&mut s, "variable.bind", json!({"ids": [inner.0], "field": "fill", "variable": "ink"}));
assert!(node(&s, inner).overrides.contains("fills"));
(s, shape, button, nested, inner)
}
#[test]
fn relinking_an_instance_keeps_a_binding_its_main_lacks_as_an_override() {
let (mut s, shape, button, nested, inner) = bound_shape_in_button();
let doc = s.ds_mut().unwrap().doc_mut();
doc.get_mut(inner).unwrap().overrides.clear();
rebase_instance(doc, nested);
assert!(node(&s, inner).overrides.contains("fills"), "the same colour from a variable the main doesn't bind");
ex(&mut s, "node.set", json!({"id": shape, "props": {"fill": "#FF0000"}}));
assert_eq!(fill(&s, inner), "111111", "an edit of the icon's main leaves the bound colour");
let placed = idv(&ex(&mut s, "instance.create", json!({"component": button, "x": 400, "y": 400})));
let copy = copy_of(&s, placed, inner);
assert_eq!(node(&s, copy).bound.values().collect::<Vec<_>>(), [&node(&s, inner).bound["fill"]]);
}
#[test]
fn hiding_and_showing_a_bound_fill_keeps_its_override() {
let (mut s, _, _, _, inner) = bound_shape_in_button();
ex(&mut s, "fill.set", json!({"ids": [inner.0], "index": 0, "visible": false}));
ex(&mut s, "fill.set", json!({"ids": [inner.0], "index": 0, "visible": true}));
let n = node(&s, inner);
assert!(n.bound.contains_key("fill"));
assert!(n.overrides.contains("fills"), "the binding still differs from the main's");
}
#[test]
fn a_top_level_instance_s_own_resizing_binding_is_not_an_override() {
let mut s = Session::new();
let (_, _, button, _) = button(&mut s);
let placed = idv(&ex(&mut s, "instance.create", json!({"component": button, "x": 400, "y": 400})));
let doc = s.ds_mut().unwrap().doc_mut();
doc.get_mut(placed).unwrap().bound.insert("minWidth".into(), "VariableID:1:1".into());
rebase_instance(doc, placed);
assert!(!node(&s, placed).overrides.contains("resizing"), "a top-level instance's resizing is its own");
}
+8 -3
View File
@@ -1,4 +1,4 @@
use super::diff::{binding_group, bindings_of, diff_groups, follow_boolean_defaults, geometry_derived, variable_groups};
use super::diff::{binding_group, bound_differently, diff_groups, follow_boolean_defaults, geometry_derived, rebound_groups, variable_groups};
use super::guard::{own_slot_content, relink_copy};
use super::instances::{copy_group, field_group, sync_instance};
use super::sync::insert_linked;
@@ -179,12 +179,17 @@ fn override_groups(doc: &Document, before: &Document, id: NodeId, n: &Node, b: &
// Binding another variable (or none) where the main binds one is an override.
for (k, _) in b.bound.iter().chain(n.bound.iter()) {
let Some(g) = binding_group(k) else { continue };
let rebound = b.bound.get(k) != n.bound.get(k) && !bindings_of(n, g).eq(bindings_of(src, g));
let rebound = b.bound.get(k) != n.bound.get(k) && bound_differently(n, src, g);
if rebound && !groups.contains(&g) {
groups.push(g);
}
}
cleared = raw.iter().filter(|g| !matches!(**g, "size" | "position") && !differs.contains(g) && n.overrides.contains(**g)).copied().collect();
let rebound = rebound_groups(n, src);
cleared = raw
.iter()
.filter(|g| !matches!(**g, "size" | "position") && !differs.contains(g) && !rebound.contains(g) && n.overrides.contains(**g))
.copied()
.collect();
if top_root {
cleared.retain(|g| !matches!(*g, "component" | "props"));
}
@@ -1,4 +1,4 @@
use super::diff::{diff_groups, variable_groups};
use super::diff::{diff_groups, rebound_groups, variable_groups};
use super::instances::{field_group, path_map};
use super::{BTreeMap, BTreeSet, Document, MAX_DEPTH, Node, NodeId, NodeKind, default_instance_name, holds_content};
@@ -216,6 +216,7 @@ pub fn rebase_instance_with(doc: &mut Document, inst: NodeId, mains: &mut MainPa
let mut bound: Vec<&str> = m.prop_refs.keys().map(|f| field_group(f)).collect();
bound.extend(variable_groups(n, m));
overrides.extend(value_groups(m, n).into_iter().filter(|g| !bound.contains(&g.as_str())));
overrides.extend(rebound_groups(n, m).into_iter().map(str::to_string));
if matches!((&m.kind, &n.kind), (NodeKind::Instance { component: a, .. }, NodeKind::Instance { component: b, .. }) if a != b) {
overrides.insert("component".into());
}
@@ -233,6 +234,7 @@ pub fn rebase_instance_with(doc: &mut Document, inst: NodeId, mains: &mut MainPa
let mut groups: Vec<String> = value_groups(m, n)
.into_iter()
.filter(|g| !matches!(g.as_str(), "name" | "exports" | "interactions") && !from_variables.contains(&g.as_str()))
.chain(rebound_groups(n, m).into_iter().map(str::to_string))
.filter(|g| placed_source.is_some() || !matches!(g.as_str(), "resizing" | "modes"))
.collect();
let named = if placed_source.is_some() { n.name != m.name } else { n.name != default_instance_name(doc, component) };
@@ -115,9 +115,65 @@ fn match_layers(
}
m.map.insert(*s, nid);
}
match_text_by_name(doc, inst, component, src, old, &mut m);
m
}
/// Main text layers nothing matched take the unmatched old text layer of the same name, when
/// exactly one of each has it: text typed into an instance stays when it switches to a variant that
/// nests the same text layer in other frames (its name path differs). Only layers outside nested
/// instances, which rebuild from their own mains. Names are counted over all those text layers,
/// matched ones too, so a name two layers share on either side never pairs by elimination.
fn match_text_by_name(
doc: &Document,
inst: NodeId,
component: NodeId,
src: &[NodeId],
old: &BTreeMap<NodeId, std::sync::Arc<Node>>,
m: &mut Matched,
) {
fn unique<K: Ord>(pairs: impl Iterator<Item = (K, NodeId)>) -> BTreeMap<K, NodeId> {
let mut seen: BTreeMap<K, Option<NodeId>> = BTreeMap::new();
for (k, id) in pairs {
seen.entry(k).and_modify(|e| *e = None).or_insert(Some(id));
}
seen.into_iter().filter_map(|(k, id)| Some((k, id?))).collect()
}
let text = |n: &Node| matches!(n.kind, NodeKind::Text(_));
let mut mains =
unique(src.iter().filter_map(|s| doc.node(*s)).filter(|s| text(s) && outside_nested(doc, s.id, component)).map(|s| (s.name.clone(), s.id)));
mains.retain(|_, s| m.fresh.contains(s));
if mains.is_empty() {
return;
}
let olds = unique(
old.iter()
.filter(|(id, o)| text(o) && outside_nested(doc, **id, inst))
.map(|(id, o)| (o.source.and_then(|s| doc.node(s)).map_or(&o.name, |s| &s.name).clone(), *id)),
);
for (name, s) in mains {
if let Some(o) = olds.get(&name).filter(|o| !m.used.contains(*o)) {
m.used.insert(*o);
m.map.insert(s, *o);
m.fresh.retain(|f| *f != s);
}
}
}
/// Whether layer `id` is below `root` with no instance between them.
fn outside_nested(doc: &Document, id: NodeId, root: NodeId) -> bool {
let mut cur = doc.node(id).and_then(|n| n.parent);
for _ in 0..=1_000_000 {
match cur.and_then(|c| doc.node(c)) {
Some(n) if n.id == root => return true,
Some(n) if matches!(n.kind, NodeKind::Instance { .. }) => return false,
Some(n) => cur = n.parent,
None => return false,
}
}
false
}
/// A rebuild's copies of the main's layers, pre-order (parents first).
struct Copies {
nodes: Vec<Node>,
@@ -282,6 +282,50 @@ fn variant_switch_keeps_compatible_overrides() {
healthy(&s);
}
#[test]
fn typed_text_stays_across_variants_that_nest_it_differently() {
let mut s = Session::new();
// Each variant's Label layers, by the frames holding them.
let shapes: [(&str, &[&[&str]]); 4] =
[("Kind=Plain", &[&["text"]]), ("Kind=Boxed", &[&["div", "text"]]), ("Kind=Twice", &[&["a"], &["b"]]), ("Kind=Moved", &[&["a"], &["c"]])];
let mut labels = Vec::new();
let mut variants = Vec::new();
for (k, (name, paths)) in shapes.into_iter().enumerate() {
let v = idv(&ex(&mut s, "frame.create", json!({"x": k as f64 * 300.0, "y": 0, "width": 200, "height": 60, "name": name})));
for frames in paths {
let mut parent = v;
for f in *frames {
parent = idv(&ex(&mut s, "frame.create", json!({"x": 0, "y": 0, "width": 200, "height": 60, "parent": parent, "name": f})));
}
labels.push(idv(&ex(&mut s, "text.create", json!({"text": "I agree", "x": 0, "y": 0, "parent": parent, "props": {"name": "Label"}}))));
}
variants.push(idv(&ex(&mut s, "component.create", json!({"ids": [v]}))));
}
ex(&mut s, "component.combineVariants", json!({"ids": variants.clone()}));
let i = idv(&ex(&mut s, "instance.create", json!({"component": variants[0], "x": 0, "y": 300})));
let typed = copy_of(&s, i, labels[0]);
ex(&mut s, "text.set", json!({"id": typed, "characters": "Architect"}));
ex(&mut s, "instance.setProperties", json!({"ids": [i], "properties": {"Kind": "Boxed"}}));
healthy(&s);
assert_eq!(chars(&s, copy_of(&s, i, labels[1])), "Architect", "one frame deeper, same name");
ex(&mut s, "instance.setProperties", json!({"ids": [i], "properties": {"Kind": "Plain"}}));
assert_eq!(chars(&s, copy_of(&s, i, labels[0])), "Architect", "and back");
ex(&mut s, "instance.setProperties", json!({"ids": [i], "properties": {"Kind": "Twice"}}));
healthy(&s);
let texts: Vec<String> = labels[2..4].iter().map(|l| chars(&s, copy_of(&s, i, *l))).collect();
assert_eq!(texts, ["I agree", "I agree"], "two layers of that name: neither is the one typed into");
// `a › Label` matches by path; the leftover `b › Label` and `c › Label` still share a name with it.
let typed = copy_of(&s, i, labels[3]);
ex(&mut s, "text.set", json!({"id": typed, "characters": "Architect"}));
ex(&mut s, "instance.setProperties", json!({"ids": [i], "properties": {"Kind": "Moved"}}));
healthy(&s);
let texts: Vec<String> = labels[4..].iter().map(|l| chars(&s, copy_of(&s, i, *l))).collect();
assert_eq!(texts, ["I agree", "I agree"], "a name two layers share doesn't pair what path matching left over");
}
#[test]
fn detach_keeps_the_look() {
let mut s = Session::new();
+40 -19
View File
@@ -1422,25 +1422,7 @@ pub fn adopt_pasted(doc: &mut Document, src: &Document, src_path: Option<&str>,
remote.extend(merge_components(doc, src, &BTreeMap::new(), Some(&foreign))?);
}
// Components `src` publishes: from its library.
if let Some(lib) = src.published.as_ref().filter(|l| own.as_deref() != Some(l.manifest.id.as_str())) {
let keys: Vec<NodeId> =
roots.iter().copied().filter(|r| !src.is_remote(*r) && lib.manifest.component(*r).is_some() && lib.doc.contains(*r)).collect();
if !keys.is_empty() {
remote.extend(import(doc, lib, &keys, false)?);
let m = &lib.manifest;
if doc.libraries.link(&m.id).is_none()
&& let Some(path) = src_path
{
doc.libraries_mut().enabled.push(LibraryLink {
id: m.id.clone(),
name: m.name.clone(),
path: path.to_string(),
version: m.version,
relative: String::new(),
});
}
}
}
remote.extend(from_published(doc, src, src_path, &roots)?);
// Point the pasted layers at those mains; what stays behind gets ids of its own.
let mut behind: BTreeMap<NodeId, NodeId> = BTreeMap::new();
let mut follow = |doc: &mut Document, id: NodeId| -> NodeId {
@@ -1479,6 +1461,45 @@ pub fn adopt_pasted(doc: &mut Document, src: &Document, src_path: Option<&str>,
Ok(())
}
/// `doc`'s copies of the components among `roots` (assets of `src`) that `src` publishes as a
/// library (`src`'s ids → `doc`'s), taken from that library, which gets enabled in `doc` when `src`
/// is saved at `src_path`. Empty when `src` publishes no library, or publishes `doc`'s own.
fn from_published(doc: &mut Document, src: &Document, src_path: Option<&str>, roots: &[NodeId]) -> Result<BTreeMap<NodeId, NodeId>> {
let own = doc.published.as_ref().map(|p| p.manifest.id.as_str());
let Some(lib) = src.published.as_ref().filter(|l| own != Some(l.manifest.id.as_str())) else { return Ok(BTreeMap::new()) };
let keys: Vec<NodeId> =
roots.iter().copied().filter(|r| !src.is_remote(*r) && lib.manifest.component(*r).is_some() && lib.doc.contains(*r)).collect();
if keys.is_empty() {
return Ok(BTreeMap::new());
}
let remote = import(doc, lib, &keys, false)?;
let m = &lib.manifest;
if doc.libraries.link(&m.id).is_none()
&& let Some(path) = src_path
{
doc.libraries_mut().enabled.push(LibraryLink {
id: m.id.clone(),
name: m.name.clone(),
path: path.to_string(),
version: m.version,
relative: String::new(),
});
}
Ok(remote)
}
/// The main in `doc` that pasting main component `main`, copied from another document `src`,
/// makes an instance of: `doc`'s copy of it from the library `src` publishes, as
/// [`adopt_pasted`] uses for instances. `None` when `src` doesn't offer it, so the paste copies
/// the main itself: also when the library holds it only because an offered component uses it.
pub fn published_main(doc: &mut Document, src: &Document, src_path: Option<&str>, main: NodeId) -> Result<Option<NodeId>> {
let Some(root) = asset_root(src, main) else { return Ok(None) };
if !src.published.as_ref().and_then(|l| l.manifest.component(root)).is_some_and(|a| a.published) {
return Ok(None);
}
Ok(from_published(doc, src, src_path, &[root])?.get(&main).copied())
}
/// Refuse edits of library copies, except by library commands (and imports of other files,
/// which bring their copies along).
pub fn check_read_only(cmd: &str, before: &Document, after: &Document) -> std::result::Result<(), String> {
+69
View File
@@ -695,3 +695,72 @@ fn library_links_follow_a_moved_folder() {
link_found(&mut s, &lid);
let _ = std::fs::remove_dir_all(&d);
}
/// A main component copied from a library file and pasted into another file is an instance of it
/// from that library, which gets enabled, as pasting an instance of it is; a variant is an instance
/// of that variant. A component the library doesn't offer pastes as a copy of itself, also one the
/// library holds because an offered component uses it.
#[test]
fn a_main_pasted_from_its_library_file_is_an_instance_of_it() {
let d = dir("paste-main");
let lib_path = path_str(&d.join("kit.figcraft"));
let mut s = Session::new();
let k = kit(&mut s);
let sizes: Vec<NodeId> = ["Size=S", "Size=L"]
.iter()
.enumerate()
.map(|(n, name)| {
idv(&ex(
&mut s,
"node.create",
json!({"type": "component", "name": name, "x": 600.0 + n as f64 * 100.0, "y": 0, "width": 40, "height": 20}),
))
})
.collect();
ex(&mut s, "component.combineVariants", json!({"ids": sizes.clone()}));
let spare = idv(&ex(&mut s, "frame.create", json!({"x": 300, "y": 300, "width": 10, "height": 10, "name": "_Spare"})));
let spare = idv(&ex(&mut s, "component.create", json!({"ids": [spare]})));
let icon = idv(&ex(&mut s, "frame.create", json!({"x": 400, "y": 300, "width": 10, "height": 10, "name": "_Icon"})));
let icon = idv(&ex(&mut s, "component.create", json!({"ids": [icon]})));
let badge = idv(&ex(&mut s, "frame.create", json!({"x": 500, "y": 300, "width": 30, "height": 30, "name": "Badge"})));
ex(&mut s, "instance.create", json!({"component": icon, "x": 5, "y": 5, "parent": badge}));
ex(&mut s, "component.create", json!({"ids": [badge]}));
let lid = publish_to(&mut s, &lib_path);
assert!(s.doc().unwrap().published.as_ref().unwrap().manifest.component(icon).is_some_and(|a| !a.published));
let at = s.doc().unwrap().world_bounds(k.button).unwrap();
ex(&mut s, "file.new", json!({"name": "Design"}));
let paste = |s: &mut Session, main: NodeId| -> NodeId {
ex(s, "doc.switch", json!({"index": 0}));
ex(s, "edit.copy", json!({"ids": [main]}));
ex(s, "doc.switch", json!({"index": 1}));
id_of(&ex(s, "edit.paste", json!({}))["ids"][0]).unwrap()
};
let main_of = |s: &Session, id: NodeId| match node(s, id).kind {
NodeKind::Instance { component, .. } => component,
k => panic!("not an instance: {k:?}"),
};
let button = paste(&mut s, k.button);
let doc = s.doc().unwrap();
assert_eq!(library_source(doc, main_of(&s, button)), Some((lid.as_str(), k.button)));
assert_eq!(doc.libraries.enabled.iter().map(|l| l.path.as_str()).collect::<Vec<_>>(), [lib_path.as_str()]);
assert_eq!(doc.world_bounds(button), Some(at), "where the main was");
let label = node(&s, button).children[0];
assert_eq!(chars(&s, label), "OK");
healthy(&s);
let copies = s.doc().unwrap().libraries.components.len();
let again = paste(&mut s, k.button);
assert_eq!(main_of(&s, again), main_of(&s, button), "the same library copy");
assert_eq!(s.doc().unwrap().libraries.components.len(), copies);
let large = paste(&mut s, sizes[1]);
assert_eq!(library_source(s.doc().unwrap(), main_of(&s, large)), Some((lid.as_str(), sizes[1])));
let card = paste(&mut s, k.card);
assert_eq!(library_source(s.doc().unwrap(), main_of(&s, card)), Some((lid.as_str(), k.card)));
let copy = paste(&mut s, spare);
assert!(matches!(node(&s, copy).kind, NodeKind::Component { .. }), "not offered by the library: a copy");
assert!(!s.doc().unwrap().is_remote(copy));
let icon_copy = paste(&mut s, icon);
assert!(matches!(node(&s, icon_copy).kind, NodeKind::Component { .. }), "only used by an offered component: a copy");
assert!(!s.doc().unwrap().is_remote(icon_copy));
healthy(&s);
let _ = std::fs::remove_dir_all(d);
}
+20 -1
View File
@@ -4,13 +4,32 @@
//! guide lines (with spacing labels) for the canvas to draw in red. Vector points also snap to
//! other points (see `vectoredit::snap`); landing on one shows a marker (a zero-length guide).
use figcraft_doc::{BoardItem, Document, NodeId};
use figcraft_doc::{BoardItem, Document, Node, NodeId, NodeKind};
use figcraft_geom::{Affine, Point, Rect, Vec2, transform_rect_bbox};
use serde::Serialize;
use crate::guides;
use crate::tools::UNMEASURED_SNAP_PX;
/// Whether `n` lands on whole pixels when dragged whatever Snap to pixel grid says: frames,
/// sections, components, component sets and instances. Figma's help: they "always snap to the
/// pixel grid, even if Snap to pixel grid is disabled". Other layers follow the setting.
pub fn always_on_pixels(n: &Node) -> bool {
n.kind.is_frame_like() || matches!(n.kind, NodeKind::Section { .. })
}
/// Put `id`'s position in its parent on whole pixels when its axes are its parent's: returns
/// whether it moved. A layer turned off its parent's axes keeps its position.
pub fn settle_on_pixels(doc: &mut Document, id: NodeId) -> crate::Result<bool> {
let n = doc.get_mut(id)?;
let [a, b, c, d, e, f] = n.transform.as_coeffs();
if !guides::axis_aligned(n.transform) || (e.round() == e && f.round() == f) {
return Ok(false);
}
n.transform = Affine::new([a, b, c, d, e.round(), f.round()]);
Ok(true)
}
/// 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.
#[derive(Clone, Debug, PartialEq, Serialize)]
+194 -2
View File
@@ -1,8 +1,9 @@
//! On-canvas text editing: caret, selection, typing. A whole editing session is one undo step.
use std::collections::BTreeMap;
use std::sync::{LazyLock, Mutex};
use figcraft_doc::{Document, ListStyle, NodeId, NodeKind, TextData};
use figcraft_doc::{Document, ImageData, ListStyle, NodeId, NodeKind, TextData};
use crate::{EngineError, Preedit, Result, Session, TextEdit};
@@ -401,6 +402,94 @@ pub fn list_indent(s: &mut Session, out: bool) -> Result<bool> {
Ok(text_of(s, id)? != before)
}
/// Whether Tab in text layer `id` moves between text layers: not in a board object's text (a
/// sticky's note, a table cell, a code block) or a widget's field, where it types as before.
fn tabs_between_texts(doc: &Document, id: NodeId) -> bool {
!in_board_object(doc, id) && crate::widgets::field_of(doc, id).is_none()
}
fn in_board_object(doc: &Document, id: NodeId) -> bool {
std::iter::once(id).chain(doc.ancestors(id)).any(|a| doc.node(a).is_some_and(|n| n.board.is_some()))
}
/// Tab (Shift+Tab: `back`) while editing text layer `from`: editing it ends as Escape ends it, and
/// the next (previous) text layer in reading order is edited with all of its text selected. At the
/// last (first) one nothing happens.
fn tab_to_next_text(s: &mut Session, from: NodeId, back: bool) -> Result<()> {
let order = reading_order(s.doc()?, tab_stops(s.doc()?, from));
let Some(at) = order.iter().position(|t| *t == from) else { return Ok(()) };
let next = if back { at.checked_sub(1).and_then(|i| order.get(i)) } else { order.get(at + 1) };
let Some(&next) = next else { return Ok(()) };
end(s)?;
begin(s, next, None, false)
}
/// The text layers Tab moves between from text layer `from`: those in the top-level layer holding
/// it (the frame or group on the page or in a section), at any depth and inside instances, that are
/// visible and unlocked with every layer around them and not in a board object; for a text on the
/// page or in a section itself, the text layers beside it there. `from` is always one of them.
fn tab_stops(doc: &Document, from: NodeId) -> Vec<NodeId> {
let is_section = |id: &NodeId| doc.node(*id).is_some_and(|n| matches!(n.kind, NodeKind::Section { .. }));
let chain: Vec<NodeId> = std::iter::once(from).chain(doc.ancestors(from)).collect();
let Some(page_at) = chain.iter().position(|c| doc.node(*c).is_some_and(|n| n.is_page())) else { return vec![from] };
let top = chain.get(..page_at).and_then(|below| below.iter().rev().copied().find(|c| !is_section(c)));
let stop = |n: &figcraft_doc::Node| n.visible && !n.locked && n.board.is_none();
let mut out = Vec::new();
match top {
Some(top) if top != from => {
let mut stack = vec![top];
let mut seen = 0usize;
while let Some(id) = stack.pop() {
seen += 1;
if seen > 1_000_000 {
break;
}
let Some(n) = doc.node(id).filter(|n| stop(n)) else { continue };
if matches!(n.kind, NodeKind::Text(_)) {
out.push(id);
}
stack.extend(n.children.iter().copied());
}
}
_ => {
let beside = doc.node(from).and_then(|n| n.parent).and_then(|p| doc.node(p)).map(|p| p.children.clone()).unwrap_or_default();
out.extend(beside.into_iter().filter(|c| doc.node(*c).is_some_and(|n| stop(n) && matches!(n.kind, NodeKind::Text(_)))));
}
}
if !out.contains(&from) {
out.push(from);
}
out
}
/// `ids` in reading order by their boxes on the page: rows top to bottom, each row left to right.
/// Rows are made from the top down: a layer joins the row of the topmost layer before it when the
/// two overlap vertically by more than nothing and by at least half the height of the shorter one,
/// else it starts the next row. Layers without bounds are left out.
fn reading_order(doc: &Document, ids: Vec<NodeId>) -> Vec<NodeId> {
let mut boxes: Vec<(NodeId, figcraft_geom::Rect)> = ids.into_iter().filter_map(|i| Some((i, doc.world_bounds(i)?))).collect();
boxes.sort_by(|a, b| a.1.y0.total_cmp(&b.1.y0).then(a.1.x0.total_cmp(&b.1.x0)));
let mut rows: Vec<Vec<(NodeId, figcraft_geom::Rect)>> = Vec::new();
for (id, b) in boxes {
let joins = |row: &Vec<(NodeId, figcraft_geom::Rect)>| {
row.first().is_some_and(|(_, a)| {
let overlap = a.y1.min(b.y1) - a.y0.max(b.y0);
overlap > 0.0 && overlap >= 0.5 * a.height().min(b.height())
})
};
match rows.last_mut() {
Some(row) if joins(row) => row.push((id, b)),
_ => rows.push(vec![(id, b)]),
}
}
rows.into_iter()
.flat_map(|mut row| {
row.sort_by(|a, b| a.1.x0.total_cmp(&b.1.x0).then(a.1.y0.total_cmp(&b.1.y0)));
row.into_iter().map(|(id, _)| id)
})
.collect()
}
/// The kind of word char `i` belongs to: 0 for spaces and punctuation, else its script, so a word
/// ends where the script changes (Han, hiragana, katakana and Hangul runs are words of their own in
/// text without spaces). Combining marks and voicing marks belong to the char before them.
@@ -459,7 +548,9 @@ fn word_right(chars: &[char], mut i: usize) -> usize {
i
}
/// A named key: Backspace, Delete, Left, Right, Up, Down, Home, End, Enter, Escape, SelectAll.
/// A named key: Backspace, Delete, Left, Right, Up, Down, Home, End, Enter, Tab, Escape, SelectAll.
/// Tab and Shift+Tab outside a list, a code block, a board object and a widget's field edit the
/// next or previous text layer ([`tab_to_next_text`]).
/// `word` moves or deletes by word, `line` to the line's ends (Up/Down, Home/End: the text's ends);
/// [`crate::keymap::text_motion`] gives them for the platform's keys. `ArrowLeft` etc. also work.
pub fn key(s: &mut Session, key: &str, shift: bool, word: bool, line: bool) -> Result<()> {
@@ -484,6 +575,7 @@ pub fn key(s: &mut Session, key: &str, shift: bool, word: bool, line: bool) -> R
match key {
"Escape" => return end(s),
"Enter" => return insert(s, "\n"),
"Tab" if !word && !line && tabs_between_texts(s.doc()?, te.id) => return tab_to_next_text(s, te.id, shift),
"Tab" => return insert(s, "\t"),
"Backspace" | "Delete" => {
return edit(s, |t, te| {
@@ -856,6 +948,106 @@ pub fn selected_text(s: &Session) -> Option<String> {
Some(t.characters.chars().skip(a).take(b.saturating_sub(a)).collect())
}
/// Copied characters with their formatting, for a paste into a text edit that keeps it.
#[derive(Clone, Debug, PartialEq)]
pub struct RichText {
pub text: String,
/// Styled runs as `(from, to, style)` char ranges of `text`. Each style carries its fills,
/// the layer's own where the run had none, so the characters keep their colour elsewhere.
pub spans: Vec<(usize, usize, figcraft_doc::TextStyle)>,
/// The data of the images the runs' fills use, so they resolve in another file.
pub images: BTreeMap<String, ImageData>,
}
/// The selected characters while editing, with their formatting (for copy).
pub fn selected_rich_text(s: &Session) -> Option<RichText> {
let (id, a, b) = selected_range(s)?;
rich_text_of(s.doc().ok()?, id, a, b)
}
/// The characters of the text layers `ids`, one per line, with their formatting; None when one of
/// them isn't a text layer or there are no characters.
pub fn layers_rich_text(doc: &Document, ids: &[NodeId]) -> Option<RichText> {
let mut joined = RichText { text: String::new(), spans: Vec::new(), images: BTreeMap::new() };
let mut offset = 0;
for (i, id) in ids.iter().enumerate() {
let layer = rich_text_of(doc, *id, 0, usize::MAX)?;
if i > 0 {
joined.text.push('\n');
offset += 1;
}
joined.text.push_str(&layer.text);
joined.spans.extend(layer.spans.into_iter().map(|(from, to, style)| (from + offset, to + offset, style)));
joined.images.extend(layer.images);
offset += layer.text.chars().count();
}
(!joined.text.is_empty()).then_some(joined)
}
/// Chars `a..b` of the text layer `id` (`b` past the end means to the end), with their formatting.
fn rich_text_of(doc: &Document, id: NodeId, a: usize, b: usize) -> Option<RichText> {
let n = doc.node(id)?;
let t = n.kind.text()?;
let b = b.min(t.char_count());
let text: String = t.characters.chars().skip(a).take(b.saturating_sub(a)).collect();
let spans: Vec<(usize, usize, figcraft_doc::TextStyle)> = t
.spans()
.into_iter()
.filter(|(from, to, _)| *to > a && *from < b)
.map(|(from, to, style)| {
let mut style = style.clone();
style.fills.get_or_insert_with(|| n.fills.clone());
(from.max(a) - a, to.min(b) - a, style)
})
.collect();
let mut images = BTreeMap::new();
for paint in spans.iter().flat_map(|(_, _, style)| style.fills.iter().flatten()) {
if let figcraft_color::PaintKind::Image(img) = &paint.kind
&& let Some(d) = doc.images.get(&img.image)
{
images.insert(img.image.clone(), d.clone());
}
}
Some(RichText { text, spans, images })
}
/// Replace the selection in the text edit with `rich`, keeping its formatting. A link to a style
/// this file doesn't have is dropped, a fill equal to the layer's is left to the layer, and the
/// copied image data is added where this file lacks the key, as a pasted layer's is.
pub fn insert_rich(s: &mut Session, rich: &RichText) -> Result<()> {
if s.ds()?.text_edit.is_some() {
let doc = s.doc_mut()?;
for (k, v) in &rich.images {
doc.images.entry(k.clone()).or_insert_with(|| v.clone());
}
}
let doc = s.doc()?;
let layer_fills = s.ds()?.text_edit.as_ref().and_then(|te| doc.node(te.id)).map(|n| n.fills.clone());
let spans: Vec<(usize, usize, figcraft_doc::TextStyle)> = rich
.spans
.iter()
.map(|(from, to, style)| {
let mut style = style.clone();
if style.style_id.as_deref().is_some_and(|id| doc.style(id).is_none()) {
style.style_id = None;
}
if style.fills == layer_fills {
style.fills = None;
}
(*from, *to, style)
})
.collect();
edit(s, |t, te| {
let (a, b) = range(te);
t.replace_range(a, b, &rich.text);
for (from, to, style) in &spans {
t.restyle(a + from, a + to, |x| *x = style.clone());
}
te.caret = a + rich.text.chars().count();
te.anchor = te.caret;
})
}
/// The selected range while editing (for styling commands), or None.
pub fn selected_range(s: &Session) -> Option<(NodeId, usize, usize)> {
let te = s.ds().ok()?.text_edit.clone()?;
@@ -569,3 +569,52 @@ fn an_empty_ime_commit_ends_the_composition_without_inserting_text() {
end(&mut s).unwrap();
assert_eq!(insert_ime_commit(&mut s, "").unwrap(), ImeInsertion::Nothing);
}
#[test]
fn rich_text_pastes_its_runs_and_drops_a_link_to_a_style_this_file_lacks() {
let (mut s, id) = setup("ab");
begin(&mut s, id, Some(2), false).unwrap();
let mut bold = data(&s, id).style.clone();
bold.font_style = "Bold".into();
bold.style_id = Some("from another file".into());
let plain = data(&s, id).style.clone();
insert_rich(&mut s, &RichText { text: "XY".into(), spans: vec![(0, 1, bold), (1, 2, plain)], images: Default::default() }).unwrap();
let t = data(&s, id);
assert_eq!(t.characters, "abXY");
assert_eq!(t.style_at(2).font_style, "Bold");
assert_eq!(t.style_at(2).style_id, None, "a link to a style this file doesn't have");
assert_eq!(t.style_at(3).font_style, "Regular");
assert_eq!(sel(&s), (4, 4));
set_caret(&mut s, 2, false).unwrap();
set_caret(&mut s, 4, true).unwrap();
let copied = selected_rich_text(&s).unwrap();
assert_eq!(copied.text, "XY");
assert_eq!(copied.spans.iter().map(|(a, b, st)| (*a, *b, st.font_style.as_str())).collect::<Vec<_>>(), [(0, 1, "Bold"), (1, 2, "Regular")]);
}
#[test]
fn copied_characters_bring_the_image_their_fill_uses_into_another_file() {
let (mut source, id) = setup("ab");
let data = figcraft_doc::ImageData { bytes: std::sync::Arc::new(vec![1, 2, 3]), width: 2, height: 2 };
{
let doc = source.doc_mut().unwrap();
doc.images.insert("pic".into(), data.clone());
doc.get_mut(id).unwrap().fills = vec![figcraft_color::Paint::image("pic", figcraft_color::ImageScaleMode::Fill)];
}
begin(&mut source, id, Some(0), false).unwrap();
set_caret(&mut source, 2, true).unwrap();
let copied = selected_rich_text(&source).unwrap();
let (mut s, target) = setup("cd");
begin(&mut s, target, Some(2), false).unwrap();
insert_rich(&mut s, &copied).unwrap();
assert_eq!(s.doc().unwrap().images.get("pic"), Some(&data), "the run's image fill resolves here");
}
#[test]
fn copied_text_layers_join_one_per_line_with_their_runs_in_place() {
let (mut s, first) = setup("ab");
let second = crate::params::id_of(&s.execute("text.create", &json!({"text": "cdé", "x": 0, "y": 50})).unwrap()["id"]).unwrap();
let joined = layers_rich_text(s.doc().unwrap(), &[first, second]).unwrap();
assert_eq!(joined.text, "ab\ncdé");
assert_eq!(joined.spans.iter().map(|(a, b, _)| (*a, *b)).collect::<Vec<_>>(), [(0, 2), (3, 6)]);
}
+4
View File
@@ -649,6 +649,10 @@ pub struct ToolState {
pub place_at: Option<Point>,
/// The document (uid) and page the crosshair was shown on.
pub(crate) place_on: Option<(u64, NodeId)>,
/// The last two Move or Scale presses, oldest first: where each was and the selection just
/// before it. A Shift double-click works from the selection its first click found. A press
/// with another tool clears them, and so does the double-click that uses them.
pub(crate) selections_before_last_two_presses: [Option<(Point, Vec<NodeId>)>; 2],
}
impl ToolState {
+45 -1
View File
@@ -139,6 +139,38 @@ impl Session {
return crate::vectoredit::begin_many(self, &ids);
}
// Groups, frames and boolean groups: select one level deeper (the layer under the pointer).
if ev.shift && !ev.cmd {
// Both presses recorded here are this double-click's; without them (the presses came in
// one frame with the double-click, or with another tool) the current selection stands in.
let before_the_clicks = match std::mem::take(&mut self.tool.selections_before_last_two_presses) {
[Some((first, before)), Some((second, _))] if within_slop(ev, first) && within_slop(ev, second) => before,
_ => sel.clone(),
};
let entered_here = before_the_clicks.iter().any(|s| *s == leaf || doc.is_ancestor(*s, leaf));
let deeper = if entered_here {
figcraft_doc::geometry::enter_target(&doc, leaf, &before_the_clicks)
} else {
let mut branch = doc.ancestors(leaf);
branch.reverse();
branch.push(leaf);
let clicked = select_target(&doc, leaf, &before_the_clicks, false);
let beside_the_selection = before_the_clicks
.iter()
.filter_map(|s| branch.iter().rposition(|b| doc.is_ancestor(*b, *s)))
.max()
.and_then(|shared| branch.get(shared + 1))
.copied();
let start = beside_the_selection.filter(|b| doc.is_ancestor(clicked, *b)).unwrap_or(clicked);
figcraft_doc::geometry::enter_target(&doc, leaf, &[start])
};
let mut alongside: Vec<NodeId> = before_the_clicks
.into_iter()
.filter(|s| doc.contains(*s) && *s != deeper && !doc.is_ancestor(*s, deeper) && !doc.is_ancestor(deeper, *s))
.collect();
alongside.push(deeper);
self.set_selection(alongside);
return Ok(());
}
let deeper = figcraft_doc::geometry::enter_target(&doc, leaf, &sel);
if deeper != target || !sel.contains(&deeper) {
self.set_selection(vec![deeper]);
@@ -382,7 +414,15 @@ impl Session {
// and what to call it; nothing is applied).
self.request_ui("dialog.createFromColor", json!({"color": c.to_css_hex()}));
} else if !sel.is_empty() {
self.execute("node.set", &json!({"ids": sel, "props": {"fill": c.to_css_hex()}}))?;
let (stroked, filled): (Vec<NodeId>, Vec<NodeId>) = sel.iter().partition(|id| doc.node(**id).is_some_and(takes_pick_on_stroke));
self.grouped("Pick color", |s| {
for (ids, key) in [(filled, "fill"), (stroked, "stroke")] {
if !ids.is_empty() {
s.execute("node.set", &json!({"ids": ids, "props": {key: c.to_css_hex()}}))?;
}
}
Ok(())
})?;
}
self.recent_colors.retain(|x| *x != c);
self.recent_colors.insert(0, c);
@@ -392,3 +432,7 @@ impl Session {
Ok(())
}
}
fn takes_pick_on_stroke(n: &Node) -> bool {
!n.fills.iter().any(|p| p.visible) && n.strokes.iter().any(|p| p.visible)
}
+231 -46
View File
@@ -79,15 +79,22 @@ impl Session {
// layers in it is like the canvas (a press starts a marquee inside it) unless the frame is
// selected; stepping out from a selected descendant is handled by the marquee below.
// An empty frame (or a widget, or a board object such as a sticky) is picked and dragged.
let in_section = |n: &figcraft_doc::Node| n.parent.and_then(|p| doc.node(p)).is_some_and(|p| matches!(p.kind, NodeKind::Section { .. }));
let board_background = |leaf: NodeId| {
!sel.contains(&leaf)
(ev.cmd || !sel.contains(&leaf))
&& doc.node(leaf).is_some_and(|n| {
n.parent == Some(page) && n.kind.is_frame_like() && !n.children.is_empty() && !crate::widgets::is_widget(n) && !n.is_board_atom()
let board = match n.kind {
NodeKind::Section { contents_hidden } => !contents_hidden,
ref k => k.is_frame_like() && (n.parent == Some(page) || in_section(n)),
};
board && !n.children.is_empty() && !crate::widgets::is_widget(n) && !n.is_board_atom()
})
};
let label = label_at(&doc, page, &self.tool.labels, ev.p());
let hit = label.or_else(|| self.hit(&doc, page, ev.p(), ev.tol() * 2.0));
let target = label.or_else(|| hit.filter(|leaf| ev.cmd || !board_background(*leaf)).map(|leaf| select_target(&doc, leaf, &sel, ev.cmd)));
let leaf = self.hit(&doc, page, ev.p(), ev.tol() * 2.0);
let hit = label.or(leaf);
let background_under_cmd = leaf.filter(|l| ev.cmd && label.is_none() && board_background(*l));
let target = label.or_else(|| leaf.filter(|leaf| !board_background(*leaf)).map(|leaf| select_target(&doc, leaf, &sel, ev.cmd)));
// A press inside the selection's box that reaches nothing above it (an unfilled shape's
// inside, the frame or canvas behind it, or a layer stacked below the selected layer the
// press is in) drags the selection. In a gap between selected layers, what's there is hit.
@@ -105,8 +112,15 @@ impl Session {
// selects just it. A press that reaches nothing above the selection uses the selection as
// its drag target instead; that fallback is not a clicked layer.
let clicked = target;
let marks_out_a_selected_board = background_under_cmd.is_some_and(|b| sel.contains(&b));
let target = match sel.iter().copied().find(|s| !locked_in(&doc, *s)) {
Some(first) if label.is_none() && !ev.shift && behind_sel(target) && selection_box(&doc, &sel).is_some_and(|q| in_quad(&q, ev.p())) => {
Some(first)
if label.is_none()
&& !ev.shift
&& !marks_out_a_selected_board
&& behind_sel(target)
&& selection_box(&doc, &sel).is_some_and(|q| in_quad(&q, ev.p())) =>
{
Some(first)
}
_ => target,
@@ -186,7 +200,7 @@ impl Session {
if let Some(f) = parent {
self.set_selection(vec![f]);
} else if !ev.shift {
self.set_selection(vec![]);
self.set_selection(background_under_cmd.into_iter().collect());
}
self.tool.gesture = Gesture::Marquee {
start: ev.p(),
@@ -249,7 +263,11 @@ impl Session {
let raw = d;
let snap_on = self.ds().map(|ds| ds.view.snap_objects).unwrap_or(true) && !ev.cmd && !ev.ctrl;
let mut guides = Vec::new();
if self.ds().map(|ds| ds.view.snap_pixel).unwrap_or(true) {
let boards = {
let doc = self.doc()?;
ids.iter().all(|i| doc.node(*i).is_some_and(crate::snap::always_on_pixels))
};
if boards || self.ds().map(|ds| ds.view.snap_pixel).unwrap_or(true) {
// Keep the box's origin on whole pixels (a rotated parent frame's, inside one);
// snapping to layers comes after, so it wins on the axes it snaps.
d = targets.round_move(d);
@@ -259,6 +277,11 @@ impl Session {
d += c;
guides = g2;
}
if boards {
// Frames, sections and components stay on whole pixels even where a layer
// they snap to doesn't.
d = targets.round_move(d);
}
let ids = ids.clone();
let dup = *duplicate;
let page = self.page()?;
@@ -343,6 +366,9 @@ impl Session {
doc.reparent(*m, page, None)?;
}
move_world(doc, *m, d.x, d.y)?;
if doc.node(*m).is_some_and(crate::snap::always_on_pixels) {
shifted &= !crate::snap::settle_on_pixels(doc, *m)?;
}
}
drop_target = (flow && target != page).then_some(target);
Ok(())
@@ -521,7 +547,13 @@ impl Session {
// The pixel grid: an upright box's dragged sides land on whole pixels (the Scale tool
// scales by the factor as dragged). Snapping to layers comes after, so it wins on the axes
// it snaps.
if !scale_tool && self.ds().map(|d| d.view.snap_pixel).unwrap_or(true) && crate::guides::axis_aligned(frame) {
// Frames, sections and components land on whole pixels whatever the setting, also where a
// layer they snap to doesn't.
let boards = {
let doc = self.doc()?;
!scale_tool && crate::guides::axis_aligned(frame) && ids.iter().all(|i| doc.node(*i).is_some_and(crate::snap::always_on_pixels))
};
if boards || !scale_tool && self.ds().map(|d| d.view.snap_pixel).unwrap_or(true) && crate::guides::axis_aligned(frame) {
p = Point::new(p.x.round(), p.y.round());
}
if let Some(t) = &targets {
@@ -530,6 +562,9 @@ impl Session {
p.y += dy;
guides = g;
}
if boards {
p = Point::new(p.x.round(), p.y.round());
}
let q = frame.inverse() * p;
let is_line = r.single && ids.first().and_then(|i| self.doc().ok()?.node(*i).map(|n| matches!(n.kind, NodeKind::Line))).unwrap_or(false);
if scale_tool {
@@ -557,9 +592,16 @@ impl Session {
self.tool.overlay.guides = guides;
return Ok(());
}
// Constrain proportions (Shift, or the node's lock).
let keep = ev.shift || r.single && ids.first().and_then(|i| self.doc().ok()?.node(*i).map(|n| n.constrain_proportions)).unwrap_or(false);
let (x0, y0, x1, y1) = resized_box(r.handle, q, w0, h0, keep, ev.alt);
let image_box = ids.first().filter(|_| ev.cmd && r.single).and_then(|i| self.image_box(*i));
// Constrain proportions (Shift, or the node's lock; cropping an image ignores the lock).
let locked =
r.single && image_box.is_none() && ids.first().and_then(|i| self.doc().ok()?.node(*i).map(|n| n.constrain_proportions)).unwrap_or(false);
let keep = ev.shift || locked;
let resized = resized_box(r.handle, q, w0, h0, keep, ev.alt);
let (x0, y0, x1, y1) = match image_box {
Some(image) => within_the_image(resized, image, (w0, h0), keep),
None => resized,
};
let (flip_x, flip_y) = (x1 < x0, y1 < y0);
let (nx0, ny0) = (x0.min(x1), y0.min(y1));
let (nw, nh) = ((x1 - x0).abs(), (y1 - y0).abs());
@@ -571,46 +613,30 @@ impl Session {
let keeps = |doc: &Document, id: NodeId| {
doc.node(id).is_some_and(|n| matches!(n.kind, NodeKind::Section { .. }) || (ev.cmd && single && n.kind.is_frame_like()))
};
let dragged_box = |world: Affine, (ox, oy): (f64, f64)| {
let mut t = world * Affine::translate((ox, oy));
if flip_x {
t *= Affine::new([-1.0, 0.0, 0.0, 1.0, nw, 0.0]);
}
if flip_y {
t *= Affine::new([1.0, 0.0, 0.0, -1.0, 0.0, nh]);
}
t
};
self.preview(|doc, _| {
if single {
let Some((id, world, _, _)) = nodes.first() else { return Ok(()) };
let kept = if keeps(doc, *id) { crate::cmd::props::children_worlds(doc, *id) } else { Vec::new() };
let mut t = *world * Affine::translate((nx0, ny0));
if flip_x {
t *= Affine::new([-1.0, 0.0, 0.0, 1.0, nw, 0.0]);
}
if flip_y {
t *= Affine::new([1.0, 0.0, 0.0, -1.0, 0.0, nh]);
}
let t = dragged_box(*world, (nx0, ny0));
// Text reflow and auto layout can recompute this box after the preview (a size bound
// to a variable lets go of it: the resize is an explicit edit).
// to a variable lets go of it: the resize is an explicit edit). A text keeps its
// fills; any other layer's image is cropped again for the box layout leaves
// (`crop_to_the_laid_out_box`).
let n = doc.get(*id)?;
let crop_images = ev.cmd
&& !matches!(n.kind, NodeKind::Text(_))
&& !std::iter::once(*id).chain(doc.ancestors(*id)).any(|a| doc.node(a).is_some_and(|n| n.layout.is_some()));
if crop_images {
// Crop the layer's image fills without moving their pixels on the page.
// Work from the interaction snapshot, just like the geometry on every move.
let (w, h) = (n.width.max(1e-6), n.height.max(1e-6));
let to_old =
Affine::scale_non_uniform(1.0 / w, 1.0 / h) * world.inverse() * t * Affine::scale_non_uniform(nw.max(0.01), nh.max(0.01));
let mut fills = n.fills.clone();
for paint in &mut fills {
let PaintKind::Image(img) = &mut paint.kind else { continue };
// A repeating image cannot be represented by a single Crop placement.
if img.scale_mode == ImageScaleMode::Tile {
continue;
}
let Some(data) = doc.images.get(&img.image) else { continue };
let (iw, ih) = (f64::from(data.width), f64::from(data.height));
// A degenerate (zero-scale) layer has no inverse: its image keeps its placement.
let crop = (Affine::new(img.placement_crop(iw, ih, w, h)) * to_old).as_coeffs();
if !crop.iter().all(|c| c.is_finite()) {
continue;
}
img.crop = Some(crop);
img.scale_mode = ImageScaleMode::Crop;
}
// Crop the layer's image fills without moving their pixels on the page.
// Work from the interaction snapshot, just like the geometry on every move.
if ev.cmd && !matches!(n.kind, NodeKind::Text(_)) {
let fills = cropped_image_fills(doc, n, *world, t, (nw, nh));
doc.get_mut(*id)?.fills = fills;
}
doc.set_world_transform(*id, t)?;
@@ -650,16 +676,81 @@ impl Session {
let lin = (mirror * local).with_translation(Vec2::ZERO);
let origin = Point::new(x0 + center.x * sx, y0 + center.y * sy) - lin * Point::new(w2 / 2.0, h2 / 2.0);
let kept = if keeps(doc, *id) { crate::cmd::props::children_worlds(doc, *id) } else { Vec::new() };
doc.set_world_transform(*id, frame * lin.with_translation(origin))?;
let (t, w2, h2) = if boards {
on_whole_pixels(doc, *id, frame * lin.with_translation(origin), w2, h2)
} else {
(frame * lin.with_translation(origin), w2, h2)
};
doc.set_world_transform(*id, t)?;
crate::cmd::props::resize_node(doc, *id, w2, h2)?;
if boards {
crate::snap::settle_on_pixels(doc, *id)?;
}
crate::cmd::props::restore_worlds(doc, &kept)?;
}
Ok(())
})?;
if single
&& ev.cmd
&& let Some((id, world, _, _)) = nodes.first()
{
let laid_out_box = |(fw, fh): (f64, f64)| {
let origin = match image_box {
Some((ix0, iy0, ix1, iy1)) => {
(slid_onto_the_image(nx0, fw, flip_x, (ix0, ix1), w0), slid_onto_the_image(ny0, fh, flip_y, (iy0, iy1), h0))
}
None => (nx0, ny0),
};
dragged_box(*world, origin)
};
self.crop_to_the_laid_out_box(*id, *world, laid_out_box, (nw, nh))?;
}
self.tool.overlay.guides = guides;
Ok(())
}
/// The box `(x0, y0, x1, y1)` of the first visible, untiled image fill of `id` in the layer's
/// own axes, as it was when the gesture began; `None` for a text or a layer without one.
fn image_box(&self, id: NodeId) -> Option<(f64, f64, f64, f64)> {
let snapshot = self.ds().ok()?.interaction.as_ref()?.doc.clone();
let n = snapshot.node(id)?;
if matches!(n.kind, NodeKind::Text(_)) {
return None;
}
n.fills.iter().filter(|p| p.visible).find_map(|p| match &p.kind {
PaintKind::Image(img) if img.scale_mode != ImageScaleMode::Tile => {
let data = snapshot.images.get(&img.image)?;
let crop = img.effective_crop(f64::from(data.width), f64::from(data.height), n.width, n.height);
let (x0, y0, x1, y1) = figcraft_doc::color::ImagePaint::crop_rect(crop);
Some((x0 * n.width, y0 * n.height, x1 * n.width, y1 * n.height))
}
_ => None,
})
}
/// After the preview's layout: when the layer didn't keep the dragged size `(nw, nh)` (a
/// minimum size, a Hug frame), crop its image fills again from the snapshot for the size it
/// has, the box placed by `laid_out_box` (given that size) in the layer's starting axes.
fn crop_to_the_laid_out_box(
&mut self,
id: NodeId,
world: Affine,
laid_out_box: impl Fn((f64, f64)) -> Affine,
(nw, nh): (f64, f64),
) -> Result<()> {
let ds = self.ds_mut()?;
let Some(snapshot) = ds.interaction.as_ref().map(|it| it.doc.clone()) else { return Ok(()) };
let Some(before) = snapshot.node(id).filter(|n| !matches!(n.kind, NodeKind::Text(_))) else { return Ok(()) };
let Some((fw, fh)) = ds.doc.node(id).map(|n| (n.width, n.height)) else { return Ok(()) };
if (fw - nw.max(0.01)).abs() < 1e-9 && (fh - nh.max(0.01)).abs() < 1e-9 {
return Ok(());
}
let fills = cropped_image_fills(&snapshot, before, world, laid_out_box((fw, fh)), (fw, fh));
std::sync::Arc::make_mut(&mut ds.doc).get_mut(id)?.fills = fills;
ds.revision += 1;
Ok(())
}
/// Scale tool handle drag (`q`: the snapped pointer in the handle box's axes): everything
/// scales by one factor about the anchor point (Alt: the centre), strokes, effects, radii and
/// text included, children by the same factor whatever their constraints.
@@ -697,6 +788,25 @@ impl Session {
}
}
/// `world` and the size `w` x `h` a layer of a resized selection takes, moved so its box in its
/// parent has its edges on whole pixels, each on the nearest one and the box at least a pixel
/// wide: a frame resized with others lands on whole pixels as one resized alone does. A layer
/// turned or scaled in its parent keeps them.
fn on_whole_pixels(doc: &Document, id: NodeId, world: Affine, w: f64, h: f64) -> (Affine, f64, f64) {
let pw = doc.node(id).and_then(|n| n.parent).map_or(Affine::IDENTITY, |p| doc.world_transform(p));
let local = pw.inverse() * world;
let [a, b, c, d, e, f] = local.as_coeffs();
if !crate::guides::axis_aligned(local) || (a.abs() - 1.0).abs() > 1e-9 || (d.abs() - 1.0).abs() > 1e-9 {
return (world, w, h);
}
let edges = |at: f64, flip: bool, len: f64| if flip { (at - len, at) } else { (at, at + len) };
let ((x0, x1), (y0, y1)) = (edges(e, a < 0.0, w), edges(f, d < 0.0, h));
let (x0, y0) = (x0.round(), y0.round());
let (w, h) = ((x1.round() - x0).max(1.0), (y1.round() - y0).max(1.0));
let (e, f) = (if a < 0.0 { x0 + w } else { x0 }, if d < 0.0 { y0 + h } else { y0 });
(pw * Affine::new([a, b, c, d, e, f]), w, h)
}
/// Moving `moving` by the same offset moves nothing else and changes nothing about them but where
/// they are: none is inside another (it would move twice) or placed by its parent's auto layout
/// (the layout would put it back, or close the gap it leaves).
@@ -714,3 +824,78 @@ fn only_shifted(doc: &Document, moving: &[NodeId]) -> bool {
!in_flow && !nested
})
}
/// `before`'s fills (from the snapshot `doc`) with each image cropped to the box `dragged` (the
/// layer's new transform, `nw` × `nh`), its pixels left where they were on the page (`world`:
/// the layer's transform before the drag).
fn cropped_image_fills(
doc: &Document,
before: &figcraft_doc::Node,
world: Affine,
dragged: Affine,
(nw, nh): (f64, f64),
) -> Vec<figcraft_doc::color::Paint> {
let (w, h) = (before.width.max(1e-6), before.height.max(1e-6));
let to_before = Affine::scale_non_uniform(1.0 / w, 1.0 / h) * world.inverse() * dragged * Affine::scale_non_uniform(nw.max(0.01), nh.max(0.01));
let mut fills = before.fills.clone();
for paint in &mut fills {
let PaintKind::Image(img) = &mut paint.kind else { continue };
// A repeating image cannot be represented by a single Crop placement.
if img.scale_mode == ImageScaleMode::Tile {
continue;
}
let Some(data) = doc.images.get(&img.image) else { continue };
let (iw, ih) = (f64::from(data.width), f64::from(data.height));
// A degenerate (zero-scale) layer has no inverse: its image keeps its placement.
let crop = (Affine::new(img.placement_crop(iw, ih, w, h)) * to_before).as_coeffs();
if !crop.iter().all(|c| c.is_finite()) {
continue;
}
img.crop = Some(crop);
img.scale_mode = ImageScaleMode::Crop;
}
fills
}
/// The extent `lo..hi` an image of extent `image` lets a crop reach on one axis of a layer that
/// started `len` long: the image's, or the layer's where that reaches further (a Fit image is
/// smaller than its layer).
fn crop_reach(image: (f64, f64), len: f64) -> (f64, f64) {
(image.0.min(image.1).min(0.0), image.0.max(image.1).max(len))
}
/// The dragged box `(x0, y0, x1, y1)` drawn back towards the starting box `(0, 0, w0, h0)` until
/// its sides stop at the image's box `image` (see [`crop_reach`]). Both ends of an axis go back by
/// the same fraction, so an Alt resize stays centred, and with `keep` (Shift) both axes do, so the
/// ratio holds. A flipped axis stays as dragged.
fn within_the_image((x0, y0, x1, y1): (f64, f64, f64, f64), image: (f64, f64, f64, f64), (w0, h0): (f64, f64), keep: bool) -> (f64, f64, f64, f64) {
let fraction = |a: f64, b: f64, image: (f64, f64), len: f64| {
if b < a {
return 1.0;
}
let (lo, hi) = crop_reach(image, len);
let mut t: f64 = 1.0;
if a < lo {
t = t.min(lo / a);
}
if b > hi {
t = t.min((hi - len) / (b - len));
}
if t.is_finite() { t.clamp(0.0, 1.0) } else { 0.0 }
};
let (tx, ty) = (fraction(x0, x1, (image.0, image.2), w0), fraction(y0, y1, (image.1, image.3), h0));
let (tx, ty) = if keep { (tx.min(ty), tx.min(ty)) } else { (tx, ty) };
(x0 * tx, y0 * ty, w0 + (x1 - w0) * tx, h0 + (y1 - h0) * ty)
}
/// Where a crop box `len` long, placed at `start` on one axis, starts once it is slid back onto
/// the image (see [`crop_reach`]): layout can make a layer longer than it was dragged (a minimum
/// size), and the crop then moves along the image rather than past its edge. A flipped axis, or
/// a box longer than the reach, stays where it is.
fn slid_onto_the_image(start: f64, len: f64, flipped: bool, image: (f64, f64), len0: f64) -> f64 {
let (lo, hi) = crop_reach(image, len0);
if flipped || len.is_nan() || len > hi - lo {
return start;
}
start.max(lo).min(hi - len)
}
+15 -1
View File
@@ -30,7 +30,10 @@ impl Session {
let tool = self.tool.tool;
let mut p = ev.p();
let mut guides = Vec::new();
let pixel = self.ds().map(|d| d.view.snap_pixel).unwrap_or(true);
// Frames and sections land on whole pixels whatever the setting, also where a layer they
// snap to doesn't (see `snap::always_on_pixels`).
let board = matches!(tool, ToolId::Frame | ToolId::Section);
let pixel = board || self.ds().map(|d| d.view.snap_pixel).unwrap_or(true);
// The pixel grid first: snapping to layers comes after, so it wins on the axes it snaps.
if pixel {
p = Point::new(p.x.round(), p.y.round());
@@ -41,6 +44,9 @@ impl Session {
p.y += dy;
guides = g;
}
if board {
p = Point::new(p.x.round(), p.y.round());
}
let mut created = id;
let page = self.page()?;
// Edit ▸ Set default properties: what new shapes take (not frames, sections, slices, lines
@@ -100,6 +106,9 @@ impl Session {
n.transform = pw.inverse() * Affine::translate((r.x0, r.y0));
}
doc.insert(n, parent, None)?;
if board {
crate::snap::settle_on_pixels(doc, nid)?;
}
if let Some(d) = &defaults {
// Best effort: a default the shape can't take leaves it as drawn.
let _ = crate::cmd::edit::apply_copied_props("edit.setDefaultProperties", doc, nid, d);
@@ -156,6 +165,11 @@ impl Session {
}
// A layer can't go into itself; it stays where it is.
let _ = d.reparent(*m, target, None);
// Frames, sections and components land on whole pixels of the frame
// they are dropped into too.
if d.node(*m).is_some_and(crate::snap::always_on_pixels) {
crate::snap::settle_on_pixels(d, *m)?;
}
}
crate::normalize(ds.doc_mut(), &before);
}
+37 -3
View File
@@ -38,11 +38,34 @@ impl Session {
/// (its children), or the focus view's frame.
pub(crate) fn marquee_within(&self, p: Point) -> Result<Option<NodeId>> {
let (doc, page) = (self.doc()?, self.page()?);
let within = frame_at(doc, page, p, &[]).filter(|f| doc.node(*f).is_some_and(|n| n.parent == Some(page)));
let within = within.filter(|f| doc.world_bounds(*f).is_some_and(|b| b.contains(p)));
let deepest = frame_at(doc, page, p, &[]).filter(|f| doc.world_bounds(*f).is_some_and(|b| b.contains(p)));
let mut chain = deepest.map(|f| doc.ancestors(f)).unwrap_or_default();
chain.reverse();
chain.extend(deepest);
let mut within = None;
for c in chain.into_iter().filter(|c| *c != page) {
let Some(n) = doc.node(c) else { break };
match &n.kind {
NodeKind::Section { contents_hidden: false } => within = Some(c),
k if k.is_frame_like() => {
within = Some(c);
break;
}
_ => break,
}
}
Ok(self.ds()?.focused().or(within))
}
fn marquee_root(&self, within: Option<NodeId>) -> Result<(NodeId, Option<NodeId>)> {
let (doc, page) = (self.doc()?, self.page()?);
Ok(match within.and_then(|w| doc.node(w)) {
Some(n) if matches!(n.kind, NodeKind::Section { .. }) => (n.id, None),
Some(n) => (n.parent.unwrap_or(page), Some(n.id)),
None => (page, None),
})
}
/// The selection a marquee over page rect `r` makes from `base` (what was selected before):
/// the layers it touches (`deep`: nested ones too); `additive` (Shift) toggles them.
pub(crate) fn marquee_selection(&self, r: Rect, within: Option<NodeId>, deep: bool, base: &[NodeId], additive: bool) -> Result<Vec<NodeId>> {
@@ -51,7 +74,10 @@ impl Session {
let mut hits = match (deep, focused) {
(true, _) => figcraft_doc::geometry::marquee_deep(doc, page, r),
(false, Some(f)) => figcraft_doc::geometry::marquee(doc, page, r, Some(f)),
(false, None) => figcraft_doc::geometry::marquee_select(doc, page, r, within),
(false, None) => {
let (root, start_inside) = self.marquee_root(within)?;
figcraft_doc::geometry::marquee_select(doc, root, r, start_inside)
}
};
if let Some(f) = focused {
hits.retain(|h| *h != f && doc.is_ancestor(f, *h));
@@ -136,6 +162,11 @@ impl Session {
}
let tool = self.acting_tool();
let edits = matches!(tool, ToolId::Move | ToolId::Scale) && !self.tool.dev_mode;
// Presses with another tool don't record the selection: the ones from before them aren't
// this double-click's.
if ev.kind == PointerKind::Down && !matches!(tool, ToolId::Move | ToolId::Scale) {
self.tool.selections_before_last_two_presses = Default::default();
}
if edits && self.origin_pointer(ev)? {
return Ok(());
}
@@ -155,6 +186,9 @@ impl Session {
}
// A click on the canvas deselects a ruler guide (the UI selects guides itself).
self.ds_mut()?.guide = None;
let now = self.ds()?.selection.clone();
let [_, last] = std::mem::take(&mut self.tool.selections_before_last_two_presses);
self.tool.selections_before_last_two_presses = [last, Some((ev.p(), now))];
self.move_down(ev)
}
ToolId::Hand => {
+43 -4
View File
@@ -642,10 +642,12 @@ fn index(cmd: &str, p: &Value, key: &str) -> Result<usize> {
}
/// Delete the points and segments of `parts` (`heal` keeps paths through deleted points closed).
pub(crate) fn delete_selection(s: &mut Session, parts: Vec<EditPart>, heal: bool) -> Result<()> {
pub(crate) fn delete_selection(s: &mut Session, parts: Vec<EditPart>, heal: bool, then_select_next: bool) -> Result<()> {
let doc = s.doc_mut()?;
let mut next = Vec::new();
for EditPart { id, vertices: verts, segments: segs } in parts {
edit(doc, id, |net| {
let following = edit(doc, id, |net| {
let following = if then_select_next { points_following(net, &verts) } else { Vec::new() };
// Segments first (their indices refer to the network before points go).
let segs: Vec<usize> =
segs.into_iter().filter(|si| net.segments.get(*si).is_some_and(|x| !verts.contains(&x.a) && !verts.contains(&x.b))).collect();
@@ -654,15 +656,52 @@ pub(crate) fn delete_selection(s: &mut Session, parts: Vec<EditPart>, heal: bool
// Point indices may have shifted: find them again by position.
let now: Vec<usize> = pts.iter().filter_map(|p| net.vertices.iter().position(|v| v.point() == *p)).collect();
ops::delete_vertices(net, &now, heal);
following.iter().filter_map(|p| net.vertices.iter().position(|v| v.point() == *p)).collect::<Vec<usize>>()
})?;
next.push((id, following));
}
set_state(s, |ve| {
ve.clear_selection();
ve.anchor = None;
ve.pen_out = None;
for (id, following) in next {
if id == ve.id {
ve.vertices = following;
} else if let Some(o) = ve.others.iter_mut().find(|o| o.id == id) {
o.vertices = following;
}
}
})
}
fn points_following(net: &VectorNetwork, deleted: &[usize]) -> Vec<Point> {
let step = |from: usize, forward: bool| {
net.segments.iter().find_map(|sg| match forward {
true => (sg.a == from).then_some(sg.b),
false => (sg.b == from).then_some(sg.a),
})
};
let mut out: Vec<Point> = Vec::new();
for &v in deleted {
let found = [true, false].into_iter().find_map(|forward| {
let mut at = v;
for _ in 0..net.vertices.len() {
at = step(at, forward)?;
if !deleted.contains(&at) {
return Some(at);
}
}
None
});
if let Some(p) = found.and_then(|i| net.vertices.get(i)).map(|x| x.point())
&& !out.contains(&p)
{
out.push(p);
}
}
out
}
/// The points a command acts on, per layer: `vertices` names points of the active layer; without
/// it, every edited layer's selected points (with `ends`, the ends of selected segments too).
fn point_sets(s: &Session, p: &Value, ends: bool) -> Result<Vec<(NodeId, Vec<usize>)>> {
@@ -1112,7 +1151,7 @@ pub fn specs() -> Vec<CommandSpec> {
}),
spec!("vector.deleteHeal", "Delete and heal selection", "{vertices?} (default the selected points of every edited layer)", true, |s, p| {
let parts = point_sets(s, p, false)?.into_iter().map(|(id, vertices)| EditPart { id, vertices, segments: vec![] }).collect();
delete_selection(s, parts, true)?;
delete_selection(s, parts, true, true)?;
Ok(json!({"ok": true}))
}),
spec!("vector.edit.delete", "Delete points", "{vertices?, segments?} (default the selection in every edited layer)", true, |s, p| {
@@ -1121,7 +1160,7 @@ pub fn specs() -> Vec<CommandSpec> {
(None, None) => ve.parts(),
(v, sg) => vec![EditPart { id: ve.id, vertices: v.unwrap_or_default(), segments: sg.unwrap_or_default() }],
};
delete_selection(s, parts, false)?;
delete_selection(s, parts, false, true)?;
Ok(json!({"ok": true}))
}),
spec!("vector.edit.cornerRadius", "Point corner radius", "{radius, vertices?}", true, |s, p| {
+1
View File
@@ -24,6 +24,7 @@ use instance::{detach, make_slot, push_changes, remove_slot, reset_instance, res
pub(crate) use instance::{swap_at, swap_instance};
use props::{add_prop, bind_prop, delete_prop, edit_prop, set_props};
pub(crate) use props::{apply_prop_bindings, check_prop_binding, describe_props};
pub(crate) use variants::fit_set;
use variants::{add_variant, combine, create_set};
pub use variants::{can_add_variant, can_combine_variants, can_create_set};
+1 -1
View File
@@ -166,7 +166,7 @@ pub(super) fn create_set(s: &mut Session, p: &Value) -> Result<Value> {
}
/// Grow a component set so it wraps its variants with 20 px of padding (right and bottom).
pub(super) fn fit_set(doc: &mut Document, set: NodeId) {
pub(crate) fn fit_set(doc: &mut Document, set: NodeId) {
let Some(kids) = doc.node(set).map(|n| n.children.clone()) else { return };
let (mut w, mut h) = (0.0f64, 0.0f64);
for c in kids {
+191 -20
View File
@@ -127,6 +127,7 @@ pub(super) fn paste_design_layers(s: &mut Session, p: &Value) -> Result<Value> {
// A design-app paste replaces the copied layers, not the copied rows: a `fill.copy` before it
// still pastes afterwards.
let props = s.clipboard.props.take();
let props_source_doc = s.clipboard.props_source_doc;
let paint = s.clipboard.paint.take();
let stroke = s.clipboard.stroke.take();
let paint_images = std::mem::take(&mut s.clipboard.paint_images);
@@ -138,6 +139,7 @@ pub(super) fn paste_design_layers(s: &mut Session, p: &Value) -> Result<Value> {
nodes,
images,
props,
props_source_doc,
paint,
stroke,
paint_images,
@@ -219,8 +221,18 @@ pub(super) fn cut(s: &mut Session, p: &Value) -> Result<Value> {
delete(s, &json!({"ids": layers}))
}
/// Paste the clipboard under `parent` with the copied top-left moved to `at` (page coords).
/// Paste the clipboard under `parent` with the copied top-left moved to `at` (page coords). A
/// copied main is pasted as an instance of it; in another file, as an instance of it from the
/// library the source file publishes, and as a copy of it when that library doesn't offer it.
pub fn paste_into(s: &mut Session, parent: NodeId, at: Option<(f64, f64)>) -> Result<Vec<NodeId>> {
paste_layers(s, parent, at, false)
}
/// [`paste_into`]. With `as_variants`, copied variants pasted into `parent`, their own set, are
/// deep copies (new variants, as Duplicate makes) and the set grows to hold them. Only a plain
/// paste with that set, or a layer in it, selected asks for this; every other paste of a copied
/// main, into another set too, still makes an instance.
fn paste_layers(s: &mut Session, parent: NodeId, at: Option<(f64, f64)>, as_variants: bool) -> Result<Vec<NodeId>> {
let clip = s.clipboard.clone();
if clip.nodes.is_empty() {
return Err(EngineError::Disabled("edit.paste".into(), "the clipboard is empty".into()));
@@ -238,15 +250,20 @@ pub fn paste_into(s: &mut Session, parent: NodeId, at: Option<(f64, f64)>) -> Re
(Some((x, y)), Some(b)) => Affine::translate((x - b.x0, y - b.y0)),
_ => Affine::IDENTITY,
};
let into_set = as_variants && copy_local && copied_variants_set(doc, &clip.nodes) == Some(parent);
let mut out = Vec::new();
let mut all = BTreeMap::new();
for (root, nodes) in &clip.nodes {
if copy_local
&& clip.copied_components.contains(root)
&& let Some(n) = nodes.first().filter(|n| matches!(n.kind, NodeKind::Component { .. }))
&& doc.node(*root).is_some_and(|n| matches!(n.kind, NodeKind::Component { .. }))
{
let instance = crate::components::create_instance(doc, *root, parent, 0.0, 0.0)?;
let copied_main = nodes.first().filter(|n| clip.copied_components.contains(root) && matches!(n.kind, NodeKind::Component { .. }));
let main = match (copied_main, foreign) {
(Some(_), _) if copy_local => {
(!into_set && doc.node(*root).is_some_and(|n| matches!(n.kind, NodeKind::Component { .. }))).then_some(*root)
}
(Some(_), Some(src)) => crate::library::published_main(doc, src, clip.source_path.as_deref(), *root)?,
_ => None,
};
if let (Some(main), Some(n)) = (main, copied_main) {
let instance = crate::components::create_instance(doc, main, parent, 0.0, 0.0)?;
doc.get_mut(instance)?.transform = doc.world_transform(parent).inverse() * shift * n.transform;
keep_a_cropped_images_proportions(doc, instance, parent);
out.push(instance);
@@ -267,6 +284,9 @@ pub fn paste_into(s: &mut Session, parent: NodeId, at: Option<(f64, f64)>) -> Re
out.push(pasted);
all.extend(map);
}
if into_set {
crate::cmd::component::fit_set(doc, parent);
}
// Board connectors pasted with what they join join the pasted copies.
let originals: Vec<(NodeId, figcraft_doc::BoardItem)> =
clip.nodes.iter().flat_map(|(_, nodes)| nodes).filter_map(|n| Some((*all.get(&n.id)?, n.board.clone()?))).collect();
@@ -307,7 +327,16 @@ pub(super) fn paste(s: &mut Session, p: &Value) -> Result<Value> {
let sel = s.selection();
let doc = s.doc()?;
let copy_local = s.ds()?.uid == s.clipboard.source_doc;
let target = id(p, "parent").or_else(|| {
let variants_set = copied_variants_set(doc, &s.clipboard.nodes)
.filter(|set| copy_local && id(p, "parent").is_none() && !sel.is_empty() && sel.iter().all(|i| doc.is_ancestor(*set, *i)));
// Where the copied variants are now, not where they were copied: the set may have moved since.
let below_the_variants = variants_set.and_then(|set| {
let copied: Vec<NodeId> = s.clipboard.nodes.iter().map(|(root, _)| *root).collect();
let left = doc.bounds_of(&copied)?.x0;
let bottom = doc.node(set)?.children.iter().filter_map(|c| doc.world_bounds(*c)).map(|r| r.y1).reduce(f64::max)?;
Some((left, bottom + 20.0))
});
let target = id(p, "parent").or(variants_set).or_else(|| {
sel.first()
.copied()
.filter(|i| {
@@ -322,6 +351,7 @@ pub(super) fn paste(s: &mut Session, p: &Value) -> Result<Value> {
let parent = target.unwrap_or(page);
let at = match (num(p, "x"), num(p, "y")) {
(Some(x), Some(y)) => Some((x, y)),
_ if below_the_variants.is_some() => below_the_variants,
_ => {
let b = s.clipboard.bounds;
match (target, b) {
@@ -344,7 +374,7 @@ pub(super) fn paste(s: &mut Session, p: &Value) -> Result<Value> {
}
}
};
let ids = paste_into(s, parent, at)?;
let ids = paste_layers(s, parent, at, variants_set.is_some())?;
if let Some(sel) = sibling_of {
let above = s.doc()?.index_in_parent(sel).map(|ix| ix + 1);
move_above(s, &ids, parent, above)?;
@@ -381,14 +411,27 @@ fn move_above(s: &mut Session, ids: &[NodeId], parent: NodeId, above: Option<usi
Ok(())
}
/// The set the copied layers are variants of: every copied root is a main component in `doc` whose
/// parent is that one component set. `None` for anything else.
fn copied_variants_set(doc: &Document, copied: &[(NodeId, Vec<Node>)]) -> Option<NodeId> {
let mut sets = copied.iter().map(|(root, _)| {
let n = doc.node(*root).filter(|n| matches!(n.kind, NodeKind::Component { .. }))?;
n.parent.filter(|set| doc.node(*set).is_some_and(|p| matches!(p.kind, NodeKind::ComponentSet { .. })))
});
let first = sets.next()??;
sets.all(|set| set == Some(first)).then_some(first)
}
/// Paste over selection (Shift+Cmd/Ctrl+V): the copies go into the parent of the selected layer
/// [`last_seen`] picks, just above it, at the place it gives.
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, 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)), doc.index_in_parent(*i).map(|ix| ix + 1))
let (parent, at, above) = match last_seen(doc, &sel) {
Some((i, at)) => {
let parent = doc.node(i).and_then(|n| n.parent).unwrap_or(page);
(parent, at, doc.index_in_parent(i).map(|ix| ix + 1))
}
None => (page, None, None),
};
@@ -398,6 +441,38 @@ pub(super) fn paste_over(s: &mut Session, _p: &Value) -> Result<Value> {
Ok(json!({"ids": ids}))
}
/// The selected layer Paste over selection pastes after, and where the copies' top-left goes.
///
/// One layer: that layer, at its position. Several in one auto layout frame's flow (none absolutely
/// positioned): the last of them in the flow, which the layout follows. Several elsewhere: the lowest (then rightmost), with the copies
/// below it, as far below as it is from the selected layers above it. A selection with nothing above
/// its lowest layer is a row: the copies go right of the rightmost, as far as it is from its
/// neighbour on the left. Layers that overlap every way get the copies right under the lowest.
fn last_seen(doc: &Document, sel: &[NodeId]) -> Option<(NodeId, Option<(f64, f64)>)> {
let first = *sel.first()?;
let top_left = |i: NodeId| doc.world_bounds(i).map(|b| (b.x0, b.y0));
if sel.len() == 1 {
return Some((first, top_left(first)));
}
let parent = doc.node(first).and_then(|n| n.parent);
let one_flow = parent.and_then(|p| doc.node(p)).is_some_and(|p| p.layout.is_some())
&& sel.iter().all(|i| doc.node(*i).is_some_and(|n| n.parent == parent && !n.child_layout.absolute));
if one_flow {
let last = sel.iter().copied().max_by_key(|i| doc.index_in_parent(*i))?;
return Some((last, top_left(last)));
}
let boxes: Vec<(NodeId, figcraft_geom::Rect)> = sel.iter().filter_map(|i| Some((*i, doc.world_bounds(*i)?))).collect();
let (lowest, low) = *boxes.iter().max_by(|(_, a), (_, b)| a.y1.total_cmp(&b.y1).then(a.x1.total_cmp(&b.x1)))?;
if let Some(above) = boxes.iter().filter(|(_, o)| o.y1 <= low.y0).map(|(_, o)| o.y1).max_by(f64::total_cmp) {
return Some((lowest, Some((low.x0, low.y1 + (low.y0 - above)))));
}
let (rightmost, right) = *boxes.iter().max_by(|(_, a), (_, b)| a.x1.total_cmp(&b.x1).then(a.y1.total_cmp(&b.y1)))?;
match boxes.iter().filter(|(_, o)| o.x1 <= right.x0).map(|(_, o)| o.x1).max_by(f64::total_cmp) {
Some(left) => Some((rightmost, Some((right.x1 + (right.x0 - left), right.y0)))),
None => Some((lowest, Some((low.x0, low.y1)))),
}
}
pub(super) fn paste_replace(s: &mut Session, p: &Value) -> Result<Value> {
let targets = req_targets("edit.pasteReplace", s, p)?;
let mut out = Vec::new();
@@ -438,7 +513,19 @@ pub(super) fn copy_props_of(doc: &Document, id: NodeId) -> Value {
v["cornerRadius"] = json!(n.corners.radii);
v["cornerSmoothing"] = json!(n.corners.smoothing);
}
// A frame's layout grids go with its look, as its fills do.
if n.kind.is_frame_like() {
v["grids"] = json!(n.grids);
v["gridStyle"] = json!(n.styles.grid);
}
// The links behind the values: the styles and the variables they come from, so the pasted
// layer follows them as the copied one does.
v["fillStyle"] = json!(n.styles.fill);
v["strokeStyle"] = json!(n.styles.stroke);
v["effectStyle"] = json!(n.styles.effect);
v["boundVariables"] = Value::Object(n.bound.iter().filter(|(f, _)| copied_binding(f)).map(|(f, v)| (f.clone(), json!(v))).collect());
if let NodeKind::Text(t) = &n.kind {
v["textStyle"] = json!(n.styles.text);
v["fontFamily"] = json!(t.style.font_family);
v["fontStyle"] = json!(t.style.font_style);
v["fontSize"] = json!(t.style.font_size);
@@ -453,26 +540,110 @@ pub(super) fn copy_props(s: &mut Session, p: &Value) -> Result<Value> {
let id = targets(s, p).first().copied().ok_or_else(|| bad("edit.copyProperties", "select one layer"))?;
let v = copy_props_of(s.doc()?, id);
s.clipboard.props = Some(v.clone());
s.clipboard.props_source_doc = s.ds()?.uid;
Ok(v)
}
/// Copied properties `props` without their style and variable links, for a paste into another
/// file: the copied ids name the source file's styles and variables, and the same ids here can
/// name unrelated ones. The values paste unlinked, and the layer's own links on them go.
fn without_links(mut props: Value) -> Value {
if let Some(m) = props.as_object_mut() {
for (k, v) in m.iter_mut() {
if k.ends_with("Style") && !k.starts_with("font") {
*v = Value::Null;
} else if k == "boundVariables" {
*v = json!({});
}
}
}
props
}
/// Give layer `id` the properties [`copy_props_of`] copied (`props`), those it can take: the text
/// properties only to text, the corners only to a layer with corners.
pub(crate) fn apply_copied_props(cmd: &str, doc: &mut Document, id: NodeId, props: &Value) -> Result<()> {
let mut m = props.as_object().cloned().unwrap_or_default();
let is_text = matches!(doc.get(id)?.kind, NodeKind::Text(_));
if !is_text {
m.retain(|k, _| !k.starts_with("font") && k != "lineHeight" && k != "letterSpacing");
let n = doc.get(id)?;
let (is_text, corners, frame) = (matches!(n.kind, NodeKind::Text(_)), n.kind.has_corner_radius(), n.kind.is_frame_like());
let takes = |k: &str| {
let text = k.starts_with("font") || k.starts_with("paragraph") || matches!(k, "lineHeight" | "letterSpacing" | "textStyle");
let corner = k == "cornerSmoothing" || k.ends_with("Radius");
let grid = k == "gridStyle" || k == "grids" || k.starts_with("layoutGrids/");
(is_text || !text) && (corners || !corner) && (frame || !grid)
};
m.retain(|k, _| takes(k));
// A style or variable the file doesn't have (deleted since the copy) isn't here to link to: the
// values it gave are pasted without a link, so the layer's own link goes too.
let here = |v: &Value| v.as_str().is_none_or(|sid| doc.style(sid).is_some());
for (k, v) in m.iter_mut() {
if k.ends_with("Style") && !k.starts_with("font") && !here(v) {
*v = Value::Null;
}
}
if !doc.get(id)?.kind.has_corner_radius() {
m.remove("cornerRadius");
m.remove("cornerSmoothing");
if let Some(Value::Object(copied)) = m.get_mut("boundVariables") {
copied.retain(|_, v| v.as_str().is_some_and(|vid| doc.variables.get_by_id(vid).is_some()));
}
// The layer's own bindings on what is pasted give way to the copied layer's: kept, a binding
// would hold the old value over the pasted one. A binding on what the copy doesn't carry (a
// text layer's font size, pasted from a frame) stays.
if let Some(Value::Object(copied)) = m.get("boundVariables") {
let mut bound: serde_json::Map<String, Value> =
n.bound.keys().filter(|f| copied_binding(f) && m.contains_key(pasted_key(f))).map(|f| (f.clone(), Value::Null)).collect();
bound.extend(copied.iter().filter(|(f, _)| takes(f)).map(|(f, v)| (f.clone(), v.clone())));
m.insert("boundVariables".into(), Value::Object(bound));
}
crate::cmd::props::apply(cmd, doc, id, &m)
}
/// The key of the properties [`copy_props_of`] copies that sets what a variable bound to `field`
/// sets: a corner's radius is `cornerRadius`, a side's stroke weight `strokeWeight`, the font
/// weight `fontStyle`, a layout grid's field `grids` and a paint's or effect's field its list.
fn pasted_key(field: &str) -> &str {
match field {
"topLeftRadius" | "topRightRadius" | "bottomRightRadius" | "bottomLeftRadius" => "cornerRadius",
f if crate::cmd::props::STROKE_SIDES.contains(&f) => "strokeWeight",
"fontWeight" => "fontStyle",
f => match f.split_once('/') {
Some(("layoutGrids", _)) => "grids",
Some((list, _)) => list,
None => f,
},
}
}
/// Whether a variable bound to `field` goes with the properties [`copy_props_of`] copies: not a
/// size, auto layout spacing, visibility or text content.
fn copied_binding(field: &str) -> bool {
!matches!(
field,
"width"
| "height"
| "minWidth"
| "maxWidth"
| "minHeight"
| "maxHeight"
| "gap"
| "columnGap"
| "rowGap"
| "crossGap"
| "padding"
| "paddingHorizontal"
| "paddingVertical"
| "paddingTop"
| "paddingRight"
| "paddingBottom"
| "paddingLeft"
| "visible"
| "characters"
)
}
pub(super) fn paste_props(s: &mut Session, p: &Value) -> Result<Value> {
let props = s.clipboard.props.clone().ok_or_else(|| EngineError::Disabled("edit.pasteProperties".into(), "no copied properties".into()))?;
let mut props = s.clipboard.props.clone().ok_or_else(|| EngineError::Disabled("edit.pasteProperties".into(), "no copied properties".into()))?;
if s.ds()?.uid != s.clipboard.props_source_doc {
props = without_links(props);
}
let ids = req_targets("edit.pasteProperties", s, p)?;
let doc = s.doc_mut()?;
for i in ids {
@@ -154,7 +154,7 @@ pub(super) fn cut_selection(s: &mut Session, sel: EditSelection) -> Result<Value
}
let cut = sel.parts.len();
let segments = copy_parts(s, "edit.cut", &sel)?;
vectoredit::delete_selection(s, sel.delete, false)?;
vectoredit::delete_selection(s, sel.delete, false, false)?;
Ok(json!({"cut": cut, "segments": segments}))
}
+1
View File
@@ -462,6 +462,7 @@ fn close(s: &mut Session, p: &Value) -> Result<Value> {
}
let uid = ds.uid;
let active_uid = s.docs.get(s.active).map(|d| d.uid);
s.remember_view(i);
s.remove_tabs(|d| d.uid == uid);
// Removing a tab before the active one shifts its index; keep the same document selected.
s.active = active_uid.and_then(|a| s.docs.iter().position(|d| d.uid == a)).unwrap_or(i.min(s.docs.len().saturating_sub(1)));
+1
View File
@@ -107,6 +107,7 @@ pub(crate) fn open(s: &mut Session, p: &Value) -> Result<Value> {
ds.on_disk = on_disk.filter(|_| native);
s.docs.push(ds);
s.active = s.docs.len() - 1;
s.restore_view();
let mut out = json!({"index": s.active, "summary": summary});
out[if warnings { "warnings" } else { "repairs" }] = json!(loaded.issues);
Ok(out)
+2 -3
View File
@@ -173,7 +173,8 @@ fn wants_data(p: &Value) -> bool {
/// Save the file of the active tab (the main file for a branch tab, with its branches), or export
/// the active document as an experimental `.fig` copy without changing its native save state.
/// Without a path the file comes back as base64 `data` for the caller to deliver (#969).
/// Without a path the file comes back as base64 `data` for the caller to deliver (#969). Saved
/// to another file, the document takes that file's name, as its tab does.
fn save_to(s: &mut Session, path: Option<String>) -> Result<Value> {
if let Some(path) = path.as_deref().filter(|p| ext(p) == "fig") {
return export_fig(s, &json!({"path": path}));
@@ -185,9 +186,7 @@ fn save_to(s: &mut Session, path: Option<String>) -> Result<Value> {
refuse_dropping_images(ds, path)?;
}
let mut snapshot = FileSnapshot::of(ds);
let follows_path = ds.path.as_deref().map_or(ds.doc.name == "Untitled", |old| ds.doc.name == file_stem(old));
if let Some(path) = path.as_deref()
&& follows_path
&& ds.path.as_deref() != Some(path)
{
Arc::make_mut(&mut snapshot.doc).name = file_stem(path);
+3
View File
@@ -234,6 +234,9 @@ fn crop(s: &mut Session, p: &Value) -> Result<Value> {
// Like any paint edit, the layer leaves its paint style.
n.styles.fill = None;
}
if s.ds()?.vector_edit.is_some() {
crate::vectoredit::end(s)?;
}
s.request_ui(cmd, json!({"id": id, "index": index}));
Ok(json!({"id": id, "index": index}))
}
+1
View File
@@ -238,6 +238,7 @@ fn wrap(s: &mut Session, p: &Value, cmd: &str, w: Wrap) -> Result<Value> {
}
if let Wrap::Frame = w {
g.clip = true;
g.fills.clear();
}
// Insert the container where the topmost layer is.
doc.insert(g, parent, index)?;
+1 -1
View File
@@ -642,7 +642,7 @@ pub fn specs() -> Vec<CommandSpec> {
spec!(
"text.edit.key",
"Text key",
"{key: Backspace|Delete|Left|Right|Up|Down|Home|End|Enter|Tab|Escape|SelectAll, shift?, alt?, cmd?} in a list, Tab nests the item and Shift+Tab, Enter on an empty item or Backspace at its start move it out; in a code block, Tab types two spaces and Enter keeps the line's indent",
"{key: Backspace|Delete|Left|Right|Up|Down|Home|End|Enter|Tab|Escape|SelectAll, shift?, alt?, cmd?} in a list, Tab nests the item and Shift+Tab, Enter on an empty item or Backspace at its start move it out; in a code block, Tab types two spaces and Enter keeps the line's indent; elsewhere Tab and Shift+Tab edit the next or previous text layer of the frame in reading order (rows top to bottom, each left to right), all of it selected, and do nothing at the last and the first (in a board object or a widget's field Tab types a tab)",
true,
|s, p| {
let k = req_string("text.edit.key", p, "key")?;
+204
View File
@@ -298,3 +298,207 @@ fn many_entries_for_one_component_each_link() {
let i = idv(&ex(&mut s, "instance.create", json!({"component": hover, "x": 0, "y": 500})));
assert_eq!(code(&mut s, i, "react"), "<Button />\n");
}
#[test]
fn a_link_names_its_source_and_translates_variant_values() {
let mut s = Session::new();
ex(&mut s, "file.new", json!({}));
let (set, hover) = button(&mut s);
ex(
&mut s,
"codeConnect.set",
json!({"id": set, "name": "Button", "importPath": "@/ui/button", "template": "<Button state={State} />",
"source": "src/ui/button.tsx", "values": {"State": {"Hover": "hovered"}}, "notes": "Primary action"}),
);
let instance = idv(&ex(&mut s, "instance.create", json!({"component": hover})));
assert!(code(&mut s, instance, "react").contains(r#"state="hovered""#), "{}", code(&mut s, instance, "react"));
// A value without a mapping keeps the design's name.
let plain = idv(&ex(&mut s, "instance.create", json!({"component": set})));
assert!(code(&mut s, plain, "react").contains(r#"state="Default""#));
}
#[test]
fn a_source_outside_the_repository_is_refused() {
let mut s = Session::new();
ex(&mut s, "file.new", json!({}));
let c = card(&mut s);
for source in ["../up.tsx", "/etc/passwd", "a\\b.tsx", "a/../../b.tsx"] {
let e = s.execute("codeConnect.set", &json!({"id": c, "source": source})).unwrap_err();
assert!(e.to_string().contains("source"), "{source}: {e}");
}
assert!(s.execute("codeConnect.set", &json!({"id": c, "values": 3})).is_err());
assert!(s.execute("codeConnect.set", &json!({"id": c, "source": "src/card.tsx"})).is_ok());
}
#[test]
fn the_new_fields_survive_a_trip_through_the_file() {
let mut s = Session::new();
ex(&mut s, "file.new", json!({}));
let (set, _) = button(&mut s);
ex(
&mut s,
"codeConnect.set",
json!({"id": set, "name": "Button", "template": "<Button />", "source": "src/b.tsx", "values": {"State": {"Hover": "h"}}, "notes": "n"}),
);
let text = ex(&mut s, "codeConnect.export", json!({}))["text"].as_str().unwrap().to_string();
let mut other = Session::new();
ex(&mut other, "file.new", json!({}));
let (set2, _) = button(&mut other);
assert_eq!(ex(&mut other, "codeConnect.import", json!({"json": text}))["linked"], 1);
let link = &other.doc().unwrap().node(set2).unwrap().code_links[0];
assert_eq!((link.source.as_str(), link.notes.as_str()), ("src/b.tsx", "n"));
assert_eq!(link.values["State"]["Hover"], "h");
}
#[test]
fn a_file_from_before_stays_as_it_was() {
let mut s = Session::new();
ex(&mut s, "file.new", json!({}));
let (set, _) = button(&mut s);
ex(&mut s, "codeConnect.set", json!({"id": set, "name": "Button", "template": "<Button />"}));
let v = ex(&mut s, "codeConnect.export", json!({}));
let parsed: Value = serde_json::from_str(v["text"].as_str().unwrap()).unwrap();
let keys: Vec<&String> = parsed["links"][0].as_object().unwrap().keys().collect();
assert_eq!(keys, ["component", "importPath", "language", "name", "template"], "no new keys unless they're used");
}
#[test]
fn listing_answers_what_an_agent_asks() {
let dir = std::env::temp_dir().join(format!("figcraft-connect-list-{}", std::process::id()));
std::fs::create_dir_all(dir.join("src")).unwrap();
std::fs::write(dir.join("src/button.tsx"), "").unwrap();
let mut s = Session::new();
ex(&mut s, "file.new", json!({}));
let (set, hover) = button(&mut s);
let c = card(&mut s);
ex(
&mut s,
"codeConnect.set",
json!({"id": set, "name": "Button", "importPath": "@/ui/button", "template": "<Button />", "source": "src/button.tsx"}),
);
let v = ex(&mut s, "codeConnect.list", json!({"root": dir}));
assert_eq!((v["mapped"].as_u64(), v["unmapped"].as_u64()), (Some(1), Some(1)));
let b = v["components"].as_array().unwrap().iter().find(|e| e["id"] == json!(set)).unwrap();
assert_eq!(b["links"][0]["import"], r#"import { Button } from "@/ui/button";"#);
assert_eq!(b["links"][0]["sourceFound"], true);
assert!(b["links"][0]["snippet"].as_str().unwrap().contains("<Button"));
assert!(b["properties"].as_array().unwrap().iter().any(|p| p["type"] == "variant"));
let only = ex(&mut s, "codeConnect.list", json!({"unmapped": true}));
assert_eq!(only["components"][0]["id"], json!(c));
// A layer leads to the component it uses, a frame to those it holds.
let i = idv(&ex(&mut s, "instance.create", json!({"component": hover})));
assert_eq!(ex(&mut s, "codeConnect.list", json!({"ids": [i]}))["components"][0]["id"], json!(set));
ex(&mut s, "codeConnect.set", json!({"id": set, "source": "src/gone.tsx"}));
assert_eq!(ex(&mut s, "codeConnect.list", json!({"root": dir, "ids": [set]}))["components"][0]["links"][0]["sourceFound"], false);
}
#[test]
fn exporting_keeps_what_other_designs_put_in_the_file() {
let dir = std::env::temp_dir().join(format!("figcraft-connect-others-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("figcraft.connect.json");
std::fs::write(&path, r#"{"version":1,"project":{"name":"shop"},"links":[{"component":"Other","language":"react","name":"Other","template":"<Other />"},{"component":"Button","language":"react","name":"Old","template":"<Old />"}]}"#).unwrap();
let mut s = Session::new();
ex(&mut s, "file.new", json!({}));
let (set, _) = button(&mut s);
ex(&mut s, "codeConnect.set", json!({"id": set, "name": "Button", "template": "<Button />"}));
ex(&mut s, "codeConnect.export", json!({"path": path}));
let v: Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();
let names: Vec<&str> = v["links"].as_array().unwrap().iter().map(|l| l["name"].as_str().unwrap()).collect();
assert_eq!(names, ["Button", "Other"], "this design's link wins, the other design's stays");
assert_eq!(v["project"]["name"], "shop", "keys the command doesn't own stay");
}
#[test]
fn listing_refuses_a_malformed_target_rather_than_reading_the_selection() {
let mut s = Session::new();
ex(&mut s, "file.new", json!({}));
let (set, _) = button(&mut s);
ex(&mut s, "select.set", json!({"ids": [set]}));
for p in [json!({"id": "not-an-id"}), json!({"ids": [set, "nope"]}), json!({"ids": "1"}), json!({"ids": [999_999]})] {
assert!(s.execute("codeConnect.list", &p).is_err(), "{p}");
}
}
/// A set called `name` with a variant `prop=value` for each of `values`. Returns (set, variants).
fn set_of(s: &mut Session, name: &str, prop: &str, values: &[&str]) -> (NodeId, Vec<NodeId>) {
let variants: Vec<NodeId> = values
.iter()
.enumerate()
.map(|(k, v)| {
let f = idv(&ex(s, "frame.create", json!({"x": k as f64 * 150.0, "y": 600, "width": 100, "height": 40, "name": format!("{prop}={v}")})));
idv(&ex(s, "component.create", json!({"ids": [f]})))
})
.collect();
let set = idv(&ex(s, "component.combineVariants", json!({"ids": variants.clone()})));
ex(s, "node.set", json!({"id": set, "props": {"name": name}}));
(set, variants)
}
#[test]
fn a_condition_reads_the_designs_value_not_its_name_in_code() {
let mut s = Session::new();
ex(&mut s, "file.new", json!({}));
let (set, variants) = set_of(&mut s, "Toggle", "State", &["On", "Off"]);
ex(&mut s, "codeConnect.set", json!({"id": set, "name": "Toggle", "template": "{State ? \"enabled\" : \"disabled\"} {State}"}));
let off = idv(&ex(&mut s, "instance.create", json!({"component": variants[1]})));
assert!(code(&mut s, off, "react").starts_with("disabled"), "{}", code(&mut s, off, "react"));
// `inactive` reads as true, but the condition is about the design's Off.
ex(&mut s, "codeConnect.set", json!({"id": set, "values": {"State": {"Off": "inactive"}}}));
let out = code(&mut s, off, "react");
assert!(out.starts_with("disabled") && out.contains("inactive"), "{out}");
}
#[test]
fn a_mapping_keyed_by_a_name_it_cant_use_is_reported() {
let mut s = Session::new();
ex(&mut s, "file.new", json!({}));
let (set, hover) = button(&mut s);
let r = ex(
&mut s,
"codeConnect.set",
json!({"id": set, "name": "Button", "template": "<Button state={State} />", "values": {"state": {"Hover": "hovered"}}}),
);
assert!(r.to_string().contains("\"state\""), "the lowercase key does nothing, so it's named: {r}");
let i = idv(&ex(&mut s, "instance.create", json!({"component": hover})));
assert!(code(&mut s, i, "react").contains(r#"state="Hover""#));
let r = ex(&mut s, "codeConnect.set", json!({"id": set, "values": {"State": {"Hover": "hovered"}}}));
assert!(!r.to_string().contains("\"State\""), "{r}");
}
#[test]
fn an_import_with_malformed_values_keeps_the_link_there() {
let mut s = Session::new();
ex(&mut s, "file.new", json!({}));
let (set, _) = button(&mut s);
ex(&mut s, "codeConnect.set", json!({"id": set, "name": "Button", "template": "<Button />", "values": {"State": {"Hover": "h"}}}));
let links = json!([{"component": "Button", "language": "react", "name": "Other", "template": "<Other />", "values": {"State": {"Hover": 7}}}]);
let r = ex(&mut s, "codeConnect.import", json!({"json": {"version": 1, "links": links}}));
assert_eq!(r["linked"], 0, "{r}");
assert!(r["warnings"][0].as_str().unwrap().contains("values"), "{r}");
let link = &s.doc().unwrap().node(set).unwrap().code_links[0];
assert_eq!((link.name.as_str(), link.values["State"]["Hover"].as_str()), ("Button", "h"));
}
#[test]
fn exporting_over_a_file_it_cant_read_is_refused() {
let dir = std::env::temp_dir().join(format!("figcraft-connect-unread-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let mut s = Session::new();
ex(&mut s, "file.new", json!({}));
let (set, _) = button(&mut s);
ex(&mut s, "codeConnect.set", json!({"id": set, "name": "Button", "template": "<Button />"}));
let big = vec![b' '; 4 * 1024 * 1024 + 1];
for (name, bytes) in [("broken.json", b"{\"links\": [".to_vec()), ("list.json", b"[]".to_vec()), ("big.json", big)] {
let path = dir.join(name);
std::fs::write(&path, &bytes).unwrap();
assert!(s.execute("codeConnect.export", &json!({"path": path})).is_err(), "{name}");
assert_eq!(std::fs::read(&path).unwrap(), bytes, "{name} is left as it was");
}
// A file that isn't there yet is written.
let new = dir.join("figcraft.connect.json");
let _ = std::fs::remove_file(&new);
ex(&mut s, "codeConnect.export", json!({"path": new}));
assert!(new.exists());
let _ = std::fs::remove_dir_all(&dir);
}
@@ -115,6 +115,7 @@ fn copying_a_variant_pastes_an_instance_but_copying_its_set_keeps_the_components
let (set, _, hover) = button_set(&mut s);
ex(&mut s, "select.set", json!({"ids": [hover]}));
ex(&mut s, "edit.copy", json!({}));
ex(&mut s, "select.set", json!({"ids": []}));
let pasted = crate::params::id_of(&ex(&mut s, "edit.paste", json!({}))["ids"][0]).unwrap();
assert_eq!(component_of(&s, pasted), hover);
assert_eq!(node(&s, pasted).name, node(&s, set).name);
@@ -241,6 +242,108 @@ fn alt_dragging_a_main_component_copies_an_instance() {
healthy(&s);
}
#[test]
fn pasting_a_variant_with_its_set_selected_adds_a_variant_below_the_others() {
let mut s = Session::new();
let (set, _, hover) = button_set(&mut s);
let bounds = |s: &Session, i: NodeId| s.doc().unwrap().world_bounds(i).unwrap();
let named = |s: &Session, i: NodeId, name: &str| kids(s, i).into_iter().find(|c| node(s, *c).name == name).unwrap();
ex(&mut s, "select.set", json!({"ids": [hover]}));
ex(&mut s, "edit.copy", json!({}));
let bottom = kids(&s, set).iter().map(|k| bounds(&s, *k).y1).fold(f64::MIN, f64::max);
let pasted = crate::params::id_of(&ex(&mut s, "edit.paste", json!({}))["ids"][0]).unwrap();
assert!(matches!(node(&s, pasted).kind, NodeKind::Component { .. }));
assert_eq!(node(&s, pasted).parent, Some(set));
assert_eq!(kids(&s, set).len(), 3);
assert_eq!(chars(&s, named(&s, pasted, "Label")), "Hover");
let (b, h) = (bounds(&s, pasted), bounds(&s, hover));
assert_eq!((b.x0, b.y0), (h.x0, bottom + 20.0));
assert!(bounds(&s, set).y1 >= b.y1, "the set grows to hold it");
let label = named(&s, hover, "Label");
ex(&mut s, "select.set", json!({"ids": [label]}));
let second = crate::params::id_of(&ex(&mut s, "edit.paste", json!({}))["ids"][0]).unwrap();
assert_eq!(node(&s, second).parent, Some(set), "a layer inside a variant selected");
assert_eq!(bounds(&s, second).y0, b.y1 + 20.0);
ex(&mut s, "edit.undo", json!({}));
assert_eq!(kids(&s, set).len(), 3);
healthy(&s);
}
#[test]
fn a_variant_pasted_into_its_set_after_the_set_moved_lands_under_the_variant() {
let mut s = Session::new();
let (set, _, hover) = button_set(&mut s);
let bounds = |s: &Session, i: NodeId| s.doc().unwrap().world_bounds(i).unwrap();
ex(&mut s, "select.set", json!({"ids": [hover]}));
ex(&mut s, "edit.copy", json!({}));
let x = bounds(&s, set).x0;
ex(&mut s, "node.set", json!({"id": set, "props": {"x": x + 1000.0}}));
let pasted = crate::params::id_of(&ex(&mut s, "edit.paste", json!({}))["ids"][0]).unwrap();
let (b, h, sb) = (bounds(&s, pasted), bounds(&s, hover), bounds(&s, set));
assert_eq!(b.x0, h.x0, "under the copied variant where it is now, not where it was copied");
assert!(sb.x0 <= b.x0 && sb.x1 >= b.x1 && sb.y1 >= b.y1, "inside the set");
healthy(&s);
}
/// Copy `main`, select `selected` and run `command` with `params`; the first pasted layer.
fn copy_then(s: &mut Session, main: NodeId, selected: &[NodeId], command: &str, params: Value) -> NodeId {
ex(s, "select.set", json!({"ids": [main]}));
ex(s, "edit.copy", json!({}));
ex(s, "select.set", json!({"ids": selected}));
crate::params::id_of(&ex(s, command, params)["ids"][0]).unwrap()
}
// Only a plain paste with the copied variants' own set, or a layer in it, selected makes new
// variants. Every other paste of a copied main into a set makes an instance of it there, as
// before: the tests below.
#[test]
fn a_variant_pasted_with_another_set_selected_is_an_instance() {
let mut s = Session::new();
let (set, _, hover) = button_set(&mut s);
let (other, ..) = button_set(&mut s);
ex(&mut s, "node.set", json!({"id": other, "props": {"y": 300}}));
let pasted = copy_then(&mut s, hover, &[other], "edit.paste", json!({}));
assert_eq!(component_of(&s, pasted), hover);
assert_eq!(node(&s, pasted).parent, Some(other));
assert_eq!((kids(&s, set).len(), kids(&s, other).len()), (2, 3));
healthy(&s);
}
#[test]
fn a_main_that_is_no_variant_pasted_with_a_set_selected_is_an_instance() {
let mut s = Session::new();
let (set, ..) = button_set(&mut s);
let k = kit(&mut s);
let pasted = copy_then(&mut s, k.card, &[set], "edit.paste", json!({}));
assert_eq!(component_of(&s, pasted), k.card);
assert_eq!(node(&s, pasted).parent, Some(set));
healthy(&s);
}
#[test]
fn a_variant_pasted_with_its_own_set_as_an_explicit_parent_is_an_instance() {
let mut s = Session::new();
let (set, _, hover) = button_set(&mut s);
let pasted = copy_then(&mut s, hover, &[hover], "edit.paste", json!({"parent": set}));
assert_eq!(component_of(&s, pasted), hover);
assert_eq!(node(&s, pasted).parent, Some(set));
healthy(&s);
}
#[test]
fn pasting_over_or_replacing_a_variant_makes_an_instance_of_the_copied_variant() {
for command in ["edit.pasteOver", "edit.pasteReplace"] {
let mut s = Session::new();
let (set, default, hover) = button_set(&mut s);
let pasted = copy_then(&mut s, hover, &[default], command, json!({}));
assert_eq!(component_of(&s, pasted), hover, "{command} on a variant of the copied variant's set");
assert_eq!(node(&s, pasted).parent, Some(set), "{command}");
healthy(&s);
}
}
#[test]
fn duplicating_a_variant_adds_a_variant_to_its_set() {
let mut s = Session::new();
+20 -8
View File
@@ -83,10 +83,12 @@ pub fn normalize(doc: &mut Document, before: &Document) {
&& ((w - n.width).abs() > 1e-6 || (h - n.height).abs() > 1e-6)
{
let dw = w - n.width;
let anchor_right = keeps_right_edge(doc, before, n);
let left_share = share_of_growth_to_the_left(doc, before, n);
figcraft_layout::set_size(doc, id, w, h);
if anchor_right && let Some(n) = doc.node_mut(id) {
n.transform *= figcraft_geom::kurbo::Affine::translate((-dw, 0.0));
if left_share > 0.0
&& let Some(n) = doc.node_mut(id)
{
n.transform *= figcraft_geom::kurbo::Affine::translate((-dw * left_share, 0.0));
}
}
}
@@ -218,13 +220,23 @@ pub(crate) fn only_moved_layers(doc: &mut Document, before: &Document, touched:
out
}
/// Whether auto-width text `n` keeps its right edge when its width changes: it was already
/// right-aligned auto-width text before the edit and no auto layout flow places it.
fn keeps_right_edge(doc: &Document, before: &Document, n: &Node) -> bool {
/// How much of a width change auto-width text `n` takes on its left: all of it when right
/// aligned (it keeps its right edge), half when centred (it keeps its middle), none otherwise.
/// Only when it had the same alignment as auto-width text before the edit and no auto layout
/// flow places it.
fn share_of_growth_to_the_left(doc: &Document, before: &Document, n: &Node) -> f64 {
use figcraft_doc::{TextAlignH, TextAutoResize};
let right_auto = |n: &Node| n.kind.text().is_some_and(|t| t.align_h == TextAlignH::Right && t.auto_resize == TextAutoResize::WidthAndHeight);
let auto_width_align = |n: &Node| n.kind.text().filter(|t| t.auto_resize == TextAutoResize::WidthAndHeight).map(|t| t.align_h);
let in_flow = !n.child_layout.absolute && n.parent.and_then(|p| doc.node(p)).is_some_and(|p| p.layout.is_some() && p.kind.is_frame_like());
right_auto(n) && before.node(n.id).is_some_and(right_auto) && !in_flow
let align = auto_width_align(n);
if in_flow || align != before.node(n.id).and_then(auto_width_align) {
return 0.0;
}
match align {
Some(TextAlignH::Right) => 1.0,
Some(TextAlignH::Center) => 0.5,
_ => 0.0,
}
}
/// Whether layer `id` changed (since `before`) in a way that can move or resize layers in an auto
+26
View File
@@ -407,3 +407,29 @@ fn a_join_stopped_at_its_budget_says_so() {
let (some, complete) = crate::design_context::referenced(s.doc().unwrap(), &start, &none, 3);
assert_eq!((some.len(), complete), (3, false), "{some:?}");
}
#[test]
fn code_links_keep_their_value_names_and_carry_source_and_notes() {
let mut s = session();
let variants: Vec<_> = ["small", "extra_large"]
.iter()
.map(|v| {
let f = node(&mut s, json!({"type": "frame", "name": format!("Size={v}"), "width": 80, "height": 32}));
id(&s.execute("component.create", &json!({"ids": [f]})).unwrap())
})
.collect();
let set = id(&s.execute("component.combineVariants", &json!({"ids": variants})).unwrap());
s.execute(
"codeConnect.set",
&json!({"id": set, "name": "Button", "template": "<Button size={Size} />", "source": "src/button.tsx",
"notes": "Use for main actions", "values": {"Size": {"extra_large": "xl"}}}),
)
.unwrap();
let instance = id(&s.execute("instance.create", &json!({"component": variants[1]})).unwrap());
let v = context(&mut s, json!({"ids": [instance]}));
let link = &v["components"][set.to_string()]["codeLinks"][0];
assert_eq!(link["values"]["Size"]["extra_large"], "xl", "a design value keeps its name: {link}");
let code = &only(&v)["code"][0];
assert_eq!((code["source"].as_str(), code["notes"].as_str()), (Some("src/button.tsx"), Some("Use for main actions")), "{code}");
assert!(code["code"].as_str().unwrap().contains("xl"), "{code}");
}
+181 -16
View File
@@ -26,6 +26,11 @@ pub const MAX_TEMPLATE: usize = 4_000;
pub const MAX_NAME: usize = 100;
/// Longest import path (chars).
pub const MAX_IMPORT: usize = 300;
/// Longest source path, and notes (chars).
pub const MAX_SOURCE: usize = 300;
pub const MAX_NOTES: usize = 2_000;
/// Most properties with mapped values on a link, and values on each.
const MAX_MAPPED: usize = 100;
/// Most links a connect file holds.
pub const MAX_FILE_LINKS: usize = 5_000;
/// Largest connect file read (bytes).
@@ -377,6 +382,8 @@ fn html_text(s: &str) -> String {
/// `link`'s template with `values` (one per parameter of `c`), every line prefixed by `pad`.
pub(crate) fn render(doc: &Document, c: &Component, values: &[(String, Value)], link: &CodeLink, lang: CodeLang, pad: &str) -> String {
// A value is written as code calls it; a condition reads the design's own value.
let coded = &in_code(values, link);
let mut out = String::new();
// A quoted attribute stays open across substitutions: `title="{a} {b}"` must treat both
// placeholders as attribute values, not text after the first one.
@@ -391,7 +398,7 @@ pub(crate) fn render(doc: &Document, c: &Component, values: &[(String, Value)],
vue_attr = None;
}
}
Piece::Value { name, inner } => match find(c, values, name) {
Piece::Value { name, inner } => match find(c, coded, name) {
Some((p, v)) => {
let e = expr(doc, c, p, v, lang);
// JSX and `view!`: a plain string reads best as an attribute value, anything
@@ -454,6 +461,12 @@ pub(crate) fn render(doc: &Document, c: &Component, values: &[(String, Value)],
out.lines().map(|l| if l.is_empty() { "\n".to_string() } else { format!("{pad}{l}\n") }).collect()
}
/// `values` with each design value the link names turned into what code calls it.
fn in_code(values: &[(String, Value)], link: &CodeLink) -> Vec<(String, Value)> {
let code = |prop: &str, v: &Value| link.values.get(prop)?.get(v.as_str()?).cloned();
values.iter().map(|(prop, v)| (prop.clone(), code(prop, v).map_or_else(|| v.clone(), Value::String))).collect()
}
/// A starting template: the code component called with every property (but slots) passed.
fn default_template(c: &Component, lang: CodeLang, name: &str) -> String {
let params: Vec<&str> = c.params.iter().filter(|p| p.kind != ParamKind::Slot).map(|p| p.ident.as_str()).collect();
@@ -469,6 +482,15 @@ fn default_template(c: &Component, lang: CodeLang, name: &str) -> String {
}
}
/// Why `source` can't name a file in a code repository: it goes down from the repository's root.
fn check_source(source: &str) -> std::result::Result<(), String> {
let plain = source.chars().count() <= MAX_SOURCE
&& !source.contains('\\')
&& !source.chars().any(char::is_control)
&& std::path::Path::new(source).components().all(|c| matches!(c, std::path::Component::Normal(_) | std::path::Component::CurDir));
if plain { Ok(()) } else { Err(format!("source: a path inside the code repository, up to {MAX_SOURCE} characters")) }
}
/// Checks a link: its name, import path and template. Returns the placeholder names that aren't
/// properties of `c` (kept as written).
pub fn check(c: &Component, link: &CodeLink, lang: CodeLang) -> std::result::Result<Vec<String>, String> {
@@ -500,6 +522,14 @@ pub fn check(c: &Component, link: &CodeLink, lang: CodeLang) -> std::result::Res
_ => format!("importPath: a module or package name (letters, digits, _ and .), up to {MAX_IMPORT} characters"),
});
}
check_source(&link.source)?;
if link.notes.chars().count() > MAX_NOTES {
return Err(format!("notes: up to {MAX_NOTES} characters"));
}
let long = |s: &String| s.chars().count() > MAX_NAME;
if link.values.len() > MAX_MAPPED || link.values.values().any(|m| m.len() > MAX_MAPPED || m.iter().any(|(k, v)| long(k) || long(v))) {
return Err(format!("values: at most {MAX_MAPPED} properties of {MAX_MAPPED} values, each up to {MAX_NAME} characters"));
}
let t = &link.template;
if t.trim().is_empty() || t.chars().count() > MAX_TEMPLATE || t.chars().any(|ch| ch.is_control() && !"\n\t\r".contains(ch)) {
return Err(format!("template: the snippet, up to {MAX_TEMPLATE} characters"));
@@ -515,6 +545,12 @@ pub fn check(c: &Component, link: &CodeLink, lang: CodeLang) -> std::result::Res
unknown.push(name.to_string());
}
}
// `in_code` reads a mapping by property name, so a key that is only a parameter name does nothing.
for prop in link.values.keys() {
if !c.params.iter().any(|p| p.prop == *prop) && !unknown.iter().any(|u| u == prop) {
unknown.push(prop.clone());
}
}
Ok(unknown)
}
@@ -557,12 +593,103 @@ fn store(doc: &mut Document, owner: NodeId, link: CodeLink) -> Result<()> {
Ok(())
}
/// The variant properties of component or set `owner`, with their values.
pub fn variants(doc: &Document, owner: NodeId) -> Vec<(String, Vec<String>)> {
main_of(doc, owner)
.and_then(|m| describe(doc, m))
.map(|c| c.params.iter().filter_map(|p| if let ParamKind::Variant(v) = &p.kind { Some((p.prop.clone(), v.clone())) } else { None }).collect())
.unwrap_or_default()
}
/// A link as the connect file holds it.
fn link_json(component: &str, l: &CodeLink) -> Value {
let mut v = link_fields(l);
v["component"] = json!(component);
v
}
/// A link's own fields, as the connect file and `inspect.designContext` give them: its keys are
/// the file's, and a mapping's property names and values stay as written.
pub(crate) fn link_fields(l: &CodeLink) -> Value {
let mut v = json!({"language": l.language, "importPath": l.import_path, "name": l.name, "template": l.template});
if !l.source.is_empty() {
v["source"] = json!(l.source);
}
if !l.values.is_empty() {
v["values"] = json!(l.values);
}
if !l.notes.is_empty() {
v["notes"] = json!(l.notes);
}
v
}
/// The components and sets `ids` are, use or hold (every one in the file without `ids`).
fn listed(doc: &Document, ids: Option<&[NodeId]>) -> Vec<NodeId> {
let mut out: Vec<NodeId> = match ids {
None => doc.nodes().filter(|n| owner(doc, n.id) == Some(n.id)).map(|n| n.id).collect(),
Some(ids) => ids.iter().flat_map(|i| doc.subtree(*i)).filter_map(|i| owner(doc, i)).collect(),
};
out.sort_unstable();
out.dedup();
out
}
/// What an agent needs to use a component: its code link for each language, or that it has none.
fn entry(doc: &Document, id: NodeId, root: Option<&str>) -> Option<Value> {
let n = doc.node(id)?;
let links: Vec<Value> = n
.code_links
.iter()
.map(|l| {
let lang = CodeLang::from_id(&l.language);
let mut v = link_fields(l);
v["import"] = json!(lang.map(|k| import_line(l, k)));
v["snippet"] = json!(lang.and_then(|k| connected_code(doc, id, k, l)));
if let Some(root) = root.filter(|_| !l.source.is_empty()) {
v["sourceFound"] = json!(crate::file_access::exists(std::path::Path::new(root).join(&l.source)));
}
v
})
.collect();
Some(json!({
"id": id,
"name": n.name,
"type": n.kind.type_name(),
"mapped": !links.is_empty(),
"properties": crate::cmd::component::describe_props(doc, id)["properties"],
"links": links,
}))
}
fn list(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "codeConnect.list";
let doc = s.doc()?;
// Anything named must be layers; nothing named lists every component in the file.
let named = get(p, "ids").is_some() || get(p, "id").is_some();
let ids = if named { Some(crate::params::req_targets(cmd, s, p)?) } else { None };
let root = text(cmd, p, "root")?;
let unmapped = crate::params::boolean(p, "unmapped").unwrap_or(false);
let all: Vec<Value> = listed(doc, ids.as_deref()).into_iter().filter_map(|id| entry(doc, id, root.as_deref())).collect();
let count = |m: bool| all.iter().filter(|e| e["mapped"] == m).count();
let (mapped, missing) = (count(true), count(false));
let components: Vec<Value> = all.into_iter().filter(|e| !unmapped || e["mapped"] == false).collect();
Ok(json!({"components": components, "mapped": mapped, "unmapped": missing}))
}
pub fn specs() -> Vec<CommandSpec> {
vec![
spec!(
"codeConnect.list",
"List code connections",
"{ids? | id? (the components those layers are, use or hold; default every component in the file), unmapped? (only those without a link), root? (the code repository: says if each link's source is there)} → {components: [{id, name, type, mapped, properties, links: [{language, importPath, import, name, template, snippet, source?, sourceFound?, values?, notes?}]}], mapped, unmapped}",
false,
list
),
spec!(
"codeConnect.set",
"Connect to code",
"{id? (component, set or instance; default the selection), language?: react|leptos|vue|swiftui|compose|arkui|flutter (default react), importPath?, name? (default the generated name), template? (default a call passing every property)} links the component (its set, for a variant) to its code component; fields left out keep their current value. Placeholders: {property} (its name or parameter name) and {property ? \"a\" : \"b\"}; other {…} stay as written → {component, language, code (the snippet for the layer), unknown (placeholder names that aren't properties)}",
"{id? (component, set or instance; default the selection), language?: react|leptos|vue|swiftui|compose|arkui|flutter (default react), importPath?, name? (default the generated name), template? (default a call passing every property), source? (the file, relative to the code repository), values? ({property: {design value: code value}}), notes?} links the component (its set, for a variant) to its code component; fields left out keep their current value. Placeholders: {property} (its name or parameter name) and {property ? \"a\" : \"b\"}; other {…} stay as written → {component, language, code (the snippet for the layer), unknown (placeholder names that aren't properties)}",
true,
|s, p| {
let cmd = "codeConnect.set";
@@ -578,7 +705,13 @@ pub fn specs() -> Vec<CommandSpec> {
None => old.template,
};
let import_path = text(cmd, p, "importPath")?.map_or(old.import_path, |i| i.trim().to_string());
let link = CodeLink { language: lang.id().into(), import_path, name, template };
let source = text(cmd, p, "source")?.map_or(old.source, |v| v.trim().to_string());
let notes = text(cmd, p, "notes")?.unwrap_or(old.notes);
let values = match get(p, "values") {
None => old.values,
Some(v) => serde_json::from_value(v.clone()).map_err(|_| bad(cmd, "values: {property: {design value: code value}}"))?,
};
let link = CodeLink { language: lang.id().into(), import_path, name, template, source, values, notes };
let unknown = check(&c, &link, lang).map_err(|e| bad(cmd, e))?;
let code = connected_code(doc, id, lang, &link);
store(s.doc_mut()?, owner, link)?;
@@ -610,27 +743,34 @@ pub fn specs() -> Vec<CommandSpec> {
spec!(
"codeConnect.export",
"Export code connections",
"{path? (write it there, e.g. figcraft.connect.json in the code repository)} every component's links as {version: 1, links: [{component (its name), language, importPath, name, template}]}, sorted → {text, links} or {path, links}",
"{path? (write it there, e.g. figcraft.connect.json in the code repository; other top-level keys of a file already there stay, and so do the links of components this file doesn't have; a file there it can't read is left alone and the export refused)} every component's links as {version: 1, links: [{component (its name), language, importPath, name, template, source?, values?, notes?}]}, sorted → {text, links} or {path, links}",
false,
|s, p| {
let cmd = "codeConnect.export";
let path = text(cmd, p, "path")?;
let doc = s.doc()?;
let mut links: Vec<Value> = doc
.nodes()
.filter(|n| owner(doc, n.id) == Some(n.id))
.flat_map(|n| {
n.code_links.iter().map(|l| {
json!({"component": n.name, "language": l.language, "importPath": l.import_path, "name": l.name, "template": l.template})
})
})
.collect();
let mut links: Vec<Value> =
doc.nodes().filter(|n| owner(doc, n.id) == Some(n.id)).flat_map(|n| n.code_links.iter().map(|l| link_json(&n.name, l))).collect();
let key =
|v: &Value| (v["component"].as_str().unwrap_or_default().to_string(), v["language"].as_str().unwrap_or_default().to_string());
links.sort_by_key(key);
let count = links.len();
let text =
serde_json::to_string_pretty(&json!({"version": VERSION, "links": links})).map_err(|e| EngineError::Other(e.to_string()))? + "\n";
// The file also holds the project's settings and the links of other designs: only
// the links of this file's components are this command's.
let old = match path.as_deref() {
Some(path) => kept_keys(cmd, path)?,
None => serde_json::Map::new(),
};
let here: Vec<&str> = doc.nodes().filter(|n| owner(doc, n.id) == Some(n.id)).map(|n| n.name.as_str()).collect();
let others = old.get("links").and_then(Value::as_array).map(Vec::as_slice).unwrap_or_default();
links.extend(others.iter().filter(|l| !l.get("component").and_then(Value::as_str).is_some_and(|c| here.contains(&c))).cloned());
links.sort_by_key(key);
let mut file = json!({"version": VERSION, "links": links});
if let Some(fields) = file.as_object_mut() {
for (k, v) in old {
fields.entry(k).or_insert(v);
}
}
let text = serde_json::to_string_pretty(&file).map_err(|e| EngineError::Other(e.to_string()))? + "\n";
match path {
Some(path) => {
crate::cmd::file::write(&path, text.as_bytes())?;
@@ -650,6 +790,18 @@ pub fn specs() -> Vec<CommandSpec> {
]
}
/// The top-level keys of the connect file at `path`, none when there is no file. A file that
/// can't be read as one is an error: writing over it would lose what it holds.
fn kept_keys(cmd: &str, path: &str) -> Result<serde_json::Map<String, Value>> {
if !crate::file_access::exists(path) {
return Ok(serde_json::Map::new());
}
match serde_json::from_slice(&crate::cmd::file::read_capped(path, MAX_FILE)?) {
Ok(Value::Object(fields)) => Ok(fields),
_ => Err(bad(cmd, format!("{path} isn't a connect file it can read, so it was left as it is"))),
}
}
fn import(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "codeConnect.import";
let parse_json = |b: &[u8]| serde_json::from_slice::<Value>(b).map_err(|e| bad(cmd, format!("not JSON: {e}")));
@@ -688,11 +840,24 @@ fn import(s: &mut Session, p: &Value) -> Result<Value> {
));
continue;
};
let values = match e.get("values") {
None | Some(Value::Null) => Default::default(),
Some(v) => match serde_json::from_value(v.clone()) {
Ok(values) => values,
Err(_) => {
warnings.push(format!("link {}: values: {{property: {{design value: code value}}}}, all strings", i + 1));
continue;
}
},
};
let link = CodeLink {
language: lang.id().into(),
import_path: field("importPath").unwrap_or_default().to_string(),
name: name.into(),
template: template.into(),
source: field("source").unwrap_or_default().to_string(),
values,
notes: field("notes").unwrap_or_default().to_string(),
};
let matches = owners.get(component).cloned().unwrap_or_default();
if matches.is_empty() {
+1 -1
View File
@@ -651,7 +651,7 @@ mod tests {
let badge = id_of(
&s.execute(
"vector.create",
&json!({"path": "M0 0 H24 V24 H0 Z", "name": "badge", "props": {"fill": "none", "stroke": "#1F3A68", "strokeWeight": 2}}),
&json!({"path": "M0 0 H24 V24 H0 Z", "name": "badge", "props": {"fill": "none", "stroke": "#1F3A68", "strokeWeight": 4}}),
)
.unwrap()["id"],
)
+9 -2
View File
@@ -178,7 +178,14 @@ fn code(doc: &Document, id: NodeId) -> Vec<Value> {
.filter_map(|l| {
let lang = CodeLang::from_id(&l.language)?;
let snippet = code_connect::connected_code(doc, id, lang, l)?;
Some(json!({"language": l.language, "importPath": l.import_path, "name": l.name, "code": snippet}))
// The snippet already holds the template and the values it maps.
let mut v = code_connect::link_fields(l);
if let Some(o) = v.as_object_mut() {
o.remove("template");
o.remove("values");
}
v["code"] = json!(snippet);
Some(v)
})
.collect()
}
@@ -355,7 +362,7 @@ fn components_json(doc: &Document, ids: &BTreeSet<NodeId>) -> Value {
v["description"] = json!(description);
}
if !n.code_links.is_empty() {
v["codeLinks"] = camel(serde_json::to_value(&n.code_links).unwrap_or(Value::Null));
v["codeLinks"] = json!(n.code_links.iter().map(code_connect::link_fields).collect::<Vec<_>>());
}
out.insert(id.to_string(), v);
}
+27
View File
@@ -119,6 +119,9 @@ pub struct DocState {
/// Where each page's view was left in this session (its centre and zoom; see
/// [`Self::open_page`]; not saved).
page_views: BTreeMap<NodeId, (f64, f64, f64)>,
/// The canvas fits the page's content when it first gets its size. Off when the view was
/// restored from where the file was left ([`Session::restore_view`]).
pub fit_when_sized: bool,
}
/// A version shown on the canvas in place of the document: read-only until it's restored or the
@@ -184,6 +187,7 @@ impl DocState {
images_left_in_file: None,
on_disk: None,
page_views: BTreeMap::new(),
fit_when_sized: true,
};
st.zoom_to_fit();
st
@@ -332,6 +336,29 @@ impl DocState {
}
}
/// Each page's view as left: the one shown now at its current view, the others shown in this
/// session at theirs.
pub(crate) fn page_views(&self) -> impl Iterator<Item = (NodeId, (f64, f64, f64))> + '_ {
let shown = (self.page, (self.view.cx, self.view.cy, self.view.zoom));
self.page_views.iter().filter(|(p, _)| **p != self.page).map(|(p, v)| (*p, *v)).chain(std::iter::once(shown))
}
/// Take `views` as where their pages were left, and show `page` (or the page shown now) at
/// its view. With one, the canvas keeps it instead of fitting the page when it gets its size.
pub(crate) fn show_views(&mut self, page: Option<NodeId>, views: impl IntoIterator<Item = (NodeId, (f64, f64, f64))>) {
self.page_views.extend(views);
if let Some(page) = page {
self.page = page;
}
match self.page_views.get(&self.page) {
Some(&(cx, cy, zoom)) => {
(self.view.cx, self.view.cy, self.view.zoom) = (cx, cy, zoom);
self.fit_when_sized = false;
}
None => self.zoom_to_fit(),
}
}
pub fn zoom_to_fit(&mut self) {
match self.doc.page_content_bounds(self.page) {
Some(b) => self.view.fit(b, 1.0),
@@ -0,0 +1,58 @@
use figcraft_doc::NodeId;
use serde_json::json;
use crate::Session;
use crate::tools::{PointerEvent, PointerKind};
fn rect(s: &mut Session, x: f64, props: serde_json::Value) -> NodeId {
let r = s.execute("shape.rectangle", &json!({"x": x, "y": 0, "width": 100, "height": 100, "props": props})).unwrap();
crate::params::id_of(&r["id"]).unwrap()
}
fn hex(paints: &[figcraft_color::Paint]) -> Vec<String> {
paints.iter().map(|p| p.solid_color().map(|c| c.to_hex()).unwrap_or_default()).collect()
}
fn pick_red_onto(s: &mut Session, ids: &[NodeId]) {
s.execute("select.set", &json!({"ids": ids})).unwrap();
s.execute("edit.pickColor", &json!({})).unwrap();
s.pointer(&PointerEvent::at(PointerKind::Down, 50.0, 50.0, 1.0)).unwrap();
}
fn scene() -> Session {
let mut s = Session::new();
s.execute("page.setBackground", &json!({"color": "#FFFFFF"})).unwrap();
rect(&mut s, 0.0, json!({"fills": ["#FF0000"]}));
s
}
#[test]
fn a_layer_with_only_a_stroke_takes_the_pick_on_its_stroke() {
let mut s = scene();
let outline = rect(&mut s, 200.0, json!({"fills": [], "strokes": ["#0000FF"], "strokeWeight": 2}));
pick_red_onto(&mut s, &[outline]);
let n = s.doc().unwrap().node(outline).unwrap().clone();
assert!(n.fills.is_empty(), "no fill appears: {:?}", n.fills);
assert_eq!(hex(&n.strokes), ["FF0000"]);
assert_eq!(n.stroke.weight, 2.0, "the stroke keeps its weight");
}
#[test]
fn a_hidden_fill_counts_as_none_and_a_visible_one_takes_the_pick() {
let mut s = scene();
let hidden = rect(&mut s, 200.0, json!({"fills": [{"type": "solid", "color": "#00FF00", "visible": false}], "strokes": ["#0000FF"]}));
let filled = rect(&mut s, 400.0, json!({"fills": ["#00FF00"], "strokes": ["#0000FF"]}));
let bare = rect(&mut s, 600.0, json!({"fills": [], "strokes": []}));
let undo = s.undo_depth().0;
pick_red_onto(&mut s, &[hidden, filled, bare]);
let d = s.doc().unwrap();
let (h, f, b) = (d.node(hidden).unwrap(), d.node(filled).unwrap(), d.node(bare).unwrap());
assert_eq!((hex(&h.strokes), h.fills.iter().any(|p| p.visible)), (vec!["FF0000".to_string()], false));
assert_eq!((hex(&f.fills), hex(&f.strokes)), (vec!["FF0000".to_string()], vec!["0000FF".to_string()]));
assert_eq!(hex(&b.fills), ["FF0000"], "with neither, the fill as before");
assert_eq!(s.undo_depth().0, undo + 1, "one step for the whole selection");
s.execute("edit.undo", &json!({})).unwrap();
let d = s.doc().unwrap();
assert_eq!(hex(&d.node(hidden).unwrap().strokes), ["0000FF"]);
assert_eq!(hex(&d.node(filled).unwrap().fills), ["00FF00"]);
}
+74
View File
@@ -0,0 +1,74 @@
//! Files open again where they were left: when a file's tab closes or the app quits, the page it
//! showed and each page's view (its centre and zoom) are kept for that file, and opening it again
//! shows them, as Figma opens a file where you were. They live in the preferences, not in the
//! file, so looking around never changes a file.
use serde::{Deserialize, Serialize};
use crate::{NodeId, Session, ViewState};
/// How many files' views are kept, the most recently left first.
pub const MAX_FILE_VIEWS: usize = 100;
/// Where a file was left.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct FileView {
pub path: String,
/// The page shown.
pub page: NodeId,
/// The view of each page shown while it was open.
pub pages: Vec<PageView>,
}
/// A page's view: the page point at the canvas's centre, and the zoom.
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
pub struct PageView {
pub page: NodeId,
pub cx: f64,
pub cy: f64,
pub zoom: f64,
}
impl Session {
/// Keep where tab `i`'s file is left. A tab without a file of its own (a new or imported file,
/// a branch) keeps nothing.
pub(crate) fn remember_view(&mut self, i: usize) {
let Some(ds) = self.docs.get(i).filter(|d| d.branch_of.is_none()) else { return };
let Some(path) = ds.path.clone() else { return };
let pages = ds.page_views().map(|(page, (cx, cy, zoom))| PageView { page, cx, cy, zoom }).collect();
let view = FileView { path, page: ds.page, pages };
let views = &mut self.prefs.file_views;
views.retain(|v| v.path != view.path);
views.insert(0, view);
views.truncate(MAX_FILE_VIEWS);
self.prefs_unsaved = true;
}
/// [`remember_view`](Self::remember_view) for every open tab, before the app quits.
pub fn remember_views(&mut self) {
for i in 0..self.docs.len() {
self.remember_view(i);
}
}
/// Show the active tab's file where it was left, if it was: its page, if the file still has
/// it as a page that isn't a divider, at its view, and each other page at its view when it is
/// shown. A view that isn't a finite centre with a zoom the canvas takes is left out.
pub(crate) fn restore_view(&mut self) {
let Ok(ds) = self.ds() else { return };
let Some(kept) = ds.path.as_deref().and_then(|p| self.prefs.file_views.iter().find(|v| v.path == p)).cloned() else { return };
let Ok(ds) = self.ds_mut() else { return };
let doc = ds.doc.clone();
let views = kept
.pages
.iter()
.filter(|v| doc.pages.contains(&v.page) && [v.cx, v.cy, v.zoom].iter().all(|x| x.is_finite()))
.filter(|v| (ViewState::MIN_ZOOM..=ViewState::MAX_ZOOM).contains(&v.zoom))
.map(|v| (v.page, (v.cx, v.cy, v.zoom)));
let page = Some(kept.page).filter(|p| doc.pages.contains(p) && !doc.is_divider(*p));
ds.show_views(page, views);
}
}
#[cfg(test)]
mod tests;
+136
View File
@@ -0,0 +1,136 @@
//! Files open again where they were left.
use serde_json::{Value, json};
use super::*;
fn ex(s: &mut Session, cmd: &str, p: Value) -> Value {
s.execute(cmd, &p).unwrap_or_else(|e| panic!("{cmd} {p}: {e}"))
}
/// A test's folder, removed when the test ends, a failing one too.
struct Dir(std::path::PathBuf);
impl std::ops::Deref for Dir {
type Target = std::path::Path;
fn deref(&self) -> &std::path::Path {
&self.0
}
}
impl Drop for Dir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
fn dir(name: &str) -> Dir {
let d = std::env::temp_dir().join(format!("figcraft-file-views-{}-{name}", std::process::id()));
std::fs::create_dir_all(&d).unwrap();
Dir(d)
}
/// A saved file at `path` with two pages, each holding a rectangle, the first page shown.
fn two_pages(s: &mut Session, path: &str) -> (NodeId, NodeId) {
ex(s, "file.new", json!({}));
ex(s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 100, "height": 100}));
ex(s, "page.add", json!({"name": "Second"}));
let pages = s.doc().unwrap().pages.clone();
ex(s, "page.select", json!({"id": pages[1].0}));
ex(s, "shape.rectangle", json!({"x": 2000, "y": 2000, "width": 50, "height": 50}));
ex(s, "page.select", json!({"id": pages[0].0}));
ex(s, "file.saveAs", json!({"path": path}));
(pages[0], pages[1])
}
fn view(s: &Session) -> (NodeId, f64, f64, f64) {
let ds = s.ds().unwrap();
(ds.page, ds.view.cx, ds.view.cy, ds.view.zoom)
}
fn look(s: &mut Session, cx: f64, cy: f64, zoom: f64) {
let v = &mut s.ds_mut().unwrap().view;
(v.cx, v.cy, v.zoom) = (cx, cy, zoom);
}
/// Closed and opened again, a file shows the page it showed, at its view, and its other page at
/// the view that page was left at; looking around leaves the file unchanged.
#[test]
fn a_file_opens_again_where_it_was_left() {
let d = dir("left");
let path = d.join("two.figcraft").to_string_lossy().into_owned();
let mut s = Session::new();
let (first, second) = two_pages(&mut s, &path);
let saved = std::fs::read(&path).unwrap();
look(&mut s, 40.0, 60.0, 2.5);
ex(&mut s, "page.select", json!({"id": second.0}));
look(&mut s, 2010.0, 2020.0, 0.5);
assert!(!s.ds().unwrap().is_dirty(), "looking around is no change to the file");
ex(&mut s, "file.close", json!({}));
assert_eq!(std::fs::read(&path).unwrap(), saved, "nothing written to the file");
assert!(s.prefs_unsaved, "kept in the preferences");
ex(&mut s, "file.open", json!({"path": path}));
assert_eq!(view(&s), (second, 2010.0, 2020.0, 0.5));
assert!(!s.ds().unwrap().fit_when_sized, "the canvas keeps the view instead of fitting");
ex(&mut s, "page.select", json!({"id": first.0}));
assert_eq!(view(&s), (first, 40.0, 60.0, 2.5));
// Through the preferences file, as the next start reads them.
let prefs: crate::Prefs = serde_json::from_value(serde_json::to_value(&s.prefs).unwrap()).unwrap();
let mut next = Session::new();
next.prefs = prefs;
ex(&mut next, "file.open", json!({"path": path}));
assert_eq!(view(&next), (second, 2010.0, 2020.0, 0.5));
}
/// Quitting keeps every open file's view; a file never saved keeps none.
#[test]
fn quitting_keeps_each_open_files_view() {
let d = dir("quit");
let (a, b) = (d.join("a.figcraft").to_string_lossy().into_owned(), d.join("b.figcraft").to_string_lossy().into_owned());
let mut s = Session::new();
let (a_page, _) = two_pages(&mut s, &a);
look(&mut s, 1.0, 2.0, 3.0);
let (b_page, _) = two_pages(&mut s, &b);
look(&mut s, 4.0, 5.0, 0.25);
ex(&mut s, "file.new", json!({}));
s.remember_views();
let kept: Vec<&str> = s.prefs.file_views.iter().map(|v| v.path.as_str()).collect();
assert_eq!(kept.len(), 2, "{kept:?}");
let mut next = Session::new();
next.prefs = s.prefs.clone();
ex(&mut next, "file.open", json!({"path": a}));
assert_eq!(view(&next), (a_page, 1.0, 2.0, 3.0));
ex(&mut next, "file.open", json!({"path": b}));
assert_eq!(view(&next), (b_page, 4.0, 5.0, 0.25));
}
/// A kept page the file no longer has, or a view the canvas can't show, is left out: the file
/// opens fitted as before.
#[test]
fn a_view_that_no_longer_fits_the_file_is_left_out() {
let d = dir("stale");
let path = d.join("one.figcraft").to_string_lossy().into_owned();
let mut s = Session::new();
let (first, _) = two_pages(&mut s, &path);
ex(&mut s, "file.close", json!({}));
s.prefs.file_views[0].page = NodeId(999_999);
s.prefs.file_views[0].pages = vec![PageView { page: first, cx: f64::NAN, cy: 0.0, zoom: 1.0 }];
ex(&mut s, "file.open", json!({"path": path}));
let ds = s.ds().unwrap();
assert_eq!(ds.page, first);
assert!(ds.fit_when_sized, "fitted as a file never left");
assert!(ds.view.cx.is_finite());
}
/// The views kept are bounded, the most recently left first.
#[test]
fn the_most_recently_left_files_are_kept() {
let mut s = Session::new();
for k in 0..MAX_FILE_VIEWS + 5 {
ex(&mut s, "file.new", json!({}));
s.ds_mut().unwrap().path = Some(format!("/nowhere/{k}.figcraft"));
ex(&mut s, "file.close", json!({"force": true}));
}
assert_eq!(s.prefs.file_views.len(), MAX_FILE_VIEWS);
assert_eq!(s.prefs.file_views[0].path, format!("/nowhere/{}.figcraft", MAX_FILE_VIEWS + 4));
}
@@ -188,6 +188,7 @@ fn frame_selection_wraps_the_layers_where_the_topmost_was() {
assert_eq!(doc.node(page).unwrap().children, vec![other, f, top], "where b (the topmost selected) was");
assert_eq!((wb(&s, a), wb(&s, b)), ((10.0, 10.0, 20.0, 20.0), (50.0, 40.0, 30.0, 30.0)));
assert_eq!(s.selection(), vec![f]);
assert!(doc.node(f).unwrap().fills.is_empty(), "no fill over what it frames: {:?}", doc.node(f).unwrap().fills);
// Inside a frame, the new frame nests there.
let outer = frame(&mut s, 500.0, 0.0, 200.0, 200.0, None);
let c = rect(&mut s, 20.0, 20.0, 10.0, 10.0, Some(outer));
+1
View File
@@ -368,6 +368,7 @@ pub static GESTURES: &[(Group, &str, &str, &str)] = &[
(Selection, "Pick select: next or previous layer", "⇥ / ⇧⇥", "Tab / Shift+Tab"),
(Selection, "Pick select: into a layer, out to its parent", "↵ / ⇧↵", "Enter / Shift+Enter"),
(Selection, "Pick select: select the picked layer", "Space", "Space"),
(Text, "While editing text: next or previous text layer", "⇥ / ⇧⇥", "Tab / Shift+Tab"),
(Edit, "Duplicate by dragging", "⌥ drag", "Alt+drag"),
(Transform, "Nudge (Shift: big nudge)", "← ↑ → ↓", "← ↑ → ↓"),
(Transform, "Resize by the nudge amount", "⌘ arrows", "Ctrl+arrows"),
+17
View File
@@ -107,13 +107,16 @@ use serde_json::{Value, json};
mod derived;
mod doc_state;
mod error;
mod file_views;
mod prefs;
mod reopen;
mod session;
mod view_state;
pub use derived::{changed_nodes, normalize};
pub use doc_state::{DocState, History, HistoryEntry, Interaction, PREVIEW_READ_ONLY, Preedit, TextEdit, VersionPreview};
pub use error::{EngineError, Result, bad};
pub use file_views::{FileView, MAX_FILE_VIEWS, PageView};
pub use prefs::{Clipboard, DefaultProps, MAX_RECENT_ACTIONS, Prefs, UI_SCALE_MAX, UI_SCALE_MIN, UI_SCALE_SIZES, UiRequest, clamp_ui_scale};
pub use session::Forward;
pub use view_state::ViewState;
@@ -339,6 +342,8 @@ mod eyedropper_create_tests;
#[cfg(test)]
mod eyedropper_image_tests;
#[cfg(test)]
mod eyedropper_stroke_tests;
#[cfg(test)]
mod facilitate_tests;
#[cfg(test)]
mod fig_export_assets_tests;
@@ -489,6 +494,8 @@ mod panels_behaviour_tests;
#[cfg(test)]
mod paste_missing_image_tests;
#[cfg(test)]
mod paste_over_tests;
#[cfg(test)]
mod paste_sibling_tests;
#[cfg(test)]
mod path_read_caps_tests;
@@ -549,6 +556,8 @@ mod proto_run_tests;
#[cfg(test)]
mod proto_tail_tests;
#[cfg(test)]
mod reopen_tests;
#[cfg(test)]
mod rest_slot_tests;
#[cfg(test)]
mod retained_walk_tests;
@@ -571,6 +580,8 @@ mod scaled_instance_tests;
#[cfg(test)]
mod section_contents_tests;
#[cfg(test)]
mod section_marquee_tests;
#[cfg(test)]
mod section_tests;
#[cfg(test)]
mod select_area_tests;
@@ -587,6 +598,8 @@ mod shapebuilder_tests;
#[cfg(test)]
mod shapes_behaviour_tests;
#[cfg(test)]
mod shift_double_click_tests;
#[cfg(test)]
mod shortcut_parity_tests;
#[cfg(test)]
mod sketch_import_tests;
@@ -625,6 +638,8 @@ mod text_motion_tests;
#[cfg(test)]
mod text_style_picker_tests;
#[cfg(test)]
mod text_tab_tests;
#[cfg(test)]
mod text_tail_tests;
#[cfg(test)]
mod text_weight_step_tests;
@@ -698,6 +713,8 @@ mod export_bounds_tests;
#[cfg(test)]
mod page_view_tests;
#[cfg(test)]
mod paste_properties_tests;
#[cfg(test)]
mod selection_reorder_tests;
#[cfg(test)]
mod selection_spacing_tests;
+95
View File
@@ -0,0 +1,95 @@
//! Shift+Cmd/Ctrl+V with several layers selected pastes after the last of them as seen.
use serde_json::{Value, json};
use crate::Session;
use crate::params::id_of;
use figcraft_doc::NodeId;
fn id(v: &Value) -> NodeId {
id_of(&v["id"]).unwrap()
}
fn frame(s: &mut Session, x: f64, y: f64) -> NodeId {
id(&s.execute("frame.create", &json!({"x": x, "y": y, "width": 200, "height": 100})).unwrap())
}
fn kids(s: &Session, parent: NodeId) -> Vec<NodeId> {
s.doc().unwrap().node(parent).unwrap().children.clone()
}
fn paste_over(s: &mut Session, sel: Vec<NodeId>) -> Vec<NodeId> {
s.set_selection(sel);
s.execute("edit.pasteOver", &json!({})).unwrap()["ids"].as_array().unwrap().iter().filter_map(id_of).collect()
}
fn top_left(s: &Session, n: NodeId) -> (f64, f64) {
let b = s.doc().unwrap().world_bounds(n).unwrap();
(b.x0, b.y0)
}
#[test]
fn several_rows_of_an_auto_layout_selected_get_the_copy_after_the_last_row() {
let mut s = Session::new();
let rows: Vec<NodeId> =
(0..4).map(|k| id(&s.execute("shape.rectangle", &json!({"x": 0, "y": k * 30, "width": 40, "height": 20})).unwrap())).collect();
let r = s.execute("layout.add", &json!({"ids": rows, "direction": "vertical"})).unwrap();
let list = id_of(&r["ids"][0]).unwrap();
assert_eq!(kids(&s, list), rows);
s.execute("edit.copy", &json!({"ids": [rows[0]]})).unwrap();
// Clicked from the middle down and back: the click order isn't the order on screen.
let pasted = paste_over(&mut s, vec![rows[1], rows[3], rows[2]]);
assert_eq!(pasted.len(), 1);
assert_eq!(kids(&s, list), vec![rows[0], rows[1], rows[2], rows[3], pasted[0]], "after the last selected row");
assert_eq!(s.selection(), pasted);
}
#[test]
fn several_artboards_in_a_column_get_the_copy_below_the_lowest_with_their_gap() {
let mut s = Session::new();
let (a, b, c) = (frame(&mut s, 0.0, 0.0), frame(&mut s, 0.0, 140.0), frame(&mut s, 0.0, 280.0));
let source = frame(&mut s, 1000.0, 0.0);
s.execute("edit.copy", &json!({"ids": [source]})).unwrap();
let pasted = paste_over(&mut s, vec![a, c, b]);
assert_eq!(pasted.len(), 1);
assert_eq!(top_left(&s, pasted[0]), (0.0, 420.0), "below the lowest artboard, 40 below it like the others");
let page = s.doc().unwrap().node(c).unwrap().parent.unwrap();
let order = kids(&s, page);
let at = |n: NodeId| order.iter().position(|i| *i == n).unwrap();
assert_eq!(at(pasted[0]), at(c) + 1, "just above the lowest artboard");
}
#[test]
fn several_artboards_in_a_row_get_the_copy_right_of_the_rightmost_with_their_gap() {
let mut s = Session::new();
let (a, b, c) = (frame(&mut s, 0.0, 0.0), frame(&mut s, 260.0, 0.0), frame(&mut s, 520.0, 0.0));
let source = frame(&mut s, 0.0, 1000.0);
s.execute("edit.copy", &json!({"ids": [source]})).unwrap();
let pasted = paste_over(&mut s, vec![b, a, c]);
assert_eq!(top_left(&s, pasted[0]), (780.0, 0.0), "right of the rightmost, 60 from it like the others");
}
#[test]
fn several_overlapping_layers_get_the_copy_right_under_the_lowest() {
let mut s = Session::new();
let (a, b) = (frame(&mut s, 0.0, 0.0), frame(&mut s, 50.0, 30.0));
let source = frame(&mut s, 1000.0, 0.0);
s.execute("edit.copy", &json!({"ids": [source]})).unwrap();
let pasted = paste_over(&mut s, vec![b, a]);
assert_eq!(top_left(&s, pasted[0]), (50.0, 130.0));
}
#[test]
fn several_absolute_layers_of_an_auto_layout_get_the_copy_below_the_lowest() {
let mut s = Session::new();
let rows: Vec<NodeId> =
(0..3).map(|k| id(&s.execute("shape.rectangle", &json!({"x": 0, "y": k * 30, "width": 40, "height": 20})).unwrap())).collect();
s.execute("layout.add", &json!({"ids": rows, "direction": "vertical"})).unwrap();
s.execute("node.set", &json!({"ids": rows, "props": {"absolute": true}})).unwrap();
s.execute("edit.copy", &json!({"ids": [rows[0]]})).unwrap();
let (x, y0) = top_left(&s, rows[1]);
let (_, y1) = top_left(&s, rows[2]);
let pasted = paste_over(&mut s, vec![rows[2], rows[0], rows[1]]);
assert_eq!(pasted.len(), 1);
assert_eq!(top_left(&s, pasted[0]), (x, y1 + 20.0 + (y1 - y0 - 20.0)), "the layout doesn't place them, so below the lowest");
}
+116
View File
@@ -0,0 +1,116 @@
//! Copy properties and Paste properties (Alt+Cmd/Ctrl+C and V) carry what a layer's look comes
//! from as well as its values: its colour, effect and grid styles, the variables bound to what is
//! copied and a frame's layout grids. A link the file pasted into doesn't have is left out.
use figcraft_doc::{LayoutGrid, NodeId};
use serde_json::{Value, json};
use crate::Session;
fn id(v: Value) -> NodeId {
NodeId(v["id"].as_u64().unwrap())
}
fn frame(s: &mut Session, x: f64) -> NodeId {
id(s.execute("frame.create", &json!({"x": x, "y": 0, "width": 100, "height": 100})).unwrap())
}
fn copy_onto(s: &mut Session, from: NodeId, to: NodeId) {
s.execute("edit.copyProperties", &json!({"id": from})).unwrap();
s.execute("edit.pasteProperties", &json!({"ids": [to]})).unwrap();
}
#[test]
fn a_frame_pastes_its_styles_variables_and_layout_grids() {
let mut s = Session::new();
let (a, b, c) = (frame(&mut s, 0.0), frame(&mut s, 200.0), frame(&mut s, 400.0));
s.execute("variable.createCollection", &json!({"name": "Tokens"})).unwrap();
for (name, value) in [("surface", "#FF0000"), ("other", "#0000FF")] {
s.execute("variable.create", &json!({"collection": "Tokens", "name": name, "type": "color", "value": value})).unwrap();
}
s.execute("variable.create", &json!({"collection": "Tokens", "name": "radius", "type": "number", "value": 16})).unwrap();
s.execute("variable.bind", &json!({"ids": [a], "field": "fills/0/color", "variable": "surface"})).unwrap();
s.execute("variable.bind", &json!({"ids": [a], "field": "cornerRadius", "variable": "radius"})).unwrap();
s.execute("node.set", &json!({"ids": [a], "props": {"grids": [serde_json::to_value(LayoutGrid::default()).unwrap()]}})).unwrap();
// B is bound to another colour, which the paste replaces.
s.execute("variable.bind", &json!({"ids": [b], "field": "fills/0/color", "variable": "other"})).unwrap();
let shadow = s.execute("style.create", &json!({"type": "effect", "name": "Shadow", "value": [{"type": "dropShadow"}]})).unwrap()["id"].clone();
let green = s.execute("style.create", &json!({"type": "paint", "name": "Green", "value": "#00FF00"})).unwrap()["id"].clone();
s.execute("style.apply", &json!({"ids": [c], "style": green})).unwrap();
s.execute("style.apply", &json!({"ids": [c], "style": shadow})).unwrap();
copy_onto(&mut s, a, b);
let (na, nb) = (s.doc().unwrap().node(a).unwrap().clone(), s.doc().unwrap().node(b).unwrap().clone());
assert_eq!(nb.bound.get("fills/0/color"), na.bound.get("fills/0/color"), "the fill follows the same variable");
assert_eq!(nb.bound.get("cornerRadius"), na.bound.get("cornerRadius"), "and so do the corners");
assert_eq!(nb.corners.radii, [16.0; 4]);
assert_eq!(nb.grids, na.grids, "a frame's layout grids come along");
copy_onto(&mut s, c, a);
let (na, nc) = (s.doc().unwrap().node(a).unwrap().clone(), s.doc().unwrap().node(c).unwrap().clone());
assert_eq!(na.styles.fill, nc.styles.fill, "the fill style is linked");
assert!(nc.styles.effect.is_some() && na.styles.effect == nc.styles.effect, "the effect style too");
assert!(!na.bound.contains_key("fills/0/color"), "the style replaces the fill's variable");
assert!(!na.bound.contains_key("cornerRadius"), "C's corners aren't bound, so A's aren't any more");
assert!(na.grids.is_empty(), "nor has it layout grids");
assert_eq!(na.fills, nc.fills);
}
#[test]
fn links_another_file_lacks_paste_as_values() {
let mut s = Session::new();
let a = frame(&mut s, 0.0);
s.execute("variable.createCollection", &json!({"name": "Tokens"})).unwrap();
s.execute("variable.create", &json!({"collection": "Tokens", "name": "surface", "type": "color", "value": "#FF0000"})).unwrap();
s.execute("variable.bind", &json!({"ids": [a], "field": "fills/0/color", "variable": "surface"})).unwrap();
let st = s.execute("style.create", &json!({"type": "paint", "name": "Line", "value": "#00FF00"})).unwrap()["id"].clone();
s.execute("node.set", &json!({"ids": [a], "props": {"strokes": [{"type": "solid", "color": "#000000"}]}})).unwrap();
s.execute("style.apply", &json!({"ids": [a], "style": st, "target": "stroke"})).unwrap();
s.execute("edit.copyProperties", &json!({"id": a})).unwrap();
let copied = s.doc().unwrap().node(a).unwrap().clone();
s.execute("file.new", &json!({})).unwrap();
let b = frame(&mut s, 0.0);
// This file's own style and variable come out with the copied ids: they are not the copied ones.
s.execute("variable.createCollection", &json!({"name": "Theirs"})).unwrap();
s.execute("variable.create", &json!({"collection": "Theirs", "name": "ink", "type": "color", "value": "#0000FF"})).unwrap();
s.execute("style.create", &json!({"type": "paint", "name": "Ink", "value": "#0000FF"})).unwrap();
let doc = s.doc().unwrap();
let vid = copied.bound["fills/0/color"].as_str();
assert!(doc.style(st.as_str().unwrap()).is_some() && doc.variables.get_by_id(vid).is_some(), "the ids are taken here");
s.execute("edit.pasteProperties", &json!({"ids": [b]})).unwrap();
let nb = s.doc().unwrap().node(b).unwrap();
assert_eq!((nb.fills.clone(), nb.strokes.clone()), (copied.fills, copied.strokes), "the values arrive");
assert!(nb.bound.is_empty() && nb.styles.fill.is_none() && nb.styles.stroke.is_none(), "{:?} {:?}", nb.bound, nb.styles);
}
#[test]
fn a_missing_style_unlinks_the_layers_own() {
let mut s = Session::new();
let (a, b) = (frame(&mut s, 0.0), frame(&mut s, 200.0));
// B's own style gives the same colour, so the paste changes no value that would unlink it.
let gone = s.execute("style.create", &json!({"type": "paint", "name": "Gone", "value": "#00FF00"})).unwrap()["id"].clone();
let own = s.execute("style.create", &json!({"type": "paint", "name": "Own", "value": "#00FF00"})).unwrap()["id"].clone();
s.execute("style.apply", &json!({"ids": [a], "style": gone, "target": "stroke"})).unwrap();
s.execute("style.apply", &json!({"ids": [b], "style": own, "target": "stroke"})).unwrap();
s.execute("edit.copyProperties", &json!({"id": a})).unwrap();
s.execute("style.delete", &json!({"style": gone})).unwrap();
s.execute("edit.pasteProperties", &json!({"ids": [b]})).unwrap();
let nb = s.doc().unwrap().node(b).unwrap();
assert!(nb.styles.stroke.is_none(), "A's strokes had no style here, so B's aren't linked: {:?}", nb.styles);
}
#[test]
fn a_binding_on_what_the_copy_doesnt_carry_stays() {
let mut s = Session::new();
let a = frame(&mut s, 0.0);
let t = id(s.execute("text.create", &json!({"text": "Hi", "x": 0, "y": 200})).unwrap());
s.execute("variable.createCollection", &json!({"name": "Tokens"})).unwrap();
s.execute("variable.create", &json!({"collection": "Tokens", "name": "body", "type": "number", "value": 18})).unwrap();
s.execute("variable.bind", &json!({"ids": [t], "field": "fontSize", "variable": "body"})).unwrap();
let before = s.doc().unwrap().node(t).unwrap().bound.get("fontSize").cloned();
copy_onto(&mut s, a, t);
let nt = s.doc().unwrap().node(t).unwrap();
assert!(before.is_some() && nt.bound.get("fontSize") == before.as_ref(), "a frame carries no font size: {:?}", nt.bound);
}
+20 -1
View File
@@ -63,7 +63,8 @@ pub struct Prefs {
/// Files that have a path are saved by themselves a few seconds after they change (the app's
/// timer; off: only File ▸ Save writes them).
pub auto_save: bool,
/// The desktop app starts on the Home screen instead of in a new file.
/// The desktop app starts on the Home screen instead of reopening the files open when it last
/// quit.
pub start_on_home: bool,
/// `figcraft://` invite links open this app (`collab.registerLinks`); `None`: on for installed
/// builds, off for development builds.
@@ -85,6 +86,18 @@ pub struct Prefs {
/// Recently opened or saved files, newest first (File ▸ Open recent; at most
/// [`cmd::file::MAX_RECENT`]).
pub recent_files: Vec<String>,
/// The files open when the desktop app last quit, in tab order: the next start opens them again
/// ([`Session::reopen_files`](crate::Session::reopen_files)).
#[serde(skip_serializing_if = "Vec::is_empty")]
pub open_files: Vec<String>,
/// Which of [`open_files`](Self::open_files) was in front.
#[serde(skip_serializing_if = "Option::is_none")]
pub front_file: Option<String>,
/// Where each file was left when its tab closed or the app quit, the most recently left first,
/// at most [`MAX_FILE_VIEWS`](crate::MAX_FILE_VIEWS): opening it again shows that page at that
/// view ([`Session::remember_views`](crate::Session::remember_views)).
#[serde(skip_serializing_if = "Vec::is_empty")]
pub file_views: Vec<crate::FileView>,
/// The files you put on a server without its key, with their owner tokens (passwords: see
/// [`online`]), most recently opened first, at most [`online::MAX_ONLINE_FILES`].
#[serde(skip_serializing_if = "Vec::is_empty", deserialize_with = "online::read")]
@@ -158,6 +171,9 @@ impl Default for Prefs {
plugin_directory: None,
publish_server: live::DEFAULT_SERVER.into(),
recent_files: Vec::new(),
open_files: Vec::new(),
front_file: None,
file_views: Vec::new(),
online_files: Vec::new(),
getting_started_dismissed: false,
link_notice_skipped: false,
@@ -201,6 +217,9 @@ pub struct Clipboard {
pub images: std::collections::BTreeMap<String, figcraft_doc::ImageData>,
/// Copied properties (Copy properties / Paste properties).
pub props: Option<Value>,
/// The file the copied properties came from: their style and variable ids name its styles and
/// variables, and in another file the same ids can name unrelated ones.
pub props_source_doc: u64,
/// A copied fill or stroke row (`fill.copy`, `stroke.copy`): whether it's a fill, and the paint.
pub paint: Option<(bool, figcraft_color::Paint)>,
/// The stroke settings (`weight`, alignment, sides…) copied with a stroke's paint.
+38
View File
@@ -0,0 +1,38 @@
//! The files open when the desktop app quit open again at its next start, in their tabs' order
//! with the same one in front, as Figma's desktop app reopens its tabs.
use serde_json::json;
use crate::{EngineError, Session};
impl Session {
/// Keep the open files to reopen at the next start: each tab's file that has a path, in tab
/// order, and the one in front. Files without one (new, imported, joined from a live session)
/// and branch tabs are left out.
pub fn remember_open_files(&mut self) {
let path = |i: usize| self.docs.get(i).filter(|d| d.branch_of.is_none()).and_then(|d| d.path.clone());
self.prefs.open_files = (0..self.docs.len()).filter_map(path).collect();
self.prefs.front_file = path(self.active);
}
/// Open the files [`remember_open_files`](Self::remember_open_files) kept, then bring the one
/// that was in front forward. A file that is no longer there is skipped; the others that don't
/// open come back with why. A file already open (a recovered copy, one named at start) keeps
/// its tab.
pub fn reopen_files(&mut self) -> Vec<(String, EngineError)> {
let mut failed = Vec::new();
for path in self.prefs.open_files.clone() {
if !crate::file_access::exists(&path) {
continue;
}
if let Err(e) = self.execute("file.open", &json!({"path": path})) {
failed.push((path, e));
}
}
let front = self.prefs.front_file.as_deref();
if let Some(i) = self.docs.iter().position(|d| front.is_some() && d.path.as_deref() == front) {
self.active = i;
}
failed
}
}
+115
View File
@@ -0,0 +1,115 @@
//! The files open when the desktop app quit open again at its next start.
use std::path::{Path, PathBuf};
use serde_json::json;
use crate::Session;
/// A fresh folder for a test's files, removed when the test ends, a failing one too.
struct Folder(PathBuf);
impl std::ops::Deref for Folder {
type Target = Path;
fn deref(&self) -> &Path {
&self.0
}
}
impl Drop for Folder {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
fn folder(name: &str) -> Folder {
let dir = std::env::temp_dir().join(format!("figcraft-reopen-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
Folder(dir)
}
fn saved(s: &mut Session, dir: &Path, name: &str) -> String {
let path = dir.join(format!("{name}.figcraft")).to_string_lossy().into_owned();
s.execute("file.new", &json!({"name": name})).unwrap();
s.execute("file.save", &json!({"path": path})).unwrap();
path
}
fn paths(s: &Session) -> Vec<Option<String>> {
s.docs.iter().map(|d| d.path.clone()).collect()
}
/// The next start: the preferences the last run kept, nothing open yet.
fn next_start(last: &Session) -> Session {
let mut s = Session::empty();
s.prefs = last.prefs.clone();
s
}
#[test]
fn the_files_open_at_quit_reopen_in_their_order_with_the_same_one_in_front() {
let dir = folder("order");
let mut s = Session::empty();
let a = saved(&mut s, &dir, "A");
s.execute("file.new", &json!({"name": "Untitled"})).unwrap();
let b = saved(&mut s, &dir, "B");
let c = saved(&mut s, &dir, "C");
s.execute("doc.switch", &json!({"index": 2})).unwrap();
s.remember_open_files();
assert_eq!(s.prefs.open_files, vec![a.clone(), b.clone(), c.clone()], "the new file without a path is left out");
assert_eq!(s.prefs.front_file.as_deref(), Some(b.as_str()));
let mut t = next_start(&s);
assert!(t.reopen_files().is_empty());
assert_eq!(paths(&t), vec![Some(a), Some(b.clone()), Some(c)]);
assert_eq!(t.docs[t.active].path.as_deref(), Some(b.as_str()), "B is in front again");
}
#[test]
fn a_file_gone_since_is_skipped_and_one_that_wont_open_says_why() {
let dir = folder("gone");
let mut s = Session::empty();
let kept = saved(&mut s, &dir, "Kept");
let gone = saved(&mut s, &dir, "Gone");
let broken = saved(&mut s, &dir, "Broken");
s.remember_open_files();
std::fs::remove_file(&gone).unwrap();
std::fs::write(&broken, b"not a figcraft file").unwrap();
let mut t = next_start(&s);
let failed = t.reopen_files();
assert_eq!(failed.iter().map(|(p, _)| p.clone()).collect::<Vec<_>>(), vec![broken]);
assert_eq!(paths(&t), vec![Some(kept)]);
}
#[test]
fn a_file_already_open_at_start_keeps_its_one_tab() {
let dir = folder("twice");
let mut s = Session::empty();
let a = saved(&mut s, &dir, "A");
let b = saved(&mut s, &dir, "B");
s.execute("doc.switch", &json!({"index": 0})).unwrap();
s.remember_open_files();
// B was named on the command line (or came back as a recovered copy).
let mut t = next_start(&s);
t.execute("file.open", &json!({"path": b})).unwrap();
assert!(t.reopen_files().is_empty());
assert_eq!(paths(&t), vec![Some(b), Some(a.clone())]);
assert_eq!(t.docs[t.active].path.as_deref(), Some(a.as_str()));
}
#[test]
fn quitting_with_nothing_open_leaves_nothing_to_reopen() {
let dir = folder("none");
let mut s = Session::empty();
saved(&mut s, &dir, "A");
s.remember_open_files();
s.execute("file.close", &json!({"index": 0})).unwrap();
s.remember_open_files();
assert!(s.prefs.open_files.is_empty());
assert_eq!(s.prefs.front_file, None);
let saved = serde_json::to_value(&s.prefs).unwrap();
assert!(saved.get("open_files").is_none() && saved.get("front_file").is_none(), "not written when empty");
}
+13 -3
View File
@@ -94,7 +94,7 @@ fn assert_save_state_unchanged(s: &Session, before: &DocState, recent: &[String]
}
#[test]
fn first_native_save_uses_chosen_filename_for_an_untitled_document() {
fn saving_to_another_file_names_the_document_after_it() {
let mut files = SaveFiles::new();
let path = files.path("Redis.figcraft");
let copy = files.path("Redis copy.figcraft");
@@ -111,9 +111,19 @@ fn first_native_save_uses_chosen_filename_for_an_untitled_document() {
s.execute("file.saveAs", &json!({"path": copy.to_string_lossy()})).unwrap();
assert_eq!(s.ds().unwrap().doc.name, "Redis copy");
s.execute("file.rename", &json!({"name": "Chosen title"})).unwrap();
s.execute("file.rename", &json!({"name": "Chosen: title"})).unwrap();
s.execute("file.save", &json!({})).unwrap();
assert_eq!(s.ds().unwrap().doc.name, "Chosen: title", "saving to the same file keeps a name given here");
s.execute("file.saveAs", &json!({"path": manual_copy.to_string_lossy()})).unwrap();
assert_eq!(s.ds().unwrap().doc.name, "Chosen title");
assert_eq!(s.ds().unwrap().doc.name, "Other", "a name given here too");
assert_eq!(figcraft_format::load_bytes(&std::fs::read(&manual_copy).unwrap()).unwrap().0.name, "Other");
// A file without one on disk yet: imported, here with its source's name.
let imported = files.path("Imported.figcraft");
let mut i = Session::new();
i.execute("file.rename", &json!({"name": "ШИМ"})).unwrap();
i.execute("file.saveAs", &json!({"path": imported.to_string_lossy()})).unwrap();
assert_eq!(i.ds().unwrap().doc.name, "Imported");
}
#[test]
+115
View File
@@ -0,0 +1,115 @@
use figcraft_doc::NodeId;
use serde_json::{Value, json};
use crate::Session;
use crate::params::id_of;
use crate::tools::{PointerEvent, PointerKind};
fn ex(s: &mut Session, cmd: &str, p: Value) -> NodeId {
id_of(&s.execute(cmd, &p).unwrap_or_else(|e| panic!("{cmd}: {e}"))["id"]).unwrap()
}
fn rect(s: &mut Session, x: f64, y: f64, parent: NodeId) -> NodeId {
ex(s, "shape.rectangle", json!({"x": x, "y": y, "width": 40, "height": 40, "parent": parent}))
}
struct Scene {
section: NodeId,
left: NodeId,
right: NodeId,
in_left: [NodeId; 2],
in_right: NodeId,
}
fn scene(s: &mut Session) -> Scene {
let section = ex(s, "node.create", json!({"type": "section", "x": 0, "y": 0, "width": 1000, "height": 600}));
let left = ex(s, "frame.create", json!({"x": 50, "y": 50, "width": 300, "height": 300, "parent": section}));
let right = ex(s, "frame.create", json!({"x": 400, "y": 50, "width": 300, "height": 300, "parent": section}));
let in_left = [rect(s, 20.0, 20.0, left), rect(s, 120.0, 120.0, left)];
let in_right = rect(s, 20.0, 20.0, right);
s.execute("select.none", &json!({})).unwrap();
Scene { section, left, right, in_left, in_right }
}
fn ev(kind: PointerKind, p: (f64, f64), cmd: bool) -> PointerEvent {
PointerEvent { cmd, ..PointerEvent::at(kind, p.0, p.1, 1.0) }
}
fn drag(s: &mut Session, a: (f64, f64), b: (f64, f64), cmd: bool) -> Vec<NodeId> {
s.pointer(&ev(PointerKind::Down, a, cmd)).unwrap();
s.pointer(&ev(PointerKind::Move, b, cmd)).unwrap();
s.pointer(&ev(PointerKind::Up, b, cmd)).unwrap();
let mut sel = s.selection();
sel.sort();
sel
}
fn x_of(s: &Session, id: NodeId) -> f64 {
s.doc().unwrap().world_bounds(id).unwrap().x0
}
fn sorted(mut v: Vec<NodeId>) -> Vec<NodeId> {
v.sort();
v
}
#[test]
fn a_drag_on_an_artboards_background_in_a_section_selects_what_it_touches() {
let mut s = Session::new();
let k = scene(&mut s);
assert_eq!(drag(&mut s, (60.0, 60.0), (110.0, 110.0), false), vec![k.in_left[0]]);
assert_eq!(drag(&mut s, (340.0, 340.0), (60.0, 60.0), false), sorted(k.in_left.to_vec()));
assert_eq!((x_of(&s, k.section), x_of(&s, k.left)), (0.0, 50.0), "nothing moved");
}
#[test]
fn a_drag_on_a_sections_background_selects_the_artboards_layers_it_touches() {
let mut s = Session::new();
let k = scene(&mut s);
assert_eq!(drag(&mut s, (20.0, 400.0), (480.0, 80.0), false), sorted(vec![k.in_left[0], k.in_left[1], k.in_right]));
assert_eq!(drag(&mut s, (20.0, 20.0), (720.0, 380.0), false), sorted(vec![k.left, k.right]), "artboards it encloses go whole");
assert_eq!(x_of(&s, k.section), 0.0, "the section stays put");
}
#[test]
fn a_selected_section_still_drags_and_a_click_on_its_background_steps_out_to_it() {
let mut s = Session::new();
let k = scene(&mut s);
s.execute("select.set", &json!({"ids": [k.section]})).unwrap();
drag(&mut s, (20.0, 400.0), (120.0, 400.0), false);
assert_eq!(x_of(&s, k.section), 100.0);
s.execute("select.set", &json!({"ids": [k.in_right]})).unwrap();
assert_eq!(drag(&mut s, (900.0, 500.0), (900.0, 500.0), false), vec![k.section]);
}
#[test]
fn cmd_drag_from_a_background_marks_out_nested_layers_and_cmd_click_still_picks_the_frame() {
let mut s = Session::new();
let k = scene(&mut s);
assert_eq!(drag(&mut s, (60.0, 60.0), (110.0, 110.0), true), vec![k.in_left[0]]);
assert_eq!(drag(&mut s, (20.0, 400.0), (480.0, 80.0), true), sorted(vec![k.in_left[0], k.in_left[1], k.in_right]));
assert_eq!((x_of(&s, k.section), x_of(&s, k.left)), (0.0, 50.0), "nothing moved");
assert_eq!(drag(&mut s, (300.0, 300.0), (300.0, 300.0), true), vec![k.left]);
assert_eq!(drag(&mut s, (900.0, 500.0), (900.0, 500.0), true), vec![k.section]);
}
#[test]
fn cmd_drag_inside_a_selected_artboard_or_section_marks_out_nested_layers_instead_of_moving_it() {
let mut s = Session::new();
let k = scene(&mut s);
s.execute("select.set", &json!({"ids": [k.left]})).unwrap();
assert_eq!(drag(&mut s, (130.0, 75.0), (90.0, 90.0), true), vec![k.in_left[0]]);
s.execute("select.set", &json!({"ids": [k.section]})).unwrap();
assert_eq!(drag(&mut s, (20.0, 400.0), (480.0, 80.0), true), sorted(vec![k.in_left[0], k.in_left[1], k.in_right]));
assert_eq!((x_of(&s, k.section), x_of(&s, k.left)), (0.0, 50.0), "nothing moved");
s.execute("select.set", &json!({"ids": [k.left]})).unwrap();
assert_eq!(drag(&mut s, (300.0, 300.0), (300.0, 300.0), true), vec![k.left], "a Cmd click keeps the artboard");
assert_eq!(drag(&mut s, (80.0, 80.0), (80.0, 80.0), true), vec![k.in_left[0]], "a Cmd click on a layer in it picks the layer");
let mut s = Session::new();
let board = ex(&mut s, "frame.create", json!({"x": 0, "y": 0, "width": 400, "height": 400}));
let inner = [rect(&mut s, 20.0, 20.0, board), rect(&mut s, 200.0, 200.0, board)];
s.execute("select.set", &json!({"ids": [board]})).unwrap();
assert_eq!(drag(&mut s, (330.0, 30.0), (10.0, 300.0), true), sorted(inner.to_vec()), "a top-level artboard too");
assert_eq!(x_of(&s, board), 0.0);
}
@@ -0,0 +1,116 @@
use serde_json::{Value, json};
use crate::Session;
use crate::params::id_of;
use crate::tools::{PointerEvent, PointerKind};
use figcraft_doc::NodeId;
fn ex(s: &mut Session, cmd: &str, p: Value) -> NodeId {
id_of(&s.execute(cmd, &p).unwrap_or_else(|e| panic!("{cmd}: {e}"))["id"]).unwrap()
}
struct Board {
frame: NodeId,
inner: NodeId,
rect: NodeId,
}
fn board(s: &mut Session, x: f64) -> Board {
let frame = ex(s, "frame.create", json!({"x": x, "y": 0, "width": 300, "height": 300}));
let rect = ex(s, "shape.rectangle", json!({"x": 50, "y": 50, "width": 100, "height": 100, "parent": frame}));
let other = ex(s, "shape.rectangle", json!({"x": 200, "y": 200, "width": 40, "height": 40, "parent": frame}));
let inner = ex(s, "object.group", json!({"ids": [rect, other]}));
let extra = ex(s, "shape.rectangle", json!({"x": 250, "y": 20, "width": 20, "height": 20, "parent": frame}));
ex(s, "object.group", json!({"ids": [inner, extra]}));
Board { frame, inner, rect }
}
fn send(s: &mut Session, kind: PointerKind, x: f64, y: f64, shift: bool) {
s.pointer(&PointerEvent { shift, ..PointerEvent::at(kind, x, y, 1.0) }).unwrap();
}
fn double_click(s: &mut Session, x: f64, y: f64, shift: bool) -> Vec<NodeId> {
send(s, PointerKind::Down, x, y, shift);
send(s, PointerKind::Up, x, y, shift);
send(s, PointerKind::Down, x, y, shift);
send(s, PointerKind::DoubleClick, x, y, shift);
send(s, PointerKind::Up, x, y, shift);
send(s, PointerKind::Move, x + 1.0, y, shift);
let mut sel = s.selection();
sel.sort();
sel
}
fn sorted(mut v: Vec<NodeId>) -> Vec<NodeId> {
v.sort();
v
}
#[test]
fn shift_double_clicks_go_deeper_in_a_neighbouring_artboard_and_keep_the_rest() {
let mut s = Session::new();
let a = board(&mut s, 0.0);
let b = board(&mut s, 400.0);
s.execute("select.none", &json!({})).unwrap();
assert_eq!(double_click(&mut s, 100.0, 100.0, false), vec![a.inner], "a plain double-click enters the artboard");
assert_eq!(double_click(&mut s, 500.0, 100.0, true), sorted(vec![a.inner, b.inner]), "Shift: the neighbour's layer joins");
assert_eq!(double_click(&mut s, 500.0, 100.0, true), sorted(vec![a.inner, b.rect]), "Shift again: a level deeper there");
assert_eq!(double_click(&mut s, 100.0, 100.0, true), sorted(vec![a.rect, b.rect]), "and in the first artboard too");
assert!(s.ds().unwrap().vector_edit.is_none());
assert_eq!(s.doc().unwrap().node(a.frame).unwrap().children.len(), 1, "nothing moved out of place");
}
#[test]
fn a_shift_double_click_on_a_neighbouring_row_adds_its_layer_at_the_selected_depth() {
let mut s = Session::new();
let section = ex(&mut s, "node.create", json!({"type": "section", "x": -100, "y": -100, "width": 1200, "height": 1000}));
let artboard = ex(&mut s, "frame.create", json!({"x": 0, "y": 0, "width": 1000, "height": 800}));
s.execute("node.reparent", &json!({"ids": [artboard], "parent": section})).unwrap();
let content = ex(&mut s, "frame.create", json!({"x": 100, "y": 100, "width": 600, "height": 400, "parent": artboard}));
let specs = ex(&mut s, "frame.create", json!({"x": 0, "y": 100, "width": 600, "height": 200, "parent": content}));
let names: Vec<NodeId> = (0..3)
.map(|i| {
let row = ex(&mut s, "frame.create", json!({"x": 30, "y": i * 30, "width": 560, "height": 22, "parent": specs}));
let name = ex(&mut s, "frame.create", json!({"x": 0, "y": 0, "width": 120, "height": 22, "parent": row}));
ex(&mut s, "text.create", json!({"text": "Client:", "x": 0, "y": 0, "parent": name}));
name
})
.collect();
s.execute("select.set", &json!({"ids": [names[0]]})).unwrap();
assert_eq!(double_click(&mut s, 135.0, 238.0, true), sorted(vec![names[0], names[1]]), "the next row's name joins the selected one");
assert_eq!(double_click(&mut s, 135.0, 268.0, true), sorted(names.clone()), "and the row after it");
}
#[test]
fn a_shift_double_click_with_the_hand_keeps_a_selection_made_after_earlier_presses() {
let mut s = Session::new();
let a = board(&mut s, 0.0);
let b = board(&mut s, 400.0);
s.execute("select.set", &json!({"ids": [a.inner]})).unwrap();
for _ in 0..2 {
send(&mut s, PointerKind::Down, 100.0, 100.0, false);
send(&mut s, PointerKind::Up, 100.0, 100.0, false);
}
s.execute("select.set", &json!({"ids": [b.inner]})).unwrap();
s.set_tool(crate::tools::ToolId::Hand);
assert_eq!(double_click(&mut s, 100.0, 100.0, true), sorted(vec![a.inner, b.inner]), "the Move presses' selection doesn't come back");
}
#[test]
fn a_shift_double_click_without_its_presses_keeps_the_current_selection() {
let mut s = Session::new();
let a = board(&mut s, 0.0);
let b = board(&mut s, 400.0);
s.execute("select.set", &json!({"ids": [a.inner]})).unwrap();
for _ in 0..2 {
send(&mut s, PointerKind::Down, 1000.0, 1000.0, false);
send(&mut s, PointerKind::Up, 1000.0, 1000.0, false);
}
s.execute("select.set", &json!({"ids": [b.inner]})).unwrap();
send(&mut s, PointerKind::DoubleClick, 100.0, 100.0, true);
assert_eq!(sorted(s.selection()), sorted(vec![a.inner, b.inner]), "a double-click alone works from the selection it finds");
}
+39
View File
@@ -960,3 +960,42 @@ fn setting_characters_as_a_command_never_renames_the_layer() {
s.execute("node.set", &json!({"id": t, "props": {"characters": "Site em 7 dias"}})).unwrap();
assert_eq!((chars(&s, t).as_str(), layer_name(&s, t).as_str()), ("Site em 7 dias", "Title"), "the field keeps its name");
}
fn top_middle(s: &Session, t: NodeId) -> (f64, f64) {
let doc = s.doc().unwrap();
let p = doc.world_transform(t) * figcraft_geom::kurbo::Point::new(doc.node(t).unwrap().width / 2.0, 0.0);
(p.x, p.y)
}
#[test]
fn centred_auto_width_text_grows_and_shrinks_both_ways() {
let font = test_mono_font();
for (src, rotation) in [("ANCHOR TEST\nabc", 0.0), ("abc", 0.0), ("abc", 90.0)] {
let mut s = Session::new();
let t = text(&mut s, src, json!({"fontSize": 40, "fontFamily": font, "textAlign": "center", "textAutoResize": "widthAndHeight"}));
s.execute("node.set", &json!({"id": t, "props": {"x": 200, "y": 50, "rotation": rotation}})).unwrap();
let anchor = top_middle(&s, t);
let w0 = size(&s, t).0;
begin(&mut s, t, Some(src.chars().count()), false).unwrap();
for c in "defghijklmnopqrstuvwxyz".chars() {
crate::textedit::insert(&mut s, &c.to_string()).unwrap();
assert_near(top_middle(&s, t), anchor, &format!("{src:?} at {rotation}°: typing {c}"));
}
assert!(size(&s, t).0 > w0 + 1e-6, "{src:?} at {rotation}°: typing grows the text");
for _ in 0..23 {
key(&mut s, "Backspace", false, false, false).unwrap();
assert_near(top_middle(&s, t), anchor, &format!("{src:?} at {rotation}°: deleting"));
}
assert!((size(&s, t).0 - w0).abs() < 1e-6, "back to the starting width");
}
}
#[test]
fn left_aligned_auto_width_text_still_grows_to_the_right() {
let font = test_mono_font();
let mut s = Session::new();
let t = text(&mut s, "abc", json!({"fontSize": 40, "fontFamily": font, "textAutoResize": "widthAndHeight"}));
let left = s.doc().unwrap().world_transform(t);
s.execute("node.set", &json!({"id": t, "props": {"characters": "abcdefghijklmnop"}})).unwrap();
assert_eq!(s.doc().unwrap().world_transform(t), left);
}
+113
View File
@@ -0,0 +1,113 @@
//! Tab and Shift+Tab while editing a text layer move editing to the next or previous text layer
//! of the same top-level frame, in reading order (rows top to bottom, each left to right), with
//! all of its text selected; hidden and locked text is passed over, and at either end the key
//! does nothing.
use figcraft_doc::NodeId;
use serde_json::{Value, json};
use crate::Session;
use crate::params::id_of;
fn ex(s: &mut Session, cmd: &str, p: Value) -> Value {
s.execute(cmd, &p).unwrap_or_else(|e| panic!("{cmd}: {e}"))
}
fn text(s: &mut Session, chars: &str, x: f64, y: f64, parent: NodeId) -> NodeId {
id_of(&ex(s, "text.create", json!({"text": chars, "x": x, "y": y, "parent": parent}))["id"]).unwrap()
}
fn frame(s: &mut Session, x: f64, y: f64) -> NodeId {
id_of(&ex(s, "frame.create", json!({"x": x, "y": y, "width": 400, "height": 300}))["id"]).unwrap()
}
fn tab(s: &mut Session, shift: bool) {
ex(s, "text.edit.key", json!({"key": "Tab", "shift": shift}));
}
/// The text being edited and whether all of it is selected.
fn editing(s: &Session) -> (NodeId, bool) {
let te = s.ds().unwrap().text_edit.clone().expect("still editing");
let n = s.doc().unwrap().node(te.id).unwrap().kind.text().unwrap().char_count();
(te.id, te.anchor.min(te.caret) == 0 && te.anchor.max(te.caret) == n)
}
fn chars(s: &Session, id: NodeId) -> String {
s.doc().unwrap().node(id).unwrap().kind.text().unwrap().characters.clone()
}
/// A frame with a row of three texts whose tops differ by a few pixels, out of order in the
/// layer list, and a second row below; a text in another frame beside it.
fn two_rows(s: &mut Session) -> Vec<NodeId> {
let f = frame(s, 0.0, 0.0);
let b = text(s, "B", 150.0, 12.0, f);
let a = text(s, "A", 10.0, 10.0, f);
let e = text(s, "E", 150.0, 100.0, f);
let c = text(s, "C", 290.0, 6.0, f);
let d = text(s, "D", 10.0, 101.0, f);
let other = frame(s, 500.0, 0.0);
text(s, "Elsewhere", 10.0, 10.0, other);
vec![a, b, c, d, e]
}
#[test]
fn tab_reads_a_row_left_to_right_then_the_next_row() {
let mut s = Session::new();
let order = two_rows(&mut s);
ex(&mut s, "text.edit.begin", json!({"id": order[0], "caret": 0}));
for want in &order[1..] {
tab(&mut s, false);
assert_eq!(editing(&s), (*want, true), "on to {} with all of it selected", chars(&s, *want));
}
assert!(order.iter().all(|t| !chars(&s, *t).contains('\t')), "no tab typed");
}
#[test]
fn shift_tab_goes_back() {
let mut s = Session::new();
let order = two_rows(&mut s);
ex(&mut s, "text.edit.begin", json!({"id": order[4], "caret": 0}));
for want in order[..4].iter().rev() {
tab(&mut s, true);
assert_eq!(editing(&s).0, *want, "back to {}", chars(&s, *want));
}
}
#[test]
fn tab_on_the_last_text_keeps_editing_it() {
let mut s = Session::new();
let order = two_rows(&mut s);
let undo = s.ds().unwrap().history.undo.len();
ex(&mut s, "text.edit.begin", json!({"id": order[4], "caret": 1}));
tab(&mut s, false);
let te = s.ds().unwrap().text_edit.clone().expect("still editing");
assert_eq!((te.id, te.caret, te.anchor), (order[4], 1, 1), "the last one: nothing moves");
assert_eq!(chars(&s, order[4]), "E", "and nothing is typed");
// Shift+Tab on the first one does nothing either.
ex(&mut s, "text.edit.end", json!({}));
ex(&mut s, "text.edit.begin", json!({"id": order[0], "caret": 0}));
tab(&mut s, true);
assert_eq!(editing(&s).0, order[0]);
ex(&mut s, "text.edit.end", json!({}));
assert_eq!(s.ds().unwrap().history.undo.len(), undo, "no undo step for it");
}
#[test]
fn hidden_and_locked_text_is_skipped() {
let mut s = Session::new();
let f = frame(&mut s, 0.0, 0.0);
let first = text(&mut s, "First", 10.0, 10.0, f);
let hidden = text(&mut s, "Hidden", 10.0, 50.0, f);
ex(&mut s, "node.set", json!({"id": hidden, "props": {"visible": false}}));
let locked = text(&mut s, "Locked", 10.0, 90.0, f);
ex(&mut s, "node.set", json!({"id": locked, "props": {"locked": true}}));
let inner = id_of(&ex(&mut s, "frame.create", json!({"x": 10, "y": 130, "width": 200, "height": 60, "parent": f}))["id"]).unwrap();
text(&mut s, "In a locked frame", 0.0, 0.0, inner);
ex(&mut s, "node.set", json!({"id": inner, "props": {"locked": true}}));
let last = text(&mut s, "Last", 10.0, 220.0, f);
ex(&mut s, "text.edit.begin", json!({"id": first, "caret": 0}));
tab(&mut s, false);
assert_eq!(editing(&s).0, last, "past the hidden text, the locked one and the text in a locked frame");
tab(&mut s, true);
assert_eq!(editing(&s).0, first);
}
+3 -3
View File
@@ -221,11 +221,11 @@ fn list_keys_at_list_items() {
2,
"Tab",
false,
"a\n\tb",
"a\nb",
vec![(B, 0), (P, 1)],
"a plain paragraph at a level isn't an item: Tab types a tab",
"a plain paragraph at a level isn't an item: Tab leaves the list alone (and moves to the next text, none here)",
),
("a\nb", vec![(P, 0), (P, 0)], 3, "Tab", false, "a\nb\t", vec![(P, 0), (P, 0)], "outside a list Tab types a tab"),
("a\nb", vec![(P, 0), (P, 0)], 3, "Tab", false, "a\nb", vec![(P, 0), (P, 0)], "outside a list Tab types no tab"),
("a", vec![(B, 8)], 1, "Tab", false, "a", vec![(B, 8)], "silent: nesting stops at 8 levels"),
];
for (chars, before, caret, k, shift, after, want, why) in cases {
+194 -20
View File
@@ -360,43 +360,134 @@ fn command_crop_preserves_each_image_fill_and_leaves_tiles() {
}
#[test]
fn command_resize_leaves_fills_when_text_or_auto_layout_recomputes_the_box() {
for case in ["text", "child", "frame"] {
fn command_resize_leaves_a_texts_fills() {
let mut s = session();
let image = image_layer(&mut s);
let fills = s.doc().unwrap().node(image).unwrap().fills.clone();
let layer = id(&ex(
&mut s,
"text.create",
json!({"text": "hello world hello world hello world", "props": {
"width": 200, "height": 100, "fontSize": 24, "textAutoResize": "none", "fills": fills
}}),
));
ex(&mut s, "select.set", json!({"ids": [layer]}));
let doc = s.doc().unwrap();
let world = doc.world_transform(layer);
let n = doc.node(layer).unwrap();
let (from, to) = (world * Point::new(n.width, n.height / 2.0), world * Point::new(10.0, n.height / 2.0));
drag(&mut s, from, to, CMD);
assert_eq!(s.doc().unwrap().node(layer).unwrap().fills, fills, "a text reflows: keep the existing resize behaviour");
}
fn image_units_per_layer_unit(s: &Session, layer: NodeId) -> (f64, f64, f64, f64) {
use figcraft_doc::color::PaintKind;
let doc = s.doc().unwrap();
let n = doc.node(layer).unwrap();
let PaintKind::Image(img) = &n.fills[0].kind else { panic!("image fill") };
let data = doc.images.get(&img.image).unwrap();
let c = img.effective_crop(f64::from(data.width), f64::from(data.height), n.width, n.height);
(c[0] / n.width, c[3] / n.height, c[4], c[5])
}
#[test]
fn command_resize_crops_in_auto_layout_against_the_box_layout_leaves() {
use figcraft_doc::color::{ImageScaleMode, PaintKind};
for case in ["child", "child with a minimum width", "auto layout frame"] {
let mut s = session();
let image = image_layer(&mut s);
let fills = s.doc().unwrap().node(image).unwrap().fills.clone();
let layer = match case {
"text" => id(&ex(
&mut s,
"text.create",
json!({"text": "hello world hello world hello world", "props": {
"width": 200, "height": 100, "fontSize": 24, "textAutoResize": "none", "fills": fills
}}),
)),
let frame = id(&ex(&mut s, "frame.create", json!({"x": 0, "y": 0, "width": 240, "height": 140})));
set(&mut s, &[frame], json!({"layout": "horizontal", "padding": 20}));
let (layer, to_x, width) = match case {
"auto layout frame" => {
set(&mut s, &[frame], json!({"fills": fills}));
(frame, 10.0, 40.0)
}
_ => {
let frame = id(&ex(&mut s, "frame.create", json!({"x": 0, "y": 0, "width": 200, "height": 100})));
set(&mut s, &[frame], json!({"layout": "horizontal", "padding": 20}));
ex(&mut s, "node.reparent", json!({"ids": [image], "parent": frame}));
if case == "child" {
ex(&mut s, "node.reparent", json!({"ids": [image], "parent": frame}));
set(&mut s, &[image], json!({"minWidth": 150}));
image
(image, 150.0, 150.0)
} else {
set(&mut s, &[frame], json!({"fills": fills}));
frame
set(&mut s, &[image], json!({"minWidth": 150}));
(image, 10.0, 150.0)
}
}
};
ex(&mut s, "select.set", json!({"ids": [layer]}));
let before = image_units_per_layer_unit(&s, layer);
let doc = s.doc().unwrap();
let world = doc.world_transform(layer);
let n = doc.node(layer).unwrap();
let from = world * Point::new(n.width, n.height / 2.0);
let to = world * Point::new(10.0, n.height / 2.0);
let (from, to) = (world * Point::new(n.width, n.height / 2.0), world * Point::new(to_x, n.height / 2.0));
drag(&mut s, from, to, CMD);
assert_eq!(s.doc().unwrap().node(layer).unwrap().fills, fills, "{case}: keep the existing resize behaviour");
let n = s.doc().unwrap().node(layer).unwrap().clone();
assert!(near(n.width, width), "{case}: {} wide, as auto layout leaves it", n.width);
let PaintKind::Image(img) = &n.fills[0].kind else { panic!("image fill") };
assert_eq!(img.scale_mode, ImageScaleMode::Crop, "{case}: cropped");
let after = image_units_per_layer_unit(&s, layer);
assert!(near(after.0, before.0) && near(after.1, before.1), "{case}: the image keeps its scale, not stretched: {before:?} -> {after:?}");
assert!(near(after.2, before.2) && near(after.3, before.3), "{case}: its left edge stays where it was in the layer: {before:?} -> {after:?}");
}
}
/// A minimum width can give a layer back the width its left side was dragged in by: the crop then
/// slides back along the image instead of running past its right edge.
#[test]
fn command_crop_slides_back_onto_the_image_when_layout_widens_the_layer() {
use figcraft_doc::color::{ImagePaint, PaintKind};
let mut s = session();
let image = image_layer(&mut s);
let frame = id(&ex(&mut s, "frame.create", json!({"x": 0, "y": 0, "width": 240, "height": 140})));
set(&mut s, &[frame], json!({"layout": "horizontal", "padding": 20}));
ex(&mut s, "node.reparent", json!({"ids": [image], "parent": frame}));
set(&mut s, &[image], json!({"minWidth": 150}));
ex(&mut s, "select.set", json!({"ids": [image]}));
let before = image_units_per_layer_unit(&s, image);
let world = s.doc().unwrap().world_transform(image);
drag(&mut s, world * Point::new(0.0, 50.0), world * Point::new(190.0, 50.0), CMD);
let doc = s.doc().unwrap();
let n = doc.node(image).unwrap();
assert!(near(n.width, 150.0), "{} wide, as the minimum width leaves it", n.width);
let PaintKind::Image(img) = &n.fills[0].kind else { panic!("image fill") };
let data = doc.images.get(&img.image).unwrap();
let crop = img.effective_crop(f64::from(data.width), f64::from(data.height), n.width, n.height);
let (x0, _, x1, _) = ImagePaint::crop_rect(crop);
assert!(x0 <= 1e-9 && x1 >= 1.0 - 1e-9, "the image covers the layer: {x0}..{x1}");
let after = image_units_per_layer_unit(&s, image);
assert!(near(after.0, before.0) && near(after.1, before.1), "the image keeps its scale: {before:?} -> {after:?}");
}
/// Where the image's edge stops a crop, Shift still keeps the ratio (both axes stop together) and
/// Alt still keeps the box centred (both sides stop together).
#[test]
fn command_crop_stopped_by_the_image_keeps_the_ratio_with_shift_and_the_centre_with_alt() {
let mut s = session();
let layer = image_layer(&mut s);
ex(&mut s, "select.set", json!({"ids": [layer]}));
drag(&mut s, Point::new(200.0, 100.0), Point::new(150.0, 80.0), CMD);
assert_eq!(size(&s, layer), (150.0, 80.0));
drag(&mut s, Point::new(150.0, 80.0), Point::new(240.0, 128.0), Mods { shift: true, alt: false, cmd: true });
assert!(
near_rect(bounds(&s, layer), Rect::new(0.0, 0.0, 187.5, 100.0)),
"the bottom stops at the image, the right side with it: {:?}",
bounds(&s, layer)
);
let mut s = session();
let layer = image_layer(&mut s);
ex(&mut s, "select.set", json!({"ids": [layer]}));
drag(&mut s, Point::new(0.0, 50.0), Point::new(20.0, 50.0), CMD);
drag(&mut s, Point::new(200.0, 50.0), Point::new(150.0, 50.0), CMD);
assert!(near_rect(bounds(&s, layer), Rect::new(20.0, 0.0, 150.0, 100.0)), "{:?}", bounds(&s, layer));
drag(&mut s, Point::new(150.0, 50.0), Point::new(190.0, 50.0), Mods { shift: false, alt: true, cmd: true });
assert!(
near_rect(bounds(&s, layer), Rect::new(0.0, 0.0, 170.0, 100.0)),
"the left side stops at the image, the right side as far: {:?}",
bounds(&s, layer)
);
}
/// A resize is an explicit edit of the size: a size bound to a variable lets go of it (#809), so
/// Cmd/Ctrl crops a bound layer's image as any other's; other bindings stay.
#[test]
@@ -913,6 +1004,73 @@ fn snapping_to_layers_wins_over_the_pixel_grid() {
assert_eq!(size(&s, b), (100.0, 151.0));
}
#[test]
fn frames_land_on_whole_pixels_whatever_they_snap_to() {
// Figma's help: frames, sections and components "always snap to the pixel grid, even if Snap
// to pixel grid is disabled". Other layers follow the setting.
let frame = |s: &mut Session, x: f64, y: f64| id(&ex(s, "frame.create", json!({"x": x, "y": y, "width": 100, "height": 100})));
let whole = |r: Rect| [r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.fract() == 0.0);
let mut s = Session::new();
// A neighbour off the pixel grid, as a scaled or imported layer leaves one: its right edge at
// 100.4.
rect(&mut s, 0.4, 0.0, 100.0, 100.0, None);
let f = frame(&mut s, 300.0, 300.0);
let r = rect(&mut s, 300.0, 600.0, 100.0, 100.0, None);
// Moved next to it, a rectangle snaps onto 100.4 and the frame to the whole pixel there.
ex(&mut s, "select.set", json!({"ids": [r]}));
drag(&mut s, Point::new(350.0, 650.0), Point::new(151.5, 650.0), Mods::default());
assert!(near(bounds(&s, r).x0, 100.4), "{:?}", bounds(&s, r));
ex(&mut s, "select.set", json!({"ids": [f]}));
drag(&mut s, Point::new(350.0, 350.0), Point::new(151.5, 350.0), Mods::default());
assert_eq!(bounds(&s, f).origin(), Point::new(100.0, 300.0), "moved by the snap, onto the whole pixel");
// With Snap to pixel grid off, frames still move, resize and draw on whole pixels.
ex(&mut s, "view.snapPixel", json!({"on": false}));
ex(&mut s, "view.snapObjects", json!({"on": false}));
drag(&mut s, Point::new(150.0, 350.0), Point::new(160.3, 360.6), Mods::default());
assert_eq!(bounds(&s, f).origin(), Point::new(110.0, 311.0), "moved");
drag(&mut s, Point::new(210.0, 411.0), Point::new(250.4, 450.6), Mods::default());
assert_eq!(size(&s, f), (140.0, 140.0), "resized");
ex(&mut s, "tool.set", json!({"tool": "frame"}));
drag(&mut s, Point::new(500.3, 500.6), Point::new(560.6, 540.2), Mods::default());
let drawn = s.selection()[0];
assert!(whole(bounds(&s, drawn)), "drawn: {:?}", bounds(&s, drawn));
// A frame already off the pixel grid lands on it once moved.
ex(&mut s, "tool.set", json!({"tool": "move"}));
let off = frame(&mut s, 800.4, 800.7);
ex(&mut s, "select.set", json!({"ids": [off]}));
drag(&mut s, Point::new(850.0, 850.0), Point::new(860.0, 850.0), Mods::default());
assert!(whole(bounds(&s, off)), "{:?}", bounds(&s, off));
// A rectangle follows the pointer.
ex(&mut s, "select.set", json!({"ids": [r]}));
drag(&mut s, Point::new(150.0, 650.0), Point::new(160.3, 650.0), Mods::default());
assert!(near(bounds(&s, r).x0, 110.7), "{:?}", bounds(&s, r));
}
#[test]
fn frames_resized_together_each_land_on_whole_pixels() {
let mut s = session();
let frame = |s: &mut Session, x: f64| id(&ex(s, "frame.create", json!({"x": x, "y": 0, "width": 100, "height": 100})));
let (a, b) = (frame(&mut s, 0.0), frame(&mut s, 200.0));
ex(&mut s, "select.set", json!({"ids": [a, b]}));
// 300 wide to 400: a third more, so each frame alone would be 133.33 wide.
drag(&mut s, Point::new(300.0, 100.0), Point::new(400.0, 100.0), Mods::default());
assert_eq!(bounds(&s, a), Rect::new(0.0, 0.0, 133.0, 100.0));
assert_eq!(bounds(&s, b), Rect::new(267.0, 0.0, 400.0, 100.0));
}
#[test]
fn a_frame_dropped_into_a_frame_off_the_pixel_grid_lands_on_its_whole_pixels() {
let mut s = session();
let target = id(&ex(&mut s, "frame.create", json!({"x": 300.5, "y": 0.5, "width": 300, "height": 300})));
let f = id(&ex(&mut s, "frame.create", json!({"x": 0, "y": 0, "width": 50, "height": 50})));
ex(&mut s, "select.set", json!({"ids": [f]}));
drag(&mut s, Point::new(25.0, 25.0), Point::new(425.0, 125.0), Mods::default());
let n = s.doc().unwrap().node(f).unwrap().clone();
assert_eq!(n.parent, Some(target));
let [.., x, y] = n.transform.as_coeffs();
assert_eq!((x.fract(), y.fract()), (0.0, 0.0), "at {x}, {y} in the frame");
}
#[test]
fn corner_cursors_stay_diagonal_whatever_the_proportions() {
let mut s = session();
@@ -974,3 +1132,19 @@ fn the_transform_box_and_its_handles() {
// At a larger zoom the same layer is big enough on screen for its handles inside it.
assert_eq!(handle_at(s.doc().unwrap(), &[tiny], Point::new(320.2, 10.2), 20.0), Some(Handle::Corner(0)));
}
#[test]
fn command_crop_changes_a_locked_ratio_and_stops_at_the_images_edges() {
let mut s = session();
let layer = image_layer(&mut s);
set(&mut s, &[layer], json!({"constrainProportions": true}));
ex(&mut s, "select.set", json!({"ids": [layer]}));
drag(&mut s, Point::new(200.0, 50.0), Point::new(150.0, 50.0), CMD);
assert_eq!(size(&s, layer), (150.0, 100.0), "a side changes the ratio, lock or not");
drag(&mut s, Point::new(150.0, 50.0), Point::new(260.0, 50.0), CMD);
assert_eq!(size(&s, layer), (200.0, 100.0), "the side stops at the image's edge");
drag(&mut s, Point::new(100.0, 0.0), Point::new(100.0, -40.0), CMD);
assert!(near_rect(bounds(&s, layer), Rect::new(0.0, 0.0, 200.0, 100.0)), "the top stops at the image's top: {:?}", bounds(&s, layer));
drag(&mut s, Point::new(200.0, 50.0), Point::new(100.0, 50.0), Mods { shift: true, alt: false, cmd: true });
assert_eq!(size(&s, layer), (100.0, 50.0), "Shift keeps the ratio");
}
@@ -700,6 +700,31 @@ fn deleting_points_vs_delete_and_heal() {
assert_eq!((n.vertices.len(), n.segments.len()), (4, 3), "deleting a segment leaves its points");
}
#[test]
fn deleting_a_point_selects_the_next_one_on_its_path() {
let mut s = Session::new();
let id = id_of(&ex(&mut s, "vector.create", json!({"path": "M0 0 L100 0 L200 0 L300 0"}))["id"]).unwrap();
ex(&mut s, "vector.edit.begin", json!({"id": id}));
let selected = |s: &Session| editing(s).unwrap().vertices.iter().map(|v| page_pos(s, id, *v)).collect::<Vec<_>>();
let second = point_at(&s, id, (100.0, 0.0));
ex(&mut s, "vector.edit.select", json!({"vertices": [second]}));
key(&mut s, "Delete", true);
assert_eq!(selected(&s), [Point::new(200.0, 0.0)], "the point after the deleted one");
key(&mut s, "Delete", true);
assert_eq!(selected(&s), [Point::new(300.0, 0.0)], "so Delete again walks along the path");
key(&mut s, "Delete", true);
assert_eq!(selected(&s), [Point::new(0.0, 0.0)], "past the path's end, the point before it");
let mut s = Session::new();
let id = square(&mut s, true);
let tr = point_at(&s, id, (100.0, 0.0));
ex(&mut s, "vector.edit.select", json!({"vertices": [tr]}));
key(&mut s, "Delete", false);
let after = selected(&s);
assert_eq!(after.len(), 1, "one point selected after a plain Delete: {after:?}");
assert!([Point::new(100.0, 100.0), Point::new(0.0, 0.0)].contains(&after[0]), "a neighbour of the deleted corner: {after:?}");
}
#[test]
fn handles_follow_their_mirroring() {
// A smooth middle point at (100, 0) on an open path; one handle is dragged to (+30, 10).