mirror of
https://github.com/storytold/figcraft.git
synced 2026-11-08 19:42:05 +00:00
Merge main into #2048
This commit is contained in:
commit
22abeefae2
41 files changed
+1224
-254
No files matched your search
@@ -360,6 +360,7 @@ Ranked; detail and milestones in [`docs/roadmap.md`](docs/roadmap.md).
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-11-06 | patch | M7, #2032: closing a tab whose file has unsaved changes asks Don't Save / Cancel / Save, as closing the window does, instead of a toast that left the tab open; Alt+close still discards at once. Tests: `titlebar_tests::closing_a_tab_with_unsaved_changes_asks`, `titlebar_tests::save_in_the_tab_question_saves_then_closes`. Numbers unchanged |
|
||||
| 2026-11-06 | patch | M9, #2026: a branch merge counts one conflict per auto layout field changed both ways, not one for every size and place auto layout works out from it; values an instance takes from its main no longer conflict, and auto layout settings changed one way survive a conflict on another field. Tests: `branch_tests::one_conflicting_auto_layout_edit_is_one_conflict`, `branch_tests::auto_layout_fields_changed_one_way_survive_a_conflict`, `branch_tests::sizes_auto_layout_works_out_never_conflict`. Numbers unchanged |
|
||||
| 2026-11-06 | patch | M8: glass takes one backdrop sample instead of its 18-sample dispersion window where the colours split under 1/256 px (the flat end of the curve, where the move is short), within one level of the window over any backdrop: a large pane renders about 2–5% faster, with the same pixels in the renders compared. Tests: `glass::tests::a_split_too_narrow_to_show_takes_one_sample`. Numbers unchanged |
|
||||
| 2026-11-02 | patch | M8, #1885: a glass whose shape is too big to keep whole at the zoom (past `MAX_SHAPE_PX` with its core's margin) bends along its edge normals instead of working out a core, so its fields never cover more pixels than a kept shape's, and the core's feature transform holds 16 bytes a pixel. The edge normals are box-blurred twice again and the bend directions once, as documented. Test: `glass::tests::a_shape_too_big_to_keep_bends_along_its_normals`. Numbers unchanged |
|
||||
| 2026-11-02 | minor | M3, #1885: glass bends the backdrop towards its core, the shape shrunk by `depth` and the bevel, as the reference tool's: round a sharp corner the bend turns smoothly instead of meeting along the diagonal, and a part thinner than twice that (a capsule, a letter's stroke) bends across itself towards its own middle (pixels about as deep as any within 2 px). Rectangles, frames, components, instances and sections whose corners aren't smoothed work their glass out in closed form, with nothing to rasterise, transform or keep: a zoom frame draws in 40 ms instead of 54 and a resize frame in 46 instead of 67 (`glass_render_timings`, release, 2×). Other shapes keep their fields, with the bend directions for the last two depths asked for beside them, so dragging the Depth slider works out only those again. Tests: `glass::tests::a_sharp_corner_bends_round_towards_the_core`, `glass::tests::a_thin_part_bends_across_itself`, `glass::tests::neighbouring_strokes_bend_towards_their_own_middles`, `glass::tests::a_rounded_rectangle_in_closed_form_matches_its_distance_transform`, `glass_cut_tests::what_the_shape_depends_on_works_it_out_again_and_nothing_else_does`. Numbers unchanged |
|
||||
|
||||
@@ -108,3 +108,7 @@ real_name = "Helen Kwok"
|
||||
[people.denisg0mes]
|
||||
real_name = "Denis Gomes"
|
||||
display_name = "Denis Gomes"
|
||||
|
||||
[people.Hamza0101]
|
||||
real_name = "Hamza Naveed"
|
||||
display_name = "Hamza0101"
|
||||
+204
-13
@@ -9,16 +9,20 @@
|
||||
//! interactions, accessibility annotations, Dev Mode resources and measurements) merge item by
|
||||
//! item: both sides changing different items of the list (or one adding items at its end) is no
|
||||
//! conflict, only the same item changed both ways or the list shortened on a side while the other
|
||||
//! changed it. Nothing that conflicts is merged until it is resolved: each conflict is resolved for
|
||||
//! one side, and the other side's changes to it are left out. Everything else from both sides is
|
||||
//! kept.
|
||||
//! changed it. Auto layout settings (a frame's and a child's) merge field by field: each field
|
||||
//! changed both ways is a conflict of its own, and the other fields merge. Values a file works out
|
||||
//! for itself (a size or place auto layout gives a layer, text sizing to its characters, a value a
|
||||
//! layer in an instance takes from its main component) never conflict: the merged file works them
|
||||
//! out again from what they follow. Nothing that conflicts is merged until it is resolved: each
|
||||
//! conflict is resolved for one side, and the other side's changes to it are left out. Everything
|
||||
//! else from both sides is kept.
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::fmt;
|
||||
|
||||
use figcraft_doc::{Document, NodeId};
|
||||
use figcraft_doc::{Document, Node, NodeId, NodeKind, Sizing, TextAutoResize};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
use serde_json::{Map, Value};
|
||||
|
||||
use crate::change::{Change, DocProp, Entry, Json, Prop};
|
||||
use crate::replica::{Mode, Positions, Replica, create_change};
|
||||
@@ -33,6 +37,7 @@ pub enum Side {
|
||||
}
|
||||
|
||||
impl Side {
|
||||
/// The side that isn't `self`.
|
||||
pub fn other(self) -> Side {
|
||||
match self {
|
||||
Side::Branch => Side::Main,
|
||||
@@ -48,6 +53,7 @@ impl Side {
|
||||
}
|
||||
}
|
||||
|
||||
/// The side `"branch"` or `"main"` names (`None` for anything else).
|
||||
pub fn parse(s: &str) -> Option<Side> {
|
||||
match s {
|
||||
"branch" => Some(Side::Branch),
|
||||
@@ -62,6 +68,9 @@ impl Side {
|
||||
pub enum Key {
|
||||
/// A layer property. A layer's parent and position are one property (where it is).
|
||||
Node(NodeId, Prop),
|
||||
/// One field of a layer property that merges field by field ([`PER_FIELD`]): `padding` of
|
||||
/// `layout`, `sizing_h` of `childLayout`…
|
||||
Field(NodeId, Prop, String),
|
||||
/// A layer deleted on one side and edited (it or what's inside it) on the other.
|
||||
Layer(NodeId),
|
||||
/// A document-level property.
|
||||
@@ -78,11 +87,13 @@ fn camel<T: Serialize>(v: &T) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// `12/fills`, `12/layer`, `doc/styleOrder`, `style/S:3`, `comment/7`… (the keys resolutions use).
|
||||
/// `12/fills`, `12/layout.padding`, `12/layer`, `doc/styleOrder`, `style/S:3`, `comment/7`… (the
|
||||
/// keys resolutions use).
|
||||
impl fmt::Display for Key {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Key::Node(id, prop) => write!(f, "{id}/{}", camel(prop)),
|
||||
Key::Field(id, prop, field) => write!(f, "{id}/{}.{field}", camel(prop)),
|
||||
Key::Layer(id) => write!(f, "{id}/layer"),
|
||||
Key::Doc(prop) => write!(f, "doc/{}", camel(prop)),
|
||||
Key::Entry(e) => match e {
|
||||
@@ -129,10 +140,25 @@ pub struct Plan {
|
||||
/// The main file's changes since the base.
|
||||
pub main: Vec<Change>,
|
||||
pub conflicts: Vec<Conflict>,
|
||||
/// Layer properties changed both ways to values both files work out for themselves
|
||||
/// ([`computed`]): no conflict, and a merge leaves the file merged into its own value.
|
||||
derived: BTreeSet<Key>,
|
||||
/// Layer properties ([`Key::Node`]) merged field by field with fields in conflict.
|
||||
fields: BTreeMap<Key, Fields>,
|
||||
branch_positions: Positions,
|
||||
main_positions: Positions,
|
||||
}
|
||||
|
||||
/// A layer property merged field by field ([`merge_fields`]): the value with every field changed
|
||||
/// one way (or the same way on both sides) merged, and each side's values of the fields changed
|
||||
/// both ways (`Null` for a field a side left out).
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
struct Fields {
|
||||
merged: Map<String, Value>,
|
||||
branch: Map<String, Value>,
|
||||
main: Map<String, Value>,
|
||||
}
|
||||
|
||||
/// Document-level properties that belong to each copy, not to the work: the file name (a branch
|
||||
/// is named after itself) and the page it opens on.
|
||||
fn merges(c: &Change) -> bool {
|
||||
@@ -152,6 +178,7 @@ fn key_of(c: &Change) -> Option<Key> {
|
||||
})
|
||||
}
|
||||
|
||||
/// The changes (indexes) in `changes` grouped by what they write ([`key_of`]).
|
||||
fn by_key(changes: &[Change]) -> BTreeMap<Key, Vec<usize>> {
|
||||
let mut out: BTreeMap<Key, Vec<usize>> = BTreeMap::new();
|
||||
for (i, c) in changes.iter().enumerate() {
|
||||
@@ -193,6 +220,108 @@ fn merged_list(base: &Document, key: &Key, b: Option<&Change>, m: Option<&Change
|
||||
merge_items(o.0.as_array()?, bv.0.as_array()?, mv.0.as_array()?).map(|v| Json(Value::Array(v)))
|
||||
}
|
||||
|
||||
/// Layer properties whose fields merge one by one: auto layout settings, a frame's (`layout`) and
|
||||
/// a child's (`childLayout`). Changing the padding on one side and the gap on the other is no
|
||||
/// conflict, and each field changed both ways is a conflict of its own ([`Key::Field`]).
|
||||
const PER_FIELD: &[Prop] = &[Prop::Layout, Prop::ChildLayout];
|
||||
|
||||
/// Three-way merge of object `o` changed to `b` on one side and `m` on the other, field by field:
|
||||
/// a field changed on one side takes that side's value, and one changed both ways (differently)
|
||||
/// is in conflict. `None` when any of them isn't an object (auto layout added or removed).
|
||||
fn merge_fields(o: &Value, b: &Value, m: &Value) -> Option<Fields> {
|
||||
let (o, b, m) = (o.as_object()?, b.as_object()?, m.as_object()?);
|
||||
let names: BTreeSet<&String> = o.keys().chain(b.keys()).chain(m.keys()).collect();
|
||||
let mut out = Fields::default();
|
||||
for name in names {
|
||||
let (base, x, y) = (o.get(name), b.get(name), m.get(name));
|
||||
let kept = if x == base {
|
||||
y
|
||||
} else if y == base || x == y {
|
||||
x
|
||||
} else {
|
||||
out.branch.insert(name.clone(), x.cloned().unwrap_or(Value::Null));
|
||||
out.main.insert(name.clone(), y.cloned().unwrap_or(Value::Null));
|
||||
base
|
||||
};
|
||||
if let Some(v) = kept {
|
||||
out.merged.insert(name.clone(), v.clone());
|
||||
}
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// Both sides' writes `b` and `m` of property `key` (one of [`PER_FIELD`]) merged field by field
|
||||
/// against the base; `None` when `key` isn't such a property or a value isn't an object.
|
||||
fn merged_fields(base: &Document, key: &Key, b: Option<&Change>, m: Option<&Change>) -> Option<Fields> {
|
||||
let Key::Node(id, prop) = key else { return None };
|
||||
let (Some(Change::Set { value: bv, .. }), Some(Change::Set { value: mv, .. })) = (b, m) else { return None };
|
||||
if !PER_FIELD.contains(prop) {
|
||||
return None;
|
||||
}
|
||||
let o = prop.get(base.node(*id)?).ok()?;
|
||||
merge_fields(&o.0, &bv.0, &mv.0)
|
||||
}
|
||||
|
||||
/// Whether layer `n` of `doc` is placed by its parent's auto layout (not absolute).
|
||||
fn in_flow(doc: &Document, n: &Node) -> bool {
|
||||
!n.child_layout.absolute && n.parent.and_then(|p| doc.node(p)).is_some_and(|p| p.layout.is_some())
|
||||
}
|
||||
|
||||
/// Whether auto layout or text works out layer `n`'s width (`horizontal`) or height: an auto layout
|
||||
/// frame hugging its contents, a child filling its auto layout parent, or text sizing to its
|
||||
/// characters.
|
||||
fn sized_for_itself(doc: &Document, n: &Node, horizontal: bool) -> bool {
|
||||
let sizing = if horizontal { n.child_layout.sizing_h } else { n.child_layout.sizing_v };
|
||||
let by_layout = match sizing {
|
||||
Sizing::Hug => n.layout.is_some(),
|
||||
Sizing::Fill => in_flow(doc, n),
|
||||
Sizing::Fixed => false,
|
||||
};
|
||||
let by_text = match &n.kind {
|
||||
NodeKind::Text(t) => t.auto_resize == TextAutoResize::WidthAndHeight || (!horizontal && t.auto_resize == TextAutoResize::Height),
|
||||
_ => false,
|
||||
};
|
||||
by_layout || by_text
|
||||
}
|
||||
|
||||
/// Whether layer `n` of `doc` (an instance, or a layer inside one) has property `prop` as its main
|
||||
/// component's layer has it: it follows the main rather than overriding it.
|
||||
fn follows_main(doc: &Document, n: &Node, prop: Prop) -> bool {
|
||||
let main = match &n.kind {
|
||||
NodeKind::Instance { component, .. } => Some(*component),
|
||||
_ => n.source,
|
||||
};
|
||||
Prop::FIELDS.contains(&prop) && main.and_then(|m| doc.node(m)).is_some_and(|m| !prop.differs(n, m))
|
||||
}
|
||||
|
||||
/// Whether layer property `key` holds a value `doc` works out for itself rather than one set on
|
||||
/// the layer: a size auto layout or text gives it ([`sized_for_itself`]), its place in an auto
|
||||
/// layout parent, or a value it takes from its main component ([`follows_main`]).
|
||||
fn computed(doc: &Document, key: &Key) -> bool {
|
||||
let Key::Node(id, prop) = key else { return false };
|
||||
let Some(n) = doc.node(*id) else { return false };
|
||||
let by_layout = match prop {
|
||||
Prop::Width => sized_for_itself(doc, n, true),
|
||||
Prop::Height => sized_for_itself(doc, n, false),
|
||||
Prop::Transform => in_flow(doc, n),
|
||||
_ => false,
|
||||
};
|
||||
by_layout || follows_main(doc, n, *prop)
|
||||
}
|
||||
|
||||
/// Whether property `key`, changed both ways, is one both files work out for themselves
|
||||
/// ([`computed`]), so neither side's value is a choice to make. A place given by auto layout is
|
||||
/// only that when both sides also turn and scale the layer the same way (a rotation is set on the
|
||||
/// layer, not worked out).
|
||||
fn derived_on_both(branch: &Document, main: &Document, key: &Key) -> bool {
|
||||
if !(computed(branch, key) && computed(main, key)) {
|
||||
return false;
|
||||
}
|
||||
let Key::Node(id, Prop::Transform) = key else { return true };
|
||||
let linear = |doc: &Document| doc.node(*id).map(|n| n.transform.as_coeffs()).map(|c| [c[0], c[1], c[2], c[3]]);
|
||||
linear(branch) == linear(main)
|
||||
}
|
||||
|
||||
/// The change at the only index in `c`.
|
||||
fn only<'a>(c: &[usize], all: &'a [Change]) -> Option<&'a Change> {
|
||||
match c {
|
||||
@@ -265,6 +394,8 @@ pub fn plan(base: &Document, branch: &Document, main: &Document) -> Result<Plan,
|
||||
let mut mc: Vec<Change> = m.changes.into_iter().filter(merges).collect();
|
||||
let mut conflicts = Vec::new();
|
||||
let mut lists = Vec::new();
|
||||
let mut derived = BTreeSet::new();
|
||||
let mut fields = BTreeMap::new();
|
||||
let km = by_key(&mc);
|
||||
for (k, bi) in by_key(&bc) {
|
||||
// Deletions conflict with edits (below); images are content-addressed, so never differ.
|
||||
@@ -279,13 +410,28 @@ pub fn plan(base: &Document, branch: &Document, main: &Document) -> Result<Plan,
|
||||
if same {
|
||||
continue;
|
||||
}
|
||||
match merged_list(base, &k, only(&bi, &bc), only(mi, &mc)) {
|
||||
Some(value) => lists.push((bi, mi.clone(), value)),
|
||||
None => conflicts.push(Conflict { key: k, deleted_by: None, branch: bi, main: mi.clone() }),
|
||||
if derived_on_both(branch, main, &k) {
|
||||
derived.insert(k);
|
||||
continue;
|
||||
}
|
||||
if let Some(value) = merged_list(base, &k, only(&bi, &bc), only(mi, &mc)) {
|
||||
lists.push((bi, mi.clone(), value));
|
||||
continue;
|
||||
}
|
||||
match (&k, merged_fields(base, &k, only(&bi, &bc), only(mi, &mc))) {
|
||||
(_, Some(f)) if f.branch.is_empty() => lists.push((bi, mi.clone(), Json(Value::Object(f.merged)))),
|
||||
(Key::Node(id, prop), Some(f)) => {
|
||||
for name in f.branch.keys() {
|
||||
let key = Key::Field(*id, *prop, name.clone());
|
||||
conflicts.push(Conflict { key, deleted_by: None, branch: bi.clone(), main: mi.clone() });
|
||||
}
|
||||
fields.insert(k, f);
|
||||
}
|
||||
_ => conflicts.push(Conflict { key: k, deleted_by: None, branch: bi, main: mi.clone() }),
|
||||
}
|
||||
}
|
||||
// Both sides' writes of a list merged item by item become the merged list, so merging either
|
||||
// way writes it.
|
||||
// Both sides' writes of a list merged item by item (or of auto layout settings merged field by
|
||||
// field) become the merged value, so merging either way writes it.
|
||||
for (bi, mi, value) in lists {
|
||||
for (changes, at) in [(&mut bc, bi), (&mut mc, mi)] {
|
||||
for i in at {
|
||||
@@ -313,6 +459,8 @@ pub fn plan(base: &Document, branch: &Document, main: &Document) -> Result<Plan,
|
||||
branch: bc,
|
||||
main: mc,
|
||||
conflicts,
|
||||
derived,
|
||||
fields,
|
||||
branch_positions: b.replica.positions().clone(),
|
||||
main_positions: m.replica.positions().clone(),
|
||||
})
|
||||
@@ -332,6 +480,42 @@ impl Plan {
|
||||
}
|
||||
}
|
||||
|
||||
/// Layer properties both sides changed to values both files work out for themselves (a size or
|
||||
/// place auto layout gives, a value an instance takes from its main): not conflicts, and
|
||||
/// merging leaves the file merged into its own value for the merged file to work out again.
|
||||
pub fn derived(&self) -> &BTreeSet<Key> {
|
||||
&self.derived
|
||||
}
|
||||
|
||||
/// The branch's and main's values of field conflict `key` ([`Key::Field`]); `None` for other
|
||||
/// keys.
|
||||
pub fn field_values(&self, key: &Key) -> Option<(&Value, &Value)> {
|
||||
let Key::Field(id, prop, name) = key else { return None };
|
||||
let f = self.fields.get(&Key::Node(*id, *prop))?;
|
||||
Some((f.branch.get(name)?, f.main.get(name)?))
|
||||
}
|
||||
|
||||
/// The side `pick` chose for each field in conflict of every property merged field by field,
|
||||
/// written into the value merged from the other fields: the writes that replace both sides'
|
||||
/// own writes of those properties.
|
||||
fn field_writes(&self, pick: &dyn Fn(&Key) -> Option<Side>) -> Vec<Change> {
|
||||
let mut out = Vec::new();
|
||||
for (key, f) in &self.fields {
|
||||
let Key::Node(id, prop) = key else { continue };
|
||||
let mut value = f.merged.clone();
|
||||
for name in f.branch.keys() {
|
||||
let won = if pick(&Key::Field(*id, *prop, name.clone())) == Some(Side::Branch) { &f.branch } else { &f.main };
|
||||
match won.get(name) {
|
||||
Some(Value::Null) | None => value.remove(name),
|
||||
Some(v) => value.insert(name.clone(), v.clone()),
|
||||
};
|
||||
}
|
||||
out.push(Change::Set { id: *id, prop: *prop, value: Json(Value::Object(value)) });
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// `side`'s positions (fractional keys) of the layers, for applying its changes elsewhere.
|
||||
fn positions(&self, side: Side) -> &Positions {
|
||||
match side {
|
||||
Side::Branch => &self.branch_positions,
|
||||
@@ -355,7 +539,10 @@ impl Plan {
|
||||
let mut skip: BTreeSet<usize> = BTreeSet::new();
|
||||
let mut batch = Vec::new();
|
||||
for c in &self.conflicts {
|
||||
if pick(&c.key) != Some(from) {
|
||||
if matches!(c.key, Key::Field(..)) {
|
||||
// Written whole below, each field from the side picked for it.
|
||||
skip.extend(c.changes(from));
|
||||
} else if pick(&c.key) != Some(from) {
|
||||
skip.extend(c.changes(from));
|
||||
} else if let (Key::Layer(id), Some(by)) = (&c.key, c.deleted_by)
|
||||
&& by != from
|
||||
@@ -372,7 +559,11 @@ impl Plan {
|
||||
// shortcut: images a side stopped using are kept (unused ones cost file size only); drop
|
||||
// them if files grow.
|
||||
let kept = |c: &Change| !matches!(c, Change::Remove { entry: Entry::Image(_) });
|
||||
batch.extend(self.changes(from).iter().enumerate().filter(|(i, c)| !skip.contains(i) && kept(c)).map(|(_, c)| c.clone()));
|
||||
// Values both files work out for themselves stay as `into` has them; normalising the merged
|
||||
// file works them out again from what changed.
|
||||
let own = |c: &Change| key_of(c).is_some_and(|k| self.derived.contains(&k));
|
||||
batch.extend(self.changes(from).iter().enumerate().filter(|(i, c)| !skip.contains(i) && kept(c) && !own(c)).map(|(_, c)| c.clone()));
|
||||
batch.extend(self.field_writes(pick));
|
||||
let mut r = Replica::from_parts(into.clone(), self.positions(from.other()).clone());
|
||||
let applied = r.apply(&batch, Mode::Strict)?;
|
||||
Ok((r.document().clone(), applied.touched))
|
||||
|
||||
@@ -28,9 +28,15 @@ impl RouteEnd {
|
||||
/// How far an elbow connector going around the objects it joins keeps from them.
|
||||
const ROOM: f64 = 24.0;
|
||||
|
||||
/// The points a connector runs through from `from` to `to`: from the middle of the side of each
|
||||
/// box facing the other end (or the side it names), straight, in right angles, or (curved) its two
|
||||
/// ends with the curve's two control points between them. `None` when a point isn't finite.
|
||||
/// How far outside the border a connector attached to a side starts and ends (#1916): the stroke's
|
||||
/// round cap never lies on the fill, and elbows leaving one side share their first run along the
|
||||
/// side's normal (curves leave tangent to it), as FigJam's connectors do.
|
||||
pub const END_GAP: f64 = 4.0;
|
||||
|
||||
/// The points a connector runs through from `from` to `to`: from [`END_GAP`] outside the middle of
|
||||
/// the side of each box facing the other end (or the side it names), straight, in right angles, or
|
||||
/// (curved) its two ends with the curve's two control points between them. `None` when a point isn't
|
||||
/// finite.
|
||||
pub fn route_points(from: RouteEnd, to: RouteEnd, routing: Routing) -> Option<Vec<Point>> {
|
||||
let (p0, s0) = attach(from, to.centre());
|
||||
let (p1, s1) = attach(to, from.centre());
|
||||
@@ -169,8 +175,9 @@ fn attach(e: RouteEnd, other: Point) -> (Point, Option<Side>) {
|
||||
RouteEnd::Point(p) => (p, None),
|
||||
RouteEnd::Box(b, side) => {
|
||||
let side = named_or_facing(b, side, other);
|
||||
(side.point(b), Some(side))
|
||||
(side.point(b) + side.normal() * END_GAP, Some(side))
|
||||
}
|
||||
// Placed by hand: the point is the user's, gap or not.
|
||||
RouteEnd::On(b, side, p) => (p, Some(named_or_facing(b, side, other))),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
//! Connector routes (`board_route`): where an end attached to a side starts (#1916).
|
||||
|
||||
use figcraft_geom::{Point, Rect};
|
||||
|
||||
use crate::board::{Routing, Side};
|
||||
use crate::board_route::{END_GAP, RouteEnd, route_points};
|
||||
|
||||
fn shape(x: f64, y: f64) -> Rect {
|
||||
Rect::new(x, y, x + 100.0, y + 60.0)
|
||||
}
|
||||
|
||||
/// An end attached to a side starts `END_GAP` outside the middle of that side, not on the border,
|
||||
/// so the stroke never lies on the fill (#1916: FigJam starts the line a few pixels outside).
|
||||
#[test]
|
||||
fn an_attached_end_starts_outside_the_border() {
|
||||
let (a, b) = (shape(0.0, 0.0), shape(300.0, 0.0));
|
||||
for routing in [Routing::Straight, Routing::Elbow, Routing::Curved] {
|
||||
let pts = route_points(RouteEnd::Box(a, Side::Auto), RouteEnd::Box(b, Side::Auto), routing).unwrap();
|
||||
assert_eq!(pts.first().copied(), Some(Point::new(100.0 + END_GAP, 30.0)), "{routing:?}: leaves the right side");
|
||||
assert_eq!(pts.last().copied(), Some(Point::new(300.0 - END_GAP, 30.0)), "{routing:?}: arrives at the left side");
|
||||
}
|
||||
// A named side, and the gap along its own normal.
|
||||
let pts = route_points(RouteEnd::Box(a, Side::Bottom), RouteEnd::Point(Point::new(50.0, 200.0)), Routing::Straight).unwrap();
|
||||
assert_eq!(pts.first().copied(), Some(Point::new(50.0, 60.0 + END_GAP)));
|
||||
}
|
||||
|
||||
/// Elbows leaving one side share their first run along its normal, and curves leave tangent to it:
|
||||
/// the second point of each lies straight out of the side.
|
||||
#[test]
|
||||
fn connectors_from_one_side_leave_together() {
|
||||
let a = shape(0.0, 0.0);
|
||||
let (up, down) = (RouteEnd::Box(shape(300.0, -200.0), Side::Auto), RouteEnd::Box(shape(300.0, 200.0), Side::Auto));
|
||||
for routing in [Routing::Elbow, Routing::Curved] {
|
||||
let p = route_points(RouteEnd::Box(a, Side::Right), up, routing).unwrap();
|
||||
let q = route_points(RouteEnd::Box(a, Side::Right), down, routing).unwrap();
|
||||
assert_eq!(p[0], q[0], "{routing:?}: the same start");
|
||||
assert_eq!(p[1].y, p[0].y, "{routing:?}: out along the side's normal first");
|
||||
assert_eq!(q[1].y, q[0].y, "{routing:?}: out along the side's normal first");
|
||||
}
|
||||
}
|
||||
|
||||
/// A point placed by hand on the object (`RouteEnd::On`) is the user's: no gap is added.
|
||||
#[test]
|
||||
fn a_hand_placed_end_keeps_its_point() {
|
||||
let a = shape(0.0, 0.0);
|
||||
let on = Point::new(80.0, 60.0);
|
||||
let pts = route_points(RouteEnd::On(a, Side::Bottom, on), RouteEnd::Point(Point::new(80.0, 200.0)), Routing::Straight).unwrap();
|
||||
assert_eq!(pts.first().copied(), Some(on));
|
||||
}
|
||||
+10
-1
@@ -27,7 +27,7 @@ pub mod vector_faces;
|
||||
pub mod vector_regions;
|
||||
|
||||
pub use board::*;
|
||||
pub use board_route::{RouteEnd, attached_sides, path_handles, reshaped, route_along, route_points};
|
||||
pub use board_route::{END_GAP, RouteEnd, attached_sides, path_handles, reshaped, route_along, route_points};
|
||||
pub use colors::*;
|
||||
pub use comments::*;
|
||||
pub use facilitation::*;
|
||||
@@ -598,7 +598,14 @@ impl Document {
|
||||
let Some(n) = self.node(id) else { return Affine::IDENTITY };
|
||||
let mut t = n.transform;
|
||||
let mut parent = n.parent;
|
||||
// More hops than nodes means the parent chain loops (a restored snapshot can leave one):
|
||||
// stop rather than spin.
|
||||
let mut hops = 0;
|
||||
while let Some(p) = parent.and_then(|p| self.node(p)).filter(|p| p.kind.bounds_follow_children()) {
|
||||
hops += 1;
|
||||
if hops > self.nodes.len() {
|
||||
break;
|
||||
}
|
||||
t = p.transform * t;
|
||||
parent = p.parent;
|
||||
}
|
||||
@@ -1303,6 +1310,8 @@ fn remap_action(a: &mut proto::Action, map: &BTreeMap<NodeId, NodeId>) {
|
||||
#[cfg(test)]
|
||||
mod blur_tests;
|
||||
#[cfg(test)]
|
||||
mod board_route_tests;
|
||||
#[cfg(test)]
|
||||
mod board_shape_tests;
|
||||
#[cfg(test)]
|
||||
mod boolean_hit_tests;
|
||||
|
||||
@@ -861,6 +861,19 @@ fn the_colour_walker_visits_calculation_literals() {
|
||||
assert_eq!(literal.a, 0.5, "the mix's stored literal was converted like every other colour");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn frame_relative_ends_on_a_looping_parent_chain() {
|
||||
let mut d = Document::new("x");
|
||||
let p = page(&d);
|
||||
let f = d.create(p, NodeKind::Group, "F", 0.0, 0.0, 100.0, 100.0).unwrap();
|
||||
let g = d.create(f, NodeKind::Group, "G", 0.0, 0.0, 10.0, 10.0).unwrap();
|
||||
let mut v = serde_json::to_value(&d).unwrap();
|
||||
// F's parent is its own child G (as a restored snapshot can leave things).
|
||||
v["nodes"][f.to_string()]["parent"] = serde_json::json!(g);
|
||||
let bad: Document = serde_json::from_value(v).unwrap();
|
||||
let _ = bad.frame_relative(g);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remove_children_removes_every_subtree_and_keeps_the_parent() {
|
||||
let mut doc = Document::new("T");
|
||||
|
||||
@@ -345,3 +345,16 @@ fn remove_all_auto_layout_strips_the_frame_and_every_frame_nested_in_it() {
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(laid_out(&s), [true, true, true]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reorder_rejects_negative_and_fractional_indexes() {
|
||||
let mut s = Session::new();
|
||||
let f = frame(&mut s, None, 0.0, 0.0, 200.0, 200.0);
|
||||
let a = rect(&mut s, Some(f), 0.0, 0.0, 10.0, 10.0);
|
||||
let b = rect(&mut s, Some(f), 0.0, 0.0, 10.0, 10.0);
|
||||
let c = rect(&mut s, Some(f), 0.0, 0.0, 10.0, 10.0);
|
||||
for bad in [json!(-1), json!(0.5), json!("x")] {
|
||||
assert!(s.execute("node.reorder", &json!({"id": c, "index": bad})).is_err(), "{bad} accepted");
|
||||
assert_eq!(kids(&s, f), vec![a, b, c]);
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
//! command and a drag of the selected connector's end), curved connectors, and elbows that go
|
||||
//! around the objects they join.
|
||||
|
||||
use figcraft_doc::{BoardItem, End, NodeKind, Routing, Side};
|
||||
use figcraft_doc::{BoardItem, END_GAP, End, NodeKind, Routing, Side};
|
||||
use figcraft_geom::{Point, Rect};
|
||||
use serde_json::json;
|
||||
|
||||
@@ -27,7 +27,7 @@ fn reattach_moves_one_end_and_undoes() {
|
||||
s.execute("board.reattach", &json!({"id": k, "end": "to", "target": c, "side": "top"})).unwrap();
|
||||
assert_eq!(connector(&s, k).to, End::Node { node: c, side: Side::Top, at: None });
|
||||
assert_eq!(connector(&s, k).from.node(), Some(a));
|
||||
assert!(near(*drawn(&s, k).last().unwrap(), Point::new(650.0, 0.0)), "arrives on c's top: {:?}", drawn(&s, k));
|
||||
assert!(near(*drawn(&s, k).last().unwrap(), Point::new(650.0, -END_GAP)), "arrives END_GAP above c's top: {:?}", drawn(&s, k));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(connector(&s, k).to.node(), Some(b), "one undo step");
|
||||
// Off into the canvas: the end stays there, free. The selection is the default connector.
|
||||
@@ -107,9 +107,9 @@ fn curved_connectors_leave_and_arrive_along_the_sides() {
|
||||
let NodeKind::Vector { network } = &n.kind else { panic!("a vector") };
|
||||
assert_eq!((network.vertices.len(), network.segments.len()), (2, 1));
|
||||
assert!(!network.segments[0].is_straight(), "one curve");
|
||||
assert_eq!(drawn(&s, k), vec![Point::new(100.0, 50.0), Point::new(300.0, 50.0)]);
|
||||
assert_eq!(drawn(&s, k), vec![Point::new(104.0, 50.0), Point::new(296.0, 50.0)]);
|
||||
// Side to side in a line: the curve's control points lie on that line, so its box is flat.
|
||||
assert!(n.height.abs() < 1e-9 && (n.width - 200.0).abs() < 1e-9, "{} × {}", n.width, n.height);
|
||||
assert!(n.height.abs() < 1e-9 && (n.width - 192.0).abs() < 1e-9, "{} × {}", n.width, n.height);
|
||||
// From a's bottom to c's top: out downwards and in from above; the box holds the whole curve.
|
||||
let k2 = id(
|
||||
&s.execute("board.connector", &json!({"from": a, "to": c, "fromSide": "bottom", "toSide": "top", "style": "curved", "label": "x"})).unwrap(),
|
||||
@@ -146,18 +146,18 @@ fn elbows_go_around_the_objects_they_join() {
|
||||
let pts = drawn(&s, k2);
|
||||
let (ra, rb) = (Rect::new(0.0, 0.0, 100.0, 100.0), Rect::new(300.0, 0.0, 400.0, 100.0));
|
||||
assert!(!through(&pts, ra) && !through(&pts, rb), "{pts:?}");
|
||||
assert_eq!(pts.first().copied(), Some(Point::new(0.0, 50.0)));
|
||||
assert_eq!(pts.last().copied(), Some(Point::new(400.0, 50.0)));
|
||||
assert_eq!(pts.first().copied(), Some(Point::new(-END_GAP, 50.0)));
|
||||
assert_eq!(pts.last().copied(), Some(Point::new(400.0 + END_GAP, 50.0)));
|
||||
assert_eq!(pts.len(), 6, "out, over, down and in: {pts:?}");
|
||||
assert!(pts.iter().all(|p| p.y <= 50.0), "over the top, the nearer way round: {pts:?}");
|
||||
assert!(pts.windows(2).all(|w| w[0].x == w[1].x || w[0].y == w[1].y), "right angles only");
|
||||
// Facing each other, the short way stays.
|
||||
assert_eq!(drawn(&s, k), vec![Point::new(100.0, 50.0), Point::new(300.0, 50.0)]);
|
||||
assert_eq!(drawn(&s, k), vec![Point::new(104.0, 50.0), Point::new(296.0, 50.0)]);
|
||||
// An end at the bottom of b leaving towards a above it: around b's side and up.
|
||||
s.execute("board.reattach", &json!({"id": k2, "end": "to", "target": b, "side": "bottom"})).unwrap();
|
||||
let pts = drawn(&s, k2);
|
||||
assert!(!through(&pts, ra) && !through(&pts, rb), "{pts:?}");
|
||||
assert_eq!(pts.last().copied(), Some(Point::new(350.0, 100.0)));
|
||||
assert_eq!(pts.last().copied(), Some(Point::new(350.0, 100.0 + END_GAP)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -202,8 +202,12 @@ fn the_connector_being_drawn_is_the_one_made() {
|
||||
// Over b: its four attach points, the one the end is at lit, and b outlined.
|
||||
assert_eq!(ov.drop_target, Some(b));
|
||||
let lit: Vec<[f64; 2]> = ov.attach.iter().filter(|a| a.1).map(|a| a.0).collect();
|
||||
// The lit attach point is the side's middle, on the border; the route's end sits
|
||||
// END_GAP outside it along the side's normal (#1916).
|
||||
let end = *drawn(&s, drawing.id).last().unwrap();
|
||||
assert_eq!((ov.attach.len(), lit), (4, vec![[end.x, end.y]]), "{style}");
|
||||
assert_eq!(ov.attach.len(), 4, "{style}");
|
||||
let [lit] = lit.as_slice() else { panic!("{style}: one lit attach point, got {lit:?}") };
|
||||
assert!(((lit[0] - end.x).abs() + (lit[1] - end.y).abs() - END_GAP).abs() < 1e-9, "{style}: {lit:?} is END_GAP inside {end:?}");
|
||||
} else {
|
||||
assert!(ov.attach.is_empty() && ov.drop_target.is_none(), "a free end");
|
||||
}
|
||||
@@ -259,7 +263,7 @@ fn an_end_dropped_along_a_side_attaches_to_that_side() {
|
||||
s.pointer(&ev(PointerKind::Up, drop)).unwrap();
|
||||
assert_eq!(connector(&s, k).from, End::Node { node: a, side, at: None }, "{drop:?}");
|
||||
if side != Side::Auto {
|
||||
assert_eq!(drawn(&s, k)[0], side.point(bounds), "the route leaves from that side");
|
||||
assert_eq!(drawn(&s, k)[0], side.point(bounds) + side.normal() * END_GAP, "the route leaves from that side, END_GAP out");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -307,5 +311,5 @@ fn a_connector_end_snaps_to_the_attach_point_under_the_pointer() {
|
||||
(connector(&s, k).from, connector(&s, k).to),
|
||||
(End::Node { node: a, side: Side::Right, at: None }, End::Node { node: b, side: Side::Top, at: None })
|
||||
);
|
||||
assert_eq!(drawn(&s, k), vec![Point::new(100.0, 50.0), Point::new(350.0, 200.0)]);
|
||||
assert_eq!(drawn(&s, k), vec![Point::new(104.0, 50.0), Point::new(350.0, 196.0)]);
|
||||
}
|
||||
@@ -11,8 +11,8 @@ use crate::board::{route, selected_connector_handles};
|
||||
use crate::board_tests::{board, connector, drawn, id, near};
|
||||
use crate::tools::{PointerEvent, PointerKind};
|
||||
|
||||
const A: Point = Point::new(100.0, 50.0);
|
||||
const B: Point = Point::new(300.0, 250.0);
|
||||
const A: Point = Point::new(104.0, 50.0);
|
||||
const B: Point = Point::new(296.0, 250.0);
|
||||
|
||||
/// Shapes a (at the origin) and b (down and to the right), 100 × 100, joined side to side.
|
||||
fn joined(style: &str) -> (Session, NodeId, NodeId, NodeId) {
|
||||
@@ -80,11 +80,11 @@ fn a_reshaped_connector_keeps_the_sides_it_left_by() {
|
||||
fn the_first_and_last_runs_gain_a_run_and_stay_on_their_ends() {
|
||||
let (mut s, _, _, k) = joined("elbow");
|
||||
reshape(&mut s, k, 0.0, 150.0, 120.0).unwrap();
|
||||
assert_eq!(drawn(&s, k), [A, pt(124.0, 50.0), pt(124.0, 120.0), pt(200.0, 120.0), pt(200.0, 250.0), B]);
|
||||
assert_eq!(drawn(&s, k), [A, pt(128.0, 50.0), pt(128.0, 120.0), pt(200.0, 120.0), pt(200.0, 250.0), B]);
|
||||
let last = drawn(&s, k).len() - 2;
|
||||
reshape(&mut s, k, last as f64, 250.0, 200.0).unwrap();
|
||||
let pts = drawn(&s, k);
|
||||
assert_eq!(pts, [A, pt(124.0, 50.0), pt(124.0, 120.0), pt(200.0, 120.0), pt(200.0, 200.0), pt(276.0, 200.0), pt(276.0, 250.0), B]);
|
||||
assert_eq!(pts, [A, pt(128.0, 50.0), pt(128.0, 120.0), pt(200.0, 120.0), pt(200.0, 200.0), pt(272.0, 200.0), pt(272.0, 250.0), B]);
|
||||
assert!(right_angled(&pts));
|
||||
}
|
||||
|
||||
@@ -97,8 +97,8 @@ fn a_lone_run_gains_a_run_at_each_end() {
|
||||
let k = id(&s.execute("board.connector", &json!({"from": a, "to": b, "style": "elbow"})).unwrap(), "id");
|
||||
assert_eq!(drawn(&s, k).len(), 2);
|
||||
reshape(&mut s, k, 0.0, 200.0, -40.0).unwrap();
|
||||
let (l, r) = (pt(100.0, 50.0), pt(300.0, 50.0));
|
||||
assert_eq!(drawn(&s, k), [l, pt(124.0, 50.0), pt(124.0, -40.0), pt(276.0, -40.0), pt(276.0, 50.0), r]);
|
||||
let (l, r) = (pt(104.0, 50.0), pt(296.0, 50.0));
|
||||
assert_eq!(drawn(&s, k), [l, pt(128.0, 50.0), pt(128.0, -40.0), pt(272.0, -40.0), pt(272.0, 50.0), r]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -168,7 +168,7 @@ fn connectors_follow_what_they_join_and_undo_with_it() {
|
||||
let b = id(&s.execute("board.sticky", &json!({"x": 400, "y": 0})).unwrap(), "id");
|
||||
let c = id(&s.execute("board.connector", &json!({"from": a, "to": b, "style": "straight", "label": "then"})).unwrap(), "id");
|
||||
let pts = drawn(&s, c);
|
||||
assert!(near(pts[0], Point::new(200.0, 100.0)) && near(pts[1], Point::new(400.0, 100.0)), "{pts:?}");
|
||||
assert!(near(pts[0], Point::new(204.0, 100.0)) && near(pts[1], Point::new(396.0, 100.0)), "{pts:?}");
|
||||
assert_eq!(node(&s, c).stroke.cap_end, StrokeCap::TriangleArrow);
|
||||
// Its label sits at the middle.
|
||||
let label = crate::board::label_of(s.doc().unwrap(), c).unwrap();
|
||||
@@ -178,19 +178,19 @@ fn connectors_follow_what_they_join_and_undo_with_it() {
|
||||
s.execute("board.setStyle", &json!({"ids": [c], "style": "elbow"})).unwrap();
|
||||
s.execute("transform.move", &json!({"ids": [b], "dx": 0, "dy": 300})).unwrap();
|
||||
let pts = drawn(&s, c);
|
||||
assert!(near(pts[0], Point::new(200.0, 100.0)) && near(*pts.last().unwrap(), Point::new(400.0, 400.0)), "{pts:?}");
|
||||
assert!(near(pts[0], Point::new(204.0, 100.0)) && near(*pts.last().unwrap(), Point::new(396.0, 400.0)), "{pts:?}");
|
||||
assert!(pts.windows(2).all(|w| w[0].x == w[1].x || w[0].y == w[1].y), "right angles: {pts:?}");
|
||||
// Undo takes the move back and the route with it.
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(near(*drawn(&s, c).last().unwrap(), Point::new(400.0, 100.0)));
|
||||
assert!(near(*drawn(&s, c).last().unwrap(), Point::new(396.0, 100.0)));
|
||||
// A deleted end stays where it was, as a point.
|
||||
s.execute("edit.delete", &json!({"ids": [b]})).unwrap();
|
||||
assert!(matches!(connector(&s, c).to, End::Point { .. }));
|
||||
assert!(near(*drawn(&s, c).last().unwrap(), Point::new(400.0, 100.0)));
|
||||
assert!(near(*drawn(&s, c).last().unwrap(), Point::new(396.0, 100.0)));
|
||||
// A connector moved on its own takes its free end along; the attached one stays.
|
||||
s.execute("transform.move", &json!({"ids": [c], "dx": 0, "dy": 50})).unwrap();
|
||||
assert!(matches!(connector(&s, c).to, End::Point { x, y } if x == 400.0 && y == 150.0), "{:?}", connector(&s, c));
|
||||
assert!(near(drawn(&s, c)[0], Point::new(200.0, 100.0)));
|
||||
assert!(matches!(connector(&s, c).to, End::Point { x, y } if x == 396.0 && y == 150.0), "{:?}", connector(&s, c));
|
||||
assert!(near(drawn(&s, c)[0], Point::new(204.0, 100.0)));
|
||||
// Deleting the connector takes its label.
|
||||
s.execute("edit.delete", &json!({"ids": [c]})).unwrap();
|
||||
assert!(!s.doc().unwrap().contains(label));
|
||||
@@ -210,8 +210,8 @@ fn routes_are_the_same_for_the_same_document() {
|
||||
let doc = s.doc().unwrap();
|
||||
let r = route(doc, &c).unwrap();
|
||||
assert_eq!(r, route(&doc.clone(), &c).unwrap());
|
||||
// Down out of the bottom, across halfway, down into the point.
|
||||
assert_eq!(r, vec![Point::new(80.0, 160.0), Point::new(80.0, 330.0), Point::new(300.0, 330.0), Point::new(300.0, 500.0)]);
|
||||
// Down out of the bottom (END_GAP below it), across halfway, down into the point.
|
||||
assert_eq!(r, vec![Point::new(80.0, 164.0), Point::new(80.0, 332.0), Point::new(300.0, 332.0), Point::new(300.0, 500.0)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -338,7 +338,7 @@ fn boards_sync_in_live_sessions() {
|
||||
let doc = room.server.document();
|
||||
let NodeKind::Vector { network } = &doc.node(c).unwrap().kind else { panic!("not a vector") };
|
||||
let end = doc.world_transform(c) * network.vertices.last().unwrap().point();
|
||||
assert_eq!(end, Point::new(400.0, 350.0), "to the moved sticky's facing side");
|
||||
assert_eq!(end, Point::new(396.0, 350.0), "to END_GAP before the moved sticky's facing side");
|
||||
assert_eq!(doc.node(a).unwrap().fills[0].solid_color(), board_color("violet"));
|
||||
}
|
||||
|
||||
@@ -410,7 +410,9 @@ fn a_press_on_a_stickys_background_picks_and_drags_it() {
|
||||
s.pointer(&PointerEvent::at(PointerKind::Up, 100.0, 450.0, 1.0)).unwrap();
|
||||
assert_eq!(s.selection(), vec![a]);
|
||||
assert_eq!(node(&s, a).transform.translation().y, 300.0);
|
||||
assert!(near(drawn(&s, c)[0], Point::new(200.0, 400.0)), "the connector followed the drag: {:?}", drawn(&s, c));
|
||||
// Its own connector's start, END_GAP outside its edge, is no snap target for it (#1916).
|
||||
assert_eq!(node(&s, a).transform.translation().x, 0.0, "not nudged sideways by its own connector");
|
||||
assert!(near(drawn(&s, c)[0], Point::new(204.0, 400.0)), "the connector followed the drag: {:?}", drawn(&s, c));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -100,18 +100,18 @@ fn routes_take_named_sides_and_free_points() {
|
||||
let side = |n, side| End::Node { node: n, side, at: None };
|
||||
let p = |x, y| End::Point { x, y };
|
||||
let pt = Point::new;
|
||||
// Side to side: out, across halfway, in.
|
||||
assert_eq!(elbow(side(a, Side::Right), side(b, Side::Left)), vec![pt(100.0, 50.0), pt(200.0, 50.0), pt(200.0, 350.0), pt(300.0, 350.0)]);
|
||||
// Side to side: out (from END_GAP outside each side), across halfway, in.
|
||||
assert_eq!(elbow(side(a, Side::Right), side(b, Side::Left)), vec![pt(104.0, 50.0), pt(200.0, 50.0), pt(200.0, 350.0), pt(296.0, 350.0)]);
|
||||
// A side and a top or bottom: one turn.
|
||||
assert_eq!(elbow(side(a, Side::Right), side(b, Side::Top)), vec![pt(100.0, 50.0), pt(350.0, 50.0), pt(350.0, 300.0)]);
|
||||
assert_eq!(elbow(side(a, Side::Bottom), side(b, Side::Left)), vec![pt(50.0, 100.0), pt(50.0, 350.0), pt(300.0, 350.0)]);
|
||||
assert_eq!(elbow(side(a, Side::Right), side(b, Side::Top)), vec![pt(104.0, 50.0), pt(350.0, 50.0), pt(350.0, 296.0)]);
|
||||
assert_eq!(elbow(side(a, Side::Bottom), side(b, Side::Left)), vec![pt(50.0, 104.0), pt(50.0, 350.0), pt(296.0, 350.0)]);
|
||||
// Two free points: the longer way first; in a line, no turns.
|
||||
assert_eq!(elbow(p(0.0, 0.0), p(100.0, 40.0)), vec![pt(0.0, 0.0), pt(50.0, 0.0), pt(50.0, 40.0), pt(100.0, 40.0)]);
|
||||
assert_eq!(elbow(p(0.0, 0.0), p(100.0, 0.0)), vec![pt(0.0, 0.0), pt(100.0, 0.0)]);
|
||||
// An automatic side faces the other end.
|
||||
let straight =
|
||||
route(doc, &figcraft_doc::Connector { from: side(a, Side::Auto), to: p(50.0, 500.0), routing: figcraft_doc::Routing::Straight, path: None });
|
||||
assert_eq!(straight.unwrap(), vec![pt(50.0, 100.0), pt(50.0, 500.0)]);
|
||||
assert_eq!(straight.unwrap(), vec![pt(50.0, 104.0), pt(50.0, 500.0)]);
|
||||
assert_eq!(Side::from_id("TOP"), Some(Side::Top));
|
||||
assert_eq!(Side::from_id("inside"), None);
|
||||
// The same place twice is refused, as are a side that doesn't exist and a point without numbers.
|
||||
@@ -128,10 +128,10 @@ fn a_connector_follows_a_layer_whose_section_moves_and_ignores_unrelated_edits()
|
||||
let a = id(&s.execute("board.sticky", &json!({"x": 50, "y": 50, "parent": sec})).unwrap(), "id");
|
||||
let b = id(&s.execute("board.stamp", &json!({"x": 800, "y": 150})).unwrap(), "id");
|
||||
let c = id(&s.execute("board.connector", &json!({"from": a, "to": b, "style": "straight"})).unwrap(), "id");
|
||||
assert!(near(drawn(&s, c)[0], Point::new(250.0, 150.0)));
|
||||
assert!(near(drawn(&s, c)[0], Point::new(254.0, 150.0)));
|
||||
// Only the section is edited; the sticky inside it moves with it, and so does the connector.
|
||||
s.execute("transform.move", &json!({"ids": [sec], "dx": 0, "dy": 100})).unwrap();
|
||||
assert!(near(drawn(&s, c)[0], Point::new(250.0, 250.0)), "{:?}", drawn(&s, c));
|
||||
assert!(near(drawn(&s, c)[0], Point::new(254.0, 250.0)), "{:?}", drawn(&s, c));
|
||||
// An edit that touches neither end leaves the connector as it was.
|
||||
let before = s.doc().unwrap().node_arc(c).cloned().unwrap();
|
||||
s.execute("board.sticky", &json!({"x": 0, "y": 900})).unwrap();
|
||||
@@ -276,3 +276,29 @@ fn a_board_tool_left_on_presses_as_move_in_a_design_file() {
|
||||
assert_eq!(s.tool.tool, ToolId::Move);
|
||||
assert_eq!(s.selection(), vec![r], "the press selected as Move does");
|
||||
}
|
||||
|
||||
/// #1916: a connector's start, END_GAP outside the layer it leaves, is a snap line for other layers
|
||||
/// but not for that layer, nor for a section holding it (both carry the connector along), and nor
|
||||
/// is the connector's label.
|
||||
#[test]
|
||||
fn a_connector_joined_to_a_moving_layer_or_its_section_is_no_snap_target() {
|
||||
let mut s = board();
|
||||
let sec = id(&s.execute("node.create", &json!({"type": "section", "x": 0, "y": 0, "width": 300, "height": 300})).unwrap(), "id");
|
||||
let a = id(&s.execute("board.sticky", &json!({"x": 50, "y": 50, "parent": sec})).unwrap(), "id");
|
||||
let b = id(&s.execute("board.stamp", &json!({"x": 800, "y": 150})).unwrap(), "id");
|
||||
let c = id(&s.execute("board.connector", &json!({"from": a, "to": b, "style": "straight", "label": "to"})).unwrap(), "id");
|
||||
// A layer the connector has nothing to do with.
|
||||
let d = id(&s.execute("board.sticky", &json!({"x": 0, "y": 900})).unwrap(), "id");
|
||||
let page = s.page().unwrap();
|
||||
let start = drawn(&s, c)[0].x;
|
||||
let label = crate::board::label_of(s.doc().unwrap(), c).unwrap();
|
||||
let lx = s.doc().unwrap().world_bounds(label).unwrap().x0;
|
||||
// A box whose left edge is 1 past a line snaps back by 1 when the line is a target.
|
||||
let pull = |s: &Session, moving: &[NodeId], x: f64| {
|
||||
let t = crate::snap::Targets::gather(s.doc().unwrap(), page, moving);
|
||||
t.snap_rect(figcraft_geom::Rect::new(x + 1.0, 600.0, x + 9.0, 610.0), 4.0).0
|
||||
};
|
||||
assert_eq!((pull(&s, &[d], start), pull(&s, &[d], lx)), (-1.0, -1.0), "for an unrelated layer, the connector and its label snap");
|
||||
assert_eq!(pull(&s, &[b], start), 0.0, "not for the layer it arrives at");
|
||||
assert_eq!((pull(&s, &[sec], start), pull(&s, &[sec], lx)), (0.0, 0.0), "not for the section the connector leaves from");
|
||||
}
|
||||
@@ -133,13 +133,19 @@ impl Session {
|
||||
(to.node().is_none() || to.node() != from.node()).then_some(to)
|
||||
}
|
||||
|
||||
/// The object `end` is on (if any) outlined, with its attach points; the one the end is at
|
||||
/// (`at`, else its named side's) lit.
|
||||
/// The object `end` is on (if any) outlined, with its attach points (the side middles, on the
|
||||
/// border); the one the end is at lit: the nearest to `at` (a route's end sits `END_GAP` outside
|
||||
/// its side's middle, #1916), else its named side's.
|
||||
fn show_attach(&mut self, end: Option<End>, at: Option<Point>) {
|
||||
let attach = match end {
|
||||
Some(End::Node { node, side, .. }) => self.doc().ok().and_then(|d| d.world_bounds(node)).map(|b| {
|
||||
let on = at.or_else(|| (side != Side::Auto).then(|| side.point(b)));
|
||||
SIDES.map(|s| s.point(b)).map(|p| ([p.x, p.y], on.is_some_and(|o| (o - p).hypot() < 1e-6))).to_vec()
|
||||
let pts = SIDES.map(|s| s.point(b));
|
||||
let lit = on.and_then(|o| {
|
||||
let near = pts.iter().enumerate().map(|(i, p)| (i, (o - *p).hypot())).filter(|(_, d)| *d <= figcraft_doc::END_GAP + 1e-6);
|
||||
near.min_by(|x, y| x.1.total_cmp(&y.1)).map(|(i, _)| i)
|
||||
});
|
||||
pts.iter().enumerate().map(|(i, p)| ([p.x, p.y], lit == Some(i))).collect()
|
||||
}),
|
||||
_ => None,
|
||||
};
|
||||
|
||||
@@ -193,6 +193,109 @@ fn branch_commands_refuse_what_makes_no_sense() {
|
||||
assert!(s.execute("branch.merge", &json!({"id": "nope"})).is_err());
|
||||
}
|
||||
|
||||
/// Node id `v` of a command's answer (`{"id": …}` or a bare id).
|
||||
fn idv(v: &Value) -> NodeId {
|
||||
NodeId(v.get("id").unwrap_or(v).as_u64().unwrap())
|
||||
}
|
||||
|
||||
/// The issue #2026 file, with a branch of it made and shown: a component `Card` (horizontal auto
|
||||
/// layout hugging its contents, padding 12, one 40×20 rectangle) and an instance of it in a
|
||||
/// vertical auto layout frame hugging its contents. Returns (session, branch id, card, instance,
|
||||
/// frame, rectangle).
|
||||
fn card_file() -> (Session, String, NodeId, NodeId, NodeId, NodeId) {
|
||||
let mut s = Session::with_document(Document::new("Cards"));
|
||||
let props = json!({"layout": "horizontal", "padding": 12, "sizingH": "hug", "sizingV": "hug"});
|
||||
let frame = idv(&ok(&mut s, "frame.create", json!({"x": 0, "y": 0, "width": 100, "height": 50, "name": "Card", "props": props})));
|
||||
let rect = idv(&ok(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 40, "height": 20, "parent": frame})));
|
||||
let card = idv(&ok(&mut s, "component.create", json!({"ids": [frame]})));
|
||||
let props = json!({"layout": "vertical", "padding": 0, "sizingH": "hug", "sizingV": "hug"});
|
||||
let stack = idv(&ok(&mut s, "frame.create", json!({"x": 0, "y": 200, "width": 100, "height": 100, "name": "Stack", "props": props})));
|
||||
let inst = idv(&ok(&mut s, "instance.create", json!({"component": card, "parent": stack})));
|
||||
let b = ok(&mut s, "branch.create", json!({"name": "padding 8"}));
|
||||
(s, b["id"].as_str().unwrap().to_string(), card, inst, stack, rect)
|
||||
}
|
||||
|
||||
/// Size and place of every layer of `doc` (what auto layout works out).
|
||||
fn geometry(doc: &Document) -> Vec<(NodeId, [f64; 8])> {
|
||||
doc.nodes()
|
||||
.map(|n| {
|
||||
let c = n.transform.as_coeffs();
|
||||
(n.id, [n.width, n.height, c[0], c[1], c[2], c[3], c[4], c[5]])
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Issue #2026: one auto layout edit on each side is one conflict (the field changed both ways),
|
||||
/// not one for every size and place auto layout works out from it; the merged file lays out
|
||||
/// from the padding picked.
|
||||
#[test]
|
||||
fn one_conflicting_auto_layout_edit_is_one_conflict() {
|
||||
for (pick, padding) in [("branch", 8.0), ("main", 16.0)] {
|
||||
let (mut s, id, card, inst, _, _) = card_file();
|
||||
ok(&mut s, "node.set", json!({"id": card, "props": {"padding": 8}}));
|
||||
ok(&mut s, "doc.switch", json!({"index": 0}));
|
||||
ok(&mut s, "node.set", json!({"id": card, "props": {"padding": 16}}));
|
||||
// What main looks like with the picked padding set directly.
|
||||
let mut direct = Session::with_document(s.doc().unwrap().clone());
|
||||
ok(&mut direct, "node.set", json!({"id": card, "props": {"padding": padding}}));
|
||||
let review = ok(&mut s, "branch.review", json!({"id": id}));
|
||||
let conflicts = review["conflicts"].as_array().unwrap();
|
||||
assert_eq!(conflicts.len(), 1, "{review}");
|
||||
let key = format!("{card}/layout.padding");
|
||||
assert_eq!(conflicts[0]["key"], key.as_str());
|
||||
assert_eq!(
|
||||
(&conflicts[0]["property"], &conflicts[0]["branch"], &conflicts[0]["main"]),
|
||||
(&json!("auto layout padding"), &json!("8, 8, 8, 8"), &json!("16, 16, 16, 16"))
|
||||
);
|
||||
let err = s.execute("branch.merge", &json!({"id": id})).unwrap_err().to_string();
|
||||
assert!(err.contains(&key) && !err.contains("width"), "{err}");
|
||||
ok(&mut s, "branch.merge", json!({"id": id, "resolutions": {&key: pick}}));
|
||||
let doc = s.doc().unwrap();
|
||||
for n in [card, inst] {
|
||||
assert_eq!(doc.node(n).unwrap().layout.as_ref().unwrap().padding, [padding; 4], "{pick} wins");
|
||||
}
|
||||
assert_eq!(geometry(doc), geometry(direct.doc().unwrap()), "{pick} wins: laid out from the padding picked");
|
||||
}
|
||||
}
|
||||
|
||||
/// Auto layout merges field by field: a gap changed only on the branch is kept whichever side's
|
||||
/// padding wins, both when merging and when updating the branch from main.
|
||||
#[test]
|
||||
fn auto_layout_fields_changed_one_way_survive_a_conflict() {
|
||||
for (cmd, pick, padding) in [("branch.merge", "main", 16.0), ("branch.merge", "branch", 8.0), ("branch.updateFromMain", "main", 16.0)] {
|
||||
let (mut s, id, card, _, _, _) = card_file();
|
||||
ok(&mut s, "node.set", json!({"id": card, "props": {"padding": 8, "gap": 30}}));
|
||||
ok(&mut s, "doc.switch", json!({"index": 0}));
|
||||
ok(&mut s, "node.set", json!({"id": card, "props": {"padding": 16, "mainAlign": "center"}}));
|
||||
let key = format!("{card}/layout.padding");
|
||||
let review = ok(&mut s, "branch.review", json!({"id": id}));
|
||||
assert_eq!(review["conflicts"].as_array().unwrap().iter().map(|c| c["key"].clone()).collect::<Vec<_>>(), vec![json!(key)], "{review}");
|
||||
ok(&mut s, cmd, json!({"id": id, "resolutions": {&key: pick}}));
|
||||
if cmd == "branch.updateFromMain" {
|
||||
ok(&mut s, "doc.switch", json!({"index": 1}));
|
||||
}
|
||||
let layout = s.doc().unwrap().node(card).unwrap().layout.clone().unwrap();
|
||||
assert_eq!((layout.padding, layout.gap, layout.main_align), ([padding; 4], 30.0, figcraft_doc::MainAlign::Center), "{cmd}, {pick} wins");
|
||||
}
|
||||
}
|
||||
|
||||
/// Auto layout on one side and a hugging frame's size on both: the sizes auto layout works out
|
||||
/// on each side are no conflict, and merging leaves no stale size behind.
|
||||
#[test]
|
||||
fn sizes_auto_layout_works_out_never_conflict() {
|
||||
let (mut s, id, card, _, stack, rect) = card_file();
|
||||
ok(&mut s, "node.set", json!({"id": rect, "props": {"width": 60}}));
|
||||
ok(&mut s, "doc.switch", json!({"index": 0}));
|
||||
ok(&mut s, "node.set", json!({"id": card, "props": {"padding": 4}}));
|
||||
let review = ok(&mut s, "branch.review", json!({"id": id}));
|
||||
assert_eq!(review["conflicts"], json!([]), "{review}");
|
||||
let mut direct = Session::with_document(s.doc().unwrap().clone());
|
||||
ok(&mut direct, "node.set", json!({"id": rect, "props": {"width": 60}}));
|
||||
ok(&mut s, "branch.merge", json!({"id": id}));
|
||||
assert_eq!(s.doc().unwrap().node(stack).unwrap().width, 60.0 + 8.0);
|
||||
assert_eq!(geometry(s.doc().unwrap()), geometry(direct.doc().unwrap()));
|
||||
}
|
||||
|
||||
/// Every change a side made (that the other side didn't overwrite) shows in `doc`.
|
||||
fn shows(changes: &[Change], doc: &Document) -> Result<(), String> {
|
||||
let r = Replica::new(doc.clone());
|
||||
@@ -282,16 +385,25 @@ fn random_edits_on_both_sides_merge() {
|
||||
let none = |_: &figcraft_collab::merge::Key| None;
|
||||
let (into_main, _) = p.merge(&m, Side::Branch, &none).unwrap_or_else(|e| panic!("seed {seed}: {e}"));
|
||||
let (into_branch, _) = p.merge(&b, Side::Main, &none).unwrap_or_else(|e| panic!("seed {seed}: {e}"));
|
||||
// Values both sides work out for themselves (sizes and places auto layout gives) stay
|
||||
// as the file merged into has them.
|
||||
let chosen = |changes: &[Change]| -> Vec<Change> {
|
||||
changes
|
||||
.iter()
|
||||
.filter(|c| !matches!(c, Change::Set { id, prop, .. } if p.derived().contains(&Key::Node(*id, *prop))))
|
||||
.cloned()
|
||||
.collect()
|
||||
};
|
||||
let mut both = Replica::new(start.clone());
|
||||
both.apply(&p.main, Mode::Strict).unwrap();
|
||||
both.apply(&p.branch, Mode::Strict).unwrap();
|
||||
both.apply(&chosen(&p.branch), Mode::Strict).unwrap();
|
||||
let mut want = both.document().clone();
|
||||
(want.name, want.current_page) = (m.name.clone(), m.current_page);
|
||||
assert_eq!(into_main, want, "seed {seed}");
|
||||
for doc in [&into_main, &into_branch] {
|
||||
assert!(doc.validate().is_empty(), "seed {seed}: {:?}", doc.validate());
|
||||
for side in [&p.branch, &p.main] {
|
||||
shows(side, doc).unwrap_or_else(|c| panic!("seed {seed}: lost {c}"));
|
||||
shows(&chosen(side), doc).unwrap_or_else(|c| panic!("seed {seed}: lost {c}"));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
//! 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::{Document, NodeId};
|
||||
use figcraft_doc::{BoardItem, Document, NodeId};
|
||||
use figcraft_geom::{Affine, Point, Rect, Vec2, transform_rect_bbox};
|
||||
use serde::Serialize;
|
||||
|
||||
@@ -94,10 +94,23 @@ impl Targets {
|
||||
t.ys.push((y, b.x0, b.x1));
|
||||
}
|
||||
}
|
||||
// Siblings and, at the top level, all top-level layers.
|
||||
// Siblings and, at the top level, all top-level layers. A board connector joined to a
|
||||
// moving layer, or to one inside it (a section carries its stickies), re-routes with it, as
|
||||
// does its label: no snapping to where its own route starts (#1916).
|
||||
let carried = |e: NodeId| moving.contains(&e) || doc.ancestors(e).iter().any(|a| moving.contains(a));
|
||||
let follows = |id: NodeId| match doc.node(id).and_then(|n| n.board.as_ref()) {
|
||||
Some(BoardItem::Connector(k)) => [k.from.node(), k.to.node()].into_iter().flatten().any(carried),
|
||||
_ => false,
|
||||
};
|
||||
if let Some(p) = doc.node(parent) {
|
||||
for c in &p.children {
|
||||
if moving.contains(c) || !doc.node(*c).is_some_and(|n| n.visible) {
|
||||
let Some(n) = doc.node(*c).filter(|n| n.visible) else { continue };
|
||||
let joined = match n.board.as_ref() {
|
||||
Some(BoardItem::Connector(_)) => follows(*c),
|
||||
Some(BoardItem::Label { connector }) => follows(*connector),
|
||||
_ => false,
|
||||
};
|
||||
if moving.contains(c) || joined {
|
||||
continue;
|
||||
}
|
||||
if let Some(b) = bbox(*c) {
|
||||
|
||||
@@ -184,14 +184,21 @@ fn edit_if(s: &mut Session, f: impl FnOnce(&mut TextData, &mut TextEdit) -> bool
|
||||
let doc = ds.doc_mut();
|
||||
let n = doc.get_mut(te.id)?;
|
||||
let NodeKind::Text(t) = &mut n.kind else { return Err(EngineError::Other("not a text layer".into())) };
|
||||
let derived_before = crate::cmd::props::text_layer_name(&t.characters);
|
||||
if !f(t, &mut te) {
|
||||
return Ok(false);
|
||||
}
|
||||
// Any edit ends a composition (a commit replaces it with the final text).
|
||||
te.preedit = None;
|
||||
let len = t.char_count();
|
||||
let derived_after = crate::cmd::props::text_layer_name(&t.characters);
|
||||
te.caret = te.caret.min(len);
|
||||
te.anchor = te.anchor.min(len);
|
||||
// The layer's name follows the characters while it is the name they derive, so the Layers
|
||||
// panel keeps up with what the canvas shows; a name the author typed is left alone.
|
||||
if crate::cmd::props::text_name_is_derived(&n.name, derived_before.as_ref()) {
|
||||
n.name = derived_after.unwrap_or_default();
|
||||
}
|
||||
if n.source.is_some() {
|
||||
n.overrides.insert("characters".into());
|
||||
}
|
||||
|
||||
@@ -326,7 +326,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
),
|
||||
spec!("node.reorder", "Reorder layer", "{id, index}", true, |s, p| {
|
||||
let i = req_id("node.reorder", p, "id")?;
|
||||
let idx = req_num("node.reorder", p, "index")?.max(0.0) as usize;
|
||||
let idx = req_index("node.reorder", p, "index")?;
|
||||
s.doc_mut()?.reorder(i, idx)?;
|
||||
ok()
|
||||
}),
|
||||
|
||||
@@ -41,6 +41,30 @@ pub(crate) fn normalize_line_endings(s: &str) -> String {
|
||||
s.replace("\r\n", "\n").replace(['\r', '\u{2028}', '\u{2029}'], "\n")
|
||||
}
|
||||
|
||||
/// The name a text layer derives from its characters: the first line, at most 64 characters, or
|
||||
/// None when that line is blank (a layer with no name of its own, which the Layers panel shows by
|
||||
/// its kind).
|
||||
///
|
||||
/// A layer whose name is this derived name is one nobody has renamed, so the editor keeps its name
|
||||
/// in step as the characters are typed ([`crate::textedit`]); any other name was chosen by the
|
||||
/// author and is kept. Commands never rename, so a layer named for its role keeps that name as a
|
||||
/// field key even when `characters` replace text that reads like it.
|
||||
pub(crate) fn text_layer_name(characters: &str) -> Option<String> {
|
||||
let first: String = characters.lines().next().unwrap_or("").chars().take(64).collect();
|
||||
(!first.trim().is_empty()).then_some(first)
|
||||
}
|
||||
|
||||
/// Whether `name` is one a text layer was given for its characters rather than by its author, so
|
||||
/// the editor may keep it in step with them. Blank text leaves a layer named `""` when the Text
|
||||
/// tool draws it and `Text` when `node.create` makes it, and both read as unnamed in the panel.
|
||||
pub(crate) fn text_name_is_derived(name: &str, derived: Option<&String>) -> bool {
|
||||
match derived {
|
||||
Some(d) => name == d,
|
||||
// `NodeKind::Text(_).label()`, which the panel falls back to for an unnamed layer.
|
||||
None => name.is_empty() || name == "Text",
|
||||
}
|
||||
}
|
||||
|
||||
/// camelCase object keys → snake_case (accept the inspect/camel forms for serde-backed values).
|
||||
pub fn snake(v: &Value) -> Value {
|
||||
match v {
|
||||
|
||||
@@ -46,7 +46,7 @@ fn without_cmd_an_end_keeps_snapping_to_a_side() {
|
||||
let end = *drawn(&s, k).last().unwrap();
|
||||
drag_end(&mut s, end, Point::new(650.0, 25.0), false);
|
||||
assert_eq!(connector(&s, k).to, End::Node { node: b, side: Side::Right, at: None });
|
||||
assert!(near(*drawn(&s, k).last().unwrap(), Point::new(700.0, 50.0)));
|
||||
assert!(near(*drawn(&s, k).last().unwrap(), Point::new(700.0 + figcraft_doc::END_GAP, 50.0)), "END_GAP outside the side");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -611,6 +611,21 @@ fn doc_change(plan: &Plan, c: &Change) -> Option<DocChange> {
|
||||
Some(DocChange { what, change: entry_change(plan, c) })
|
||||
}
|
||||
|
||||
/// One side's value of an auto layout field in conflict, in words: `16`, `8, 8, 8, 8`, `min`,
|
||||
/// `on`, `none`.
|
||||
fn field_text(v: &Value) -> String {
|
||||
match v {
|
||||
Value::Null => "none".to_string(),
|
||||
Value::Bool(on) => if *on { "on" } else { "off" }.to_string(),
|
||||
Value::Number(n) => n.as_f64().map_or_else(|| n.to_string(), |x| x.to_string()),
|
||||
Value::String(s) => words(s),
|
||||
Value::Array(items) => items.iter().map(field_text).collect::<Vec<_>>().join(", "),
|
||||
Value::Object(_) => v.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The review's row for conflict `c`: the layer (or file entry) and property, and what each side
|
||||
/// changed it to.
|
||||
fn conflict_row(plan: &Plan, c: &Conflict, base: &Document, head: &Document, main: &Document) -> ConflictRow {
|
||||
let layer = |id: NodeId| main.node(id).or(head.node(id)).or(base.node(id)).map_or_else(|| id.to_string(), |n| n.name.clone());
|
||||
let text = |side: Side| match c.changes(side).first().and_then(|i| plan.changes(side).get(*i)) {
|
||||
@@ -627,6 +642,11 @@ fn conflict_row(plan: &Plan, c: &Conflict, base: &Document, head: &Document, mai
|
||||
let property = if *prop == Prop::Parent { "place in layers".to_string() } else { words(prop) };
|
||||
(Some(*id), layer(*id), property, b, m)
|
||||
}
|
||||
Key::Field(id, prop, field) => {
|
||||
let (b, m) = plan.field_values(&c.key).map_or_else(|| ("changed".into(), "changed".into()), |(b, m)| (field_text(b), field_text(m)));
|
||||
let owner = if *prop == Prop::Layout { "auto layout".to_string() } else { words(prop) };
|
||||
(Some(*id), layer(*id), format!("{owner} {}", field.replace('_', " ")), b, m)
|
||||
}
|
||||
Key::Layer(id) => {
|
||||
let (b, m) = if c.deleted_by == Some(Side::Branch) { ("deleted", "edited") } else { ("edited", "deleted") };
|
||||
(Some(*id), layer(*id), "layer".to_string(), b.to_string(), m.to_string())
|
||||
|
||||
@@ -748,3 +748,71 @@ fn a_link_is_underlined_by_default_and_underline_takes_it_off() {
|
||||
s.execute("text.underline", &json!({"ids": [f]})).unwrap();
|
||||
assert_eq!(inner_style(&s).decoration, TextDecoration::None, "Underline on the frame reads the text inside it");
|
||||
}
|
||||
|
||||
fn layer_name(s: &Session, t: NodeId) -> String {
|
||||
s.doc().unwrap().node(t).unwrap().name.clone()
|
||||
}
|
||||
|
||||
/// Select everything in the layer being edited and delete it.
|
||||
fn clear_edited_text(s: &mut Session, t: NodeId) {
|
||||
let len = s.doc().unwrap().node(t).unwrap().kind.text().unwrap().char_count();
|
||||
crate::textedit::set_caret(s, 0, false).unwrap();
|
||||
crate::textedit::set_caret(s, len, true).unwrap();
|
||||
crate::textedit::key(s, "Backspace", false, false, false).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typing_renames_a_text_layer_that_still_carries_the_name_its_characters_gave_it() {
|
||||
// The Layers panel shows a layer's name, so a layer still carrying the name its characters
|
||||
// gave it has to follow them while they are typed or the panel and the canvas disagree
|
||||
// (#1747). The target app's plugin API calls this `autoRename`: "Whether updating the
|
||||
// characters in the text node should update the name of the node… This is automatically reset
|
||||
// to false if `name` is modified in order to allow the node to keep the new name."
|
||||
let mut s = Session::new();
|
||||
|
||||
// Nobody renamed this layer, so typing in it keeps its name up to date.
|
||||
let t = text(&mut s, "hello", json!({}));
|
||||
assert_eq!(layer_name(&s, t), "hello", "a new layer is named after its first line");
|
||||
crate::textedit::begin(&mut s, t, Some(5), false).unwrap();
|
||||
crate::textedit::insert(&mut s, " there").unwrap();
|
||||
assert_eq!((chars(&s, t).as_str(), layer_name(&s, t).as_str()), ("hello there", "hello there"), "the name follows what is typed");
|
||||
|
||||
// A name the author typed is theirs: later typing leaves it alone.
|
||||
s.execute("node.set", &json!({"id": t, "props": {"name": "Greeting"}})).unwrap();
|
||||
crate::textedit::begin(&mut s, t, Some(11), false).unwrap();
|
||||
crate::textedit::insert(&mut s, "!").unwrap();
|
||||
assert_eq!((chars(&s, t).as_str(), layer_name(&s, t).as_str()), ("hello there!", "Greeting"), "a chosen name is kept");
|
||||
|
||||
// Only the first line names the layer.
|
||||
let v = text(&mut s, "first", json!({}));
|
||||
crate::textedit::begin(&mut s, v, Some(5), false).unwrap();
|
||||
crate::textedit::insert(&mut s, "\nsecond").unwrap();
|
||||
assert_eq!((chars(&s, v).as_str(), layer_name(&s, v).as_str()), ("first\nsecond", "first"), "the first line alone names it");
|
||||
|
||||
// Emptied text reads as a new empty text layer does, not as the word that was deleted.
|
||||
clear_edited_text(&mut s, v);
|
||||
assert_eq!((chars(&s, v).as_str(), layer_name(&s, v).as_str()), ("", ""), "emptied text has no name of its own, so the panel shows its kind");
|
||||
|
||||
// The usual way a layer is made: the Text tool, a click, then typing into the empty layer.
|
||||
use crate::tools::{PointerEvent, PointerKind, ToolId};
|
||||
s.set_tool(ToolId::Text);
|
||||
s.pointer(&PointerEvent::at(PointerKind::Down, 300.0, 300.0, 1.0)).unwrap();
|
||||
s.pointer(&PointerEvent::at(PointerKind::Up, 300.0, 300.0, 1.0)).unwrap();
|
||||
let drawn = s.ds().unwrap().text_edit.as_ref().unwrap().id;
|
||||
assert_eq!(layer_name(&s, drawn), "", "a layer the tool drew has no name of its own yet");
|
||||
crate::textedit::insert(&mut s, "Pricing").unwrap();
|
||||
assert_eq!((chars(&s, drawn).as_str(), layer_name(&s, drawn).as_str()), ("Pricing", "Pricing"), "the first word typed names it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn setting_characters_as_a_command_never_renames_the_layer() {
|
||||
// Only the editor follows the characters. Layer names are field keys for `data.fill`,
|
||||
// component property bindings and templates, which write `characters` into a layer named for
|
||||
// its role ("Title") and look it up by that name again, so a command must leave the name as it
|
||||
// is even when it reads like the text it replaces.
|
||||
let mut s = Session::new();
|
||||
let t = text(&mut s, "Title", json!({}));
|
||||
assert_eq!(layer_name(&s, t), "Title");
|
||||
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");
|
||||
}
|
||||
@@ -75,6 +75,9 @@ const MAX_CHUNK: u64 = 512 * 1024 * 1024;
|
||||
/// Largest decompressed schema chunk: Figma's schema unpacks to well under 1 MB, so a schema that
|
||||
/// inflates past this is refused before its definitions are decoded.
|
||||
const MAX_SCHEMA: u64 = 16 * 1024 * 1024;
|
||||
/// Longest image hash (bytes) an image is found by: `images/` names and embedded images both
|
||||
/// stop at 64 bytes (128 hex digits).
|
||||
pub(crate) const MAX_IMAGE_HASH: usize = 64;
|
||||
/// Largest image member read.
|
||||
const MAX_IMAGE: u64 = figcraft_doc::ImageData::MAX_BYTES;
|
||||
/// Total decompressed ZIP image bytes read per import: the native image budget (`IMAGE_BUDGET`) on
|
||||
@@ -141,10 +144,14 @@ fn import_with_image_limit(bytes: &[u8], name: &str, image_limit: u64) -> Result
|
||||
let max_nodes = layer_budget(packed);
|
||||
drop(message);
|
||||
let file_name = archive.file_name.as_deref().filter(|n| !n.trim().is_empty()).unwrap_or(name);
|
||||
let (json, mut warnings, networks) = map::to_rest(&msg, file_name, max_nodes);
|
||||
let (mut json, mut warnings, networks) = map::to_rest(&msg, file_name, max_nodes);
|
||||
// The message goes before the layers are built, so the images it carries are copied out first.
|
||||
let embedded = embedded_copies(&msg);
|
||||
drop(msg);
|
||||
let aliases = embedded_aliases(&embedded, |hash| archive.has_image(hash));
|
||||
if !aliases.is_empty() {
|
||||
canonical_image_refs(&mut json, &aliases);
|
||||
}
|
||||
let images = |r: &str| archive.image(r).or_else(|| embedded.get(r).map(|b| b.to_vec()));
|
||||
let (mut doc, more) = crate::rest::import_with_networks(&json, &images, networks, max_nodes)?;
|
||||
let skipped = archive.image_budget.skipped.get();
|
||||
@@ -227,9 +234,53 @@ fn embedded_copies(msg: &Kv) -> BTreeMap<String, Arc<[u8]>> {
|
||||
out
|
||||
}
|
||||
|
||||
/// Embedded images ([`embedded_copies`]) whose blob an earlier hash already names, each with that
|
||||
/// hash. Hashes that also have an `images/` member keep their own name: the member is read first.
|
||||
/// Pointing every alias at one name has the import copy and hash each blob once, however many
|
||||
/// hashes a file points at it.
|
||||
fn embedded_aliases(embedded: &BTreeMap<String, Arc<[u8]>>, in_zip: impl Fn(&str) -> bool) -> BTreeMap<String, String> {
|
||||
let mut first: BTreeMap<usize, &String> = BTreeMap::new();
|
||||
let mut out = BTreeMap::new();
|
||||
for (hash, bytes) in embedded {
|
||||
if in_zip(hash) {
|
||||
continue;
|
||||
}
|
||||
// Hashes naming one blob share its copy, so the copy's address tells the blob.
|
||||
let canonical = *first.entry(bytes.as_ptr() as usize).or_insert(hash);
|
||||
if canonical != hash {
|
||||
out.insert(hash.clone(), canonical.clone());
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Rename every `imageRef` in REST `json` found in `aliases` to the name it maps to.
|
||||
fn canonical_image_refs(json: &mut serde_json::Value, aliases: &BTreeMap<String, String>) {
|
||||
use serde_json::Value;
|
||||
let mut pending = vec![json];
|
||||
while let Some(value) = pending.pop() {
|
||||
match value {
|
||||
Value::Object(fields) => {
|
||||
for (key, field) in fields.iter_mut() {
|
||||
match field {
|
||||
Value::String(r) if key == "imageRef" => {
|
||||
if let Some(canonical) = aliases.get(r.as_str()) {
|
||||
r.clone_from(canonical);
|
||||
}
|
||||
}
|
||||
_ => pending.push(field),
|
||||
}
|
||||
}
|
||||
}
|
||||
Value::Array(items) => pending.extend(items.iter_mut()),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The hash and blob index of an `Image` value whose `dataBlob` points at a usable blob.
|
||||
fn embedded_image(image: &Kv, blobs: &[Kv]) -> Option<(String, usize)> {
|
||||
let hash = image.get("hash").and_then(Kv::bytes).filter(|h| !h.is_empty() && h.len() <= 64)?;
|
||||
let hash = image.get("hash").and_then(Kv::bytes).filter(|h| !h.is_empty() && h.len() <= MAX_IMAGE_HASH)?;
|
||||
let Some(Kv::Uint(index)) = image.get("dataBlob") else { return None };
|
||||
let index = usize::try_from(*index).ok()?;
|
||||
let bytes = blob(blobs, index)?;
|
||||
@@ -275,10 +326,15 @@ impl<'b> Archive<'b> {
|
||||
Ok(Archive { canvas, file_name, zip: Some(z), image_budget })
|
||||
}
|
||||
|
||||
/// Whether `images/` has a member for image `hash`.
|
||||
fn has_image(&self, hash: &str) -> bool {
|
||||
self.zip.as_ref().is_some_and(|z| z.index_for_name(&format!("images/{hash}")).is_some())
|
||||
}
|
||||
|
||||
/// Bytes of image `hash` (lowercase hex) from `images/`.
|
||||
fn image(&self, hash: &str) -> Option<Vec<u8>> {
|
||||
let budget = &self.image_budget;
|
||||
if hash.is_empty() || hash.len() > 128 || !hash.bytes().all(|b| b.is_ascii_hexdigit()) {
|
||||
if hash.is_empty() || hash.len() > 2 * MAX_IMAGE_HASH || !hash.bytes().all(|b| b.is_ascii_hexdigit()) {
|
||||
return None;
|
||||
}
|
||||
// A clone shares the parsed directory and the bytes; the resolver only has shared access.
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
//! Malformed image paint filters are skipped with a warning.
|
||||
//! Malformed image paint filters are skipped with a warning, and image hashes too long to name
|
||||
//! an image aren't spelled out.
|
||||
|
||||
use super::*;
|
||||
|
||||
@@ -25,3 +26,12 @@ fn boolean_filter_values_are_malformed_even_when_false() {
|
||||
assert!(warnings.iter().any(|warning| warning.contains(expected_warning)), "{warnings:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_oversized_image_hash_is_not_spelled_out() {
|
||||
let paint = |len: usize| Kv::Object(vec![("type", Kv::Enum("IMAGE")), ("image", Kv::Object(vec![("hash", Kv::Bytes(vec![0xab; len]))]))]);
|
||||
let image_ref = |len: usize| super::paint(&paint(len), &mut |_| {}).and_then(|p| p.get("imageRef").cloned());
|
||||
assert_eq!(image_ref(20), Some(Value::String("ab".repeat(20))));
|
||||
assert_eq!(image_ref(crate::fig::MAX_IMAGE_HASH), Some(Value::String("ab".repeat(crate::fig::MAX_IMAGE_HASH))));
|
||||
assert_eq!(image_ref(crate::fig::MAX_IMAGE_HASH + 1), Some(Value::String(String::new())));
|
||||
}
|
||||
@@ -162,8 +162,17 @@ pub(crate) fn paint(p: &Kv, warn: &mut dyn FnMut(String)) -> Option<Value> {
|
||||
o.insert("gradientStops".into(), Value::Array(stops));
|
||||
}
|
||||
"IMAGE" => {
|
||||
let hash: String =
|
||||
p.get("image").and_then(|i| i.get("hash")).and_then(Kv::bytes).unwrap_or_default().iter().map(|b| format!("{b:02x}")).collect();
|
||||
// A hash longer than any the file's images can be named by resolves to nothing: it
|
||||
// isn't spelled out, which a shared style would repeat for every layer using it.
|
||||
let hash: String = p
|
||||
.get("image")
|
||||
.and_then(|i| i.get("hash"))
|
||||
.and_then(Kv::bytes)
|
||||
.filter(|h| h.len() <= crate::fig::MAX_IMAGE_HASH)
|
||||
.unwrap_or_default()
|
||||
.iter()
|
||||
.map(|b| format!("{b:02x}"))
|
||||
.collect();
|
||||
o.insert("imageRef".into(), json!(hash));
|
||||
let mode = p.get("imageScaleMode").and_then(Kv::str).unwrap_or("FILL");
|
||||
o.insert("scaleMode".into(), json!(mode));
|
||||
|
||||
@@ -619,7 +619,7 @@ fn other_layer_kinds_import_as_the_closest_layers() {
|
||||
let world = doc.world_transform(link.id);
|
||||
let ends: Vec<(f64, f64)> =
|
||||
network_of(&doc, "Link").vertices.iter().map(|v| world * figcraft_doc::geom::Point::new(v.x, v.y)).map(|p| (p.x, p.y)).collect();
|
||||
assert_eq!(ends, [(0.0, 300.0), (200.0, 300.0), (200.0, 50.0), (400.0, 50.0)]);
|
||||
assert_eq!(ends, [(0.0, 300.0), (198.0, 300.0), (198.0, 50.0), (396.0, 50.0)]);
|
||||
assert_eq!(link.stroke.cap_end, StrokeCap::TriangleArrow);
|
||||
// A table: a frame.
|
||||
assert!(matches!(named(&doc, "Grid").kind, NodeKind::Frame));
|
||||
@@ -656,9 +656,9 @@ fn connectors_without_a_saved_path_follow_their_line_style() {
|
||||
// Curved: one curve from A's right side to B's left, leaving and arriving level.
|
||||
let curve = network_of(&doc, "Curve");
|
||||
let ends: Vec<_> = curve.vertices.iter().map(|v| world("Curve") * figcraft_doc::geom::Point::new(v.x, v.y)).collect();
|
||||
assert_eq!(ends.iter().map(|p| (p.x, p.y)).collect::<Vec<_>>(), [(100.0, 650.0), (300.0, 650.0)]);
|
||||
assert_eq!(ends.iter().map(|p| (p.x, p.y)).collect::<Vec<_>>(), [(104.0, 650.0), (296.0, 650.0)], "END_GAP outside the sides");
|
||||
assert_eq!(curve.segments.len(), 1);
|
||||
assert_eq!((curve.segments[0].ta, curve.segments[0].tb), ((100.0, 0.0), (-100.0, 0.0)), "the curve leaves and arrives along the sides");
|
||||
assert_eq!((curve.segments[0].ta, curve.segments[0].tb), ((96.0, 0.0), (-96.0, 0.0)), "the curve leaves and arrives along the sides");
|
||||
// Straight: unchanged, to the points the file gives on the layers.
|
||||
let line: Vec<_> =
|
||||
network_of(&doc, "Line").vertices.iter().map(|v| world("Line") * figcraft_doc::geom::Point::new(v.x, v.y)).map(|p| (p.x, p.y)).collect();
|
||||
|
||||
@@ -795,6 +795,44 @@ fn hashes_naming_one_blob_share_one_copy_of_it() {
|
||||
assert_eq!(*copies[&"63".repeat(20)], [7; 16]);
|
||||
}
|
||||
|
||||
/// Hashes naming one blob are imported as one image: every alias is renamed to the first hash
|
||||
/// before layers are built, so the blob is copied and hashed once, not once per hash.
|
||||
#[test]
|
||||
fn hashes_naming_one_blob_are_imported_once() {
|
||||
let rect = |i: u64, hash: u8, blob: u64| {
|
||||
let paint = o(vec![("type", e("IMAGE")), ("image", o(vec![("hash", Kv::Bytes(vec![hash; 20])), ("dataBlob", u(blob))]))]);
|
||||
node(i, Some((1, &format!("{i:04}"))), "RECTANGLE", &format!("R{i}"), vec![("size", xy(10.0, 10.0)), ("fillPaints", arr(vec![paint]))])
|
||||
};
|
||||
let mut nodes = vec![node(0, None, "DOCUMENT", "D", vec![]), node(1, Some((0, "!")), "CANVAS", "P", vec![])];
|
||||
nodes.extend((2..42).map(|i| rect(i, i as u8, 0)));
|
||||
let msg = o(vec![("nodeChanges", arr(nodes)), ("blobs", arr(vec![o(vec![("bytes", Kv::Bytes(png()))])]))]);
|
||||
let copies = embedded_copies(&msg);
|
||||
let aliases = embedded_aliases(&copies, |_| false);
|
||||
assert_eq!(aliases.len(), 39);
|
||||
assert!(aliases.values().all(|c| *c == "02".repeat(20)));
|
||||
// A hash `images/` also holds keeps its own name.
|
||||
assert!(!embedded_aliases(&copies, |h| h == "05".repeat(20)).contains_key(&"05".repeat(20)));
|
||||
let (doc, warnings) = import(&canvas(&schema(), &msg), "x").unwrap();
|
||||
assert!(!warnings.iter().any(|w| w.contains("isn't in the file")), "{warnings:?}");
|
||||
assert_eq!(doc.images.len(), 1);
|
||||
let key = doc.images.keys().next().unwrap();
|
||||
for i in 2..42 {
|
||||
let figcraft_doc::color::PaintKind::Image(img) = &named(&doc, &format!("R{i}")).fills[0].kind else { panic!("not an image fill") };
|
||||
assert_eq!(&img.image, key);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn image_refs_are_renamed_wherever_they_sit() {
|
||||
let aliases: BTreeMap<String, String> = [("b".to_string(), "a".to_string())].into();
|
||||
let mut json = serde_json::json!({"fills": [{"imageRef": "b"}, {"imageRef": "c"}], "styles": {"s": {"fills": [{"imageRef": "b"}]}}, "name": "b"});
|
||||
canonical_image_refs(&mut json, &aliases);
|
||||
assert_eq!(
|
||||
json,
|
||||
serde_json::json!({"fills": [{"imageRef": "a"}, {"imageRef": "c"}], "styles": {"s": {"fills": [{"imageRef": "a"}]}}, "name": "b"})
|
||||
);
|
||||
}
|
||||
|
||||
mod image_budget {
|
||||
use super::*;
|
||||
|
||||
|
||||
+65
-21
@@ -3,22 +3,25 @@
|
||||
//! `CRAFT_FONTS` is empty and native apps use system fonts. Required web releases enforce Inter
|
||||
//! Regular/SemiBold and Noto Sans Georgian Regular after filtering. Recipe: craft-fonts `docs/integration.md`.
|
||||
//! Noto Sans CJK only with `FIGCRAFT_EMBED_CJK` set (the web build's only way to show CJK UI text).
|
||||
//! `FIGCRAFT_WEB_FONTS` (comma-separated families) adds manifest families to the web build.
|
||||
use std::fmt::Write as _;
|
||||
use std::path::PathBuf;
|
||||
|
||||
/// Font build script: emit `craft_fonts.rs` from `input_fonts`, passing the
|
||||
/// `CRAFT_FONTS_DIR`, `CRAFT_FONTS_REQUIRED`, wasm target and `FIGCRAFT_EMBED_CJK` inputs;
|
||||
/// `CRAFT_FONTS_DIR`, `CRAFT_FONTS_REQUIRED`, wasm target, `FIGCRAFT_EMBED_CJK` and `FIGCRAFT_WEB_FONTS` inputs;
|
||||
/// report generation and write failures with `cargo::error`.
|
||||
fn main() {
|
||||
println!("cargo::rerun-if-env-changed=CRAFT_FONTS_DIR");
|
||||
println!("cargo::rerun-if-env-changed=CRAFT_FONTS_REQUIRED");
|
||||
println!("cargo::rerun-if-env-changed=FIGCRAFT_EMBED_CJK");
|
||||
println!("cargo::rerun-if-env-changed=FIGCRAFT_WEB_FONTS");
|
||||
let mut src = String::from("pub static CRAFT_FONTS: &[CraftFont] = &[\n");
|
||||
let dir = std::env::var_os("CRAFT_FONTS_DIR").map(PathBuf::from);
|
||||
let required = std::env::var_os("CRAFT_FONTS_REQUIRED").is_some();
|
||||
let wasm = std::env::var("CARGO_CFG_TARGET_ARCH").is_ok_and(|a| a == "wasm32");
|
||||
let embed_cjk = std::env::var_os("FIGCRAFT_EMBED_CJK").is_some();
|
||||
match input_fonts(dir.as_deref(), wasm, required, embed_cjk) {
|
||||
let web_fonts = web_fonts(&std::env::var("FIGCRAFT_WEB_FONTS").unwrap_or_default());
|
||||
match input_fonts(dir.as_deref(), wasm, required, embed_cjk, &web_fonts) {
|
||||
Ok(entries) => src.push_str(&entries),
|
||||
Err(e) => println!("cargo::error={e}"),
|
||||
}
|
||||
@@ -29,21 +32,37 @@ fn main() {
|
||||
}
|
||||
}
|
||||
|
||||
/// The families `FIGCRAFT_WEB_FONTS` names: comma-separated, trimmed, empty names dropped.
|
||||
fn web_fonts(list: &str) -> Vec<String> {
|
||||
list.split(',').map(str::trim).filter(|f| !f.is_empty()).map(str::to_owned).collect()
|
||||
}
|
||||
|
||||
/// The families in `web_fonts` that `faces` has no face of, in the order named.
|
||||
fn not_embedded<'a>(web_fonts: &'a [String], faces: &[(String, String)]) -> Vec<&'a str> {
|
||||
web_fonts.iter().map(String::as_str).filter(|w| !faces.iter().any(|(family, _)| family == w)).collect()
|
||||
}
|
||||
|
||||
/// Collect the effective catalog and enforce the required web release faces after filtering.
|
||||
fn input_fonts(dir: Option<&std::path::Path>, wasm: bool, required: bool, embed_cjk: bool) -> Result<String, String> {
|
||||
/// Families named in `web_fonts` that nothing embedded get a warning (most likely misspelt).
|
||||
fn input_fonts(dir: Option<&std::path::Path>, wasm: bool, required: bool, embed_cjk: bool, web_fonts: &[String]) -> Result<String, String> {
|
||||
let Some(dir) = dir else {
|
||||
for family in web_fonts {
|
||||
println!("cargo::warning=FIGCRAFT_WEB_FONTS: {family:?} isn't embedded: this build has no craft-fonts");
|
||||
}
|
||||
return if required { Err("CRAFT_FONTS_REQUIRED is set but CRAFT_FONTS_DIR is missing".into()) } else { Ok(String::new()) };
|
||||
};
|
||||
let mut out = String::new();
|
||||
let mut faces = Vec::new();
|
||||
let mut loaded = false;
|
||||
for manifest in ["fonts/latin-manifest.txt", "fonts/manifest.txt"] {
|
||||
let path = dir.join(manifest);
|
||||
if manifest == "fonts/latin-manifest.txt" && !path.exists() {
|
||||
watch(&path);
|
||||
continue;
|
||||
}
|
||||
match craft_fonts(dir, manifest, wasm, embed_cjk) {
|
||||
match craft_fonts(dir, manifest, wasm, embed_cjk, web_fonts) {
|
||||
Ok(catalog) => {
|
||||
loaded = true;
|
||||
out.push_str(&catalog.entries);
|
||||
faces.extend(catalog.faces);
|
||||
}
|
||||
@@ -51,6 +70,11 @@ fn input_fonts(dir: Option<&std::path::Path>, wasm: bool, required: bool, embed_
|
||||
Err(e) => println!("cargo::warning=craft-fonts {manifest} skipped: CRAFT_FONTS_DIR={}: {e}", dir.display()),
|
||||
}
|
||||
}
|
||||
let why =
|
||||
if loaded { "no manifest row was kept for it (misspelt? CJK also needs FIGCRAFT_EMBED_CJK)" } else { "no craft-fonts manifest was read" };
|
||||
for family in not_embedded(web_fonts, &faces) {
|
||||
println!("cargo::warning=FIGCRAFT_WEB_FONTS: {family:?} isn't embedded: {why}");
|
||||
}
|
||||
if required && wasm {
|
||||
for (family, style) in [("Inter", "Regular"), ("Inter", "SemiBold"), ("Noto Sans Georgian", "Regular")] {
|
||||
if !faces.iter().any(|(f, s)| f == family && s == style) {
|
||||
@@ -82,9 +106,9 @@ struct Catalog {
|
||||
|
||||
/// Parse a font manifest of `family | style | file | scripts` rows into `CraftFont`
|
||||
/// entries: skip Adobe-authored families, skip CJK unless requested, keep the web catalog
|
||||
/// to its budgeted families, canonicalize and watch each face, and emit `include_bytes!`
|
||||
/// items.
|
||||
fn craft_fonts(dir: &std::path::Path, manifest_rel: &str, wasm: bool, embed_cjk: bool) -> Result<Catalog, String> {
|
||||
/// to its budgeted families and the ones `web_fonts` adds, canonicalize and watch each face, and
|
||||
/// emit `include_bytes!` items.
|
||||
fn craft_fonts(dir: &std::path::Path, manifest_rel: &str, wasm: bool, embed_cjk: bool, web_fonts: &[String]) -> Result<Catalog, String> {
|
||||
let manifest = dir.join(manifest_rel);
|
||||
watch(&manifest);
|
||||
let text = std::fs::read_to_string(&manifest).map_err(|e| format!("{}: {e}", manifest.display()))?;
|
||||
@@ -105,9 +129,11 @@ fn craft_fonts(dir: &std::path::Path, manifest_rel: &str, wasm: bool, embed_cjk:
|
||||
continue;
|
||||
}
|
||||
// Web builds have a size budget: Inter, Noto Sans Georgian (small, for the Georgian UI), only the
|
||||
// SemiBold wordmark, and optionally Noto Sans CJK (every CJK script, for CJK UI text).
|
||||
// SemiBold wordmark, optionally Noto Sans CJK (every CJK script, for CJK UI text), and the
|
||||
// families a distribution names in `FIGCRAFT_WEB_FONTS` (a Thai face for Thai text, say).
|
||||
let wordmark = *family == "Archivo" && *style == "SemiBold";
|
||||
if wasm && !matches!(*family, "Inter" | "Noto Sans Georgian") && !wordmark && !cjk {
|
||||
let added = web_fonts.iter().any(|f| f == family);
|
||||
if wasm && !matches!(*family, "Inter" | "Noto Sans Georgian") && !wordmark && !cjk && !added {
|
||||
continue;
|
||||
}
|
||||
let path = dir.join(file).canonicalize().map_err(|e| format!("{file}: {e}"))?;
|
||||
@@ -161,9 +187,9 @@ mod tests {
|
||||
fn restored_latin_catalog_preserves_permitted_native_faces_and_web_budget() {
|
||||
let f = Fixture::new();
|
||||
std::fs::write(f.0.join("fonts/latin-manifest.txt"), include_str!("tests/fixtures/latin-families.txt")).unwrap();
|
||||
let native = craft_fonts(&f.0, "fonts/latin-manifest.txt", false, false).unwrap();
|
||||
let native = craft_fonts(&f.0, "fonts/latin-manifest.txt", false, false, &[]).unwrap();
|
||||
assert_eq!(native.faces.len(), 43, "all prior permitted presentation faces remain available");
|
||||
let web = craft_fonts(&f.0, "fonts/latin-manifest.txt", true, false).unwrap();
|
||||
let web = craft_fonts(&f.0, "fonts/latin-manifest.txt", true, false, &[]).unwrap();
|
||||
assert_eq!(web.faces.len(), 4, "the web catalog keeps only the four Inter faces");
|
||||
for catalog in [&native, &web] {
|
||||
assert!(!catalog.entries.contains("Source Sans 3"));
|
||||
@@ -171,16 +197,16 @@ mod tests {
|
||||
}
|
||||
assert!(native.faces.iter().any(|(family, _)| family == "Carlito"));
|
||||
assert!(native.faces.iter().any(|(family, _)| family == "Liberation Serif"));
|
||||
assert!(input_fonts(Some(&f.0), true, true, false).is_ok());
|
||||
assert!(input_fonts(Some(&f.0), true, true, false, &[]).is_ok());
|
||||
}
|
||||
|
||||
/// Asserts required web input rejects a catalog missing Inter Regular or Inter SemiBold.
|
||||
#[test]
|
||||
fn required_web_rejects_core_only_and_partial_latin_catalogs() {
|
||||
let f = Fixture::new();
|
||||
assert!(input_fonts(Some(&f.0), true, true, false).unwrap_err().contains("Inter Regular"));
|
||||
assert!(input_fonts(Some(&f.0), true, true, false, &[]).unwrap_err().contains("Inter Regular"));
|
||||
f.manifest("latin-manifest.txt", &[("Inter", "Regular"), ("Unrelated", "SemiBold")]);
|
||||
assert!(input_fonts(Some(&f.0), true, true, false).unwrap_err().contains("Inter SemiBold"));
|
||||
assert!(input_fonts(Some(&f.0), true, true, false, &[]).unwrap_err().contains("Inter SemiBold"));
|
||||
}
|
||||
|
||||
/// Asserts required web input embeds the Inter and Georgian catalogs (three entries) and
|
||||
@@ -189,12 +215,12 @@ mod tests {
|
||||
fn required_web_embeds_both_catalogs_and_requires_georgian() {
|
||||
let f = Fixture::new();
|
||||
f.manifest("latin-manifest.txt", &[("Inter", "Regular"), ("Inter", "SemiBold")]);
|
||||
let entries = input_fonts(Some(&f.0), true, true, false).unwrap();
|
||||
let entries = input_fonts(Some(&f.0), true, true, false, &[]).unwrap();
|
||||
assert_eq!(entries.matches("CraftFont {").count(), 3);
|
||||
assert!(entries.contains("family: \"Inter\""));
|
||||
assert!(entries.contains("family: \"Noto Sans Georgian\""));
|
||||
f.manifest("manifest.txt", &[("Other", "Regular")]);
|
||||
assert!(input_fonts(Some(&f.0), true, true, false).unwrap_err().contains("Noto Sans Georgian Regular"));
|
||||
assert!(input_fonts(Some(&f.0), true, true, false, &[]).unwrap_err().contains("Noto Sans Georgian Regular"));
|
||||
}
|
||||
|
||||
/// Asserts absent font input is empty when optional and an error when required, while present
|
||||
@@ -202,10 +228,10 @@ mod tests {
|
||||
#[test]
|
||||
fn optional_and_native_inputs_keep_their_existing_policy() {
|
||||
let f = Fixture::new();
|
||||
assert!(input_fonts(None, true, false, false).unwrap().is_empty());
|
||||
assert!(input_fonts(None, true, true, false).unwrap_err().contains("CRAFT_FONTS_DIR is missing"));
|
||||
assert!(input_fonts(Some(&f.0), true, false, false).unwrap().contains("Noto Sans Georgian"));
|
||||
assert!(input_fonts(Some(&f.0), false, true, false).unwrap().contains("Noto Sans Georgian"));
|
||||
assert!(input_fonts(None, true, false, false, &[]).unwrap().is_empty());
|
||||
assert!(input_fonts(None, true, true, false, &[]).unwrap_err().contains("CRAFT_FONTS_DIR is missing"));
|
||||
assert!(input_fonts(Some(&f.0), true, false, false, &[]).unwrap().contains("Noto Sans Georgian"));
|
||||
assert!(input_fonts(Some(&f.0), false, true, false, &[]).unwrap().contains("Noto Sans Georgian"));
|
||||
}
|
||||
|
||||
/// Asserts required web input rejects a manifest whose face file is missing, even when every
|
||||
@@ -215,6 +241,24 @@ mod tests {
|
||||
let f = Fixture::new();
|
||||
f.manifest("latin-manifest.txt", &[("Inter", "Regular"), ("Inter", "SemiBold")]);
|
||||
std::fs::remove_file(f.0.join("fonts/face.ttf")).unwrap();
|
||||
assert!(input_fonts(Some(&f.0), true, true, false).unwrap_err().contains("fonts/face.ttf"));
|
||||
assert!(input_fonts(Some(&f.0), true, true, false, &[]).unwrap_err().contains("fonts/face.ttf"));
|
||||
}
|
||||
|
||||
/// Asserts `FIGCRAFT_WEB_FONTS` (split on commas, trimmed) adds the families it names to the web
|
||||
/// catalog only, leaves native and unset builds as they were, and reports a family nothing
|
||||
/// embedded.
|
||||
#[test]
|
||||
fn web_fonts_add_the_families_they_name_to_the_web_catalog() {
|
||||
let f = Fixture::new();
|
||||
f.manifest("manifest.txt", &[("Noto Sans Georgian", "Regular"), ("Noto Sans Thai", "Regular"), ("Noto Sans Hebrew", "Regular")]);
|
||||
let named = web_fonts(" Noto Sans Thai, ,Noto Sans Thia ");
|
||||
assert_eq!(named, ["Noto Sans Thai", "Noto Sans Thia"]);
|
||||
let families = |c: &Catalog| c.faces.iter().map(|(family, _)| family.clone()).collect::<Vec<_>>();
|
||||
let web = craft_fonts(&f.0, "fonts/manifest.txt", true, false, &named).unwrap();
|
||||
assert_eq!(families(&web), ["Noto Sans Georgian", "Noto Sans Thai"], "the named family joins; the others stay out");
|
||||
assert_eq!(families(&craft_fonts(&f.0, "fonts/manifest.txt", true, false, &[]).unwrap()), ["Noto Sans Georgian"], "unset: as before");
|
||||
assert_eq!(craft_fonts(&f.0, "fonts/manifest.txt", false, false, &[]).unwrap().faces.len(), 3, "native builds embed every family");
|
||||
assert_eq!(not_embedded(&named, &web.faces), ["Noto Sans Thia"], "a misspelt family is reported");
|
||||
assert!(input_fonts(Some(&f.0), true, false, false, &named).unwrap().contains("family: \"Noto Sans Thai\""));
|
||||
}
|
||||
}
|
||||
@@ -290,7 +290,7 @@ fn a_selected_connector_shows_its_ends_as_handles() {
|
||||
let b = u.app.session.execute("board.sticky", &json!({"x": 400, "y": 0})).unwrap()["id"].clone();
|
||||
u.app.session.execute("board.connector", &json!({"from": a, "to": b, "style": "straight"})).unwrap();
|
||||
let shapes = flat(&u.frame_output(vec![]).shapes);
|
||||
let ends = [u.app.to_screen(200.0, 100.0), u.app.to_screen(400.0, 100.0)];
|
||||
let ends = [u.app.to_screen(204.0, 100.0), u.app.to_screen(396.0, 100.0)];
|
||||
for end in ends {
|
||||
let ring = shapes.iter().any(|s| matches!(s, egui::Shape::Circle(c) if (c.center - end).length() < 0.5 && c.radius == 5.0));
|
||||
assert!(ring, "a handle at {end:?}");
|
||||
|
||||
@@ -187,13 +187,18 @@ fn setup() -> (Ui, NodeId, NodeId) {
|
||||
(u, a, b)
|
||||
}
|
||||
|
||||
/// The field named `name` in the Design panel: the middle of its value, and what it shows.
|
||||
/// The topmost field named `name` in the Design panel: its value centre and displayed text.
|
||||
/// Layer opacity precedes the equally named opacity fields in paint rows.
|
||||
fn field(u: &mut Ui, name: &str) -> (Pos2, String) {
|
||||
u.frame(vec![]);
|
||||
let out = u.frame_output(vec![]);
|
||||
let nodes = out.platform_output.accesskit_update.expect("an AccessKit update").nodes;
|
||||
let n =
|
||||
nodes.iter().map(|(_, n)| n).find(|n| n.role() == Role::SpinButton && n.label() == Some(name)).unwrap_or_else(|| panic!("no field {name:?}"));
|
||||
let n = nodes
|
||||
.iter()
|
||||
.map(|(_, n)| n)
|
||||
.filter(|n| n.role() == Role::SpinButton && n.label() == Some(name))
|
||||
.min_by(|a, b| a.bounds().map_or(f64::INFINITY, |r| r.y0).total_cmp(&b.bounds().map_or(f64::INFINITY, |r| r.y0)))
|
||||
.unwrap_or_else(|| panic!("no field {name:?}"));
|
||||
let b = n.bounds().expect("bounds");
|
||||
(pos2(((b.x0 + b.x1) / 2.0) as f32, ((b.y0 + b.y1) / 2.0) as f32), n.value().unwrap_or_default().to_string())
|
||||
}
|
||||
@@ -203,11 +208,26 @@ fn label(u: &mut Ui, name: &str) -> Pos2 {
|
||||
u.frame(vec![]);
|
||||
let out = u.frame_output(vec![]);
|
||||
let nodes = out.platform_output.accesskit_update.expect("an AccessKit update").nodes;
|
||||
let n = nodes.iter().map(|(_, n)| n).find(|n| n.role() == Role::SpinButton && n.label() == Some(name)).unwrap();
|
||||
let n = nodes
|
||||
.iter()
|
||||
.map(|(_, n)| n)
|
||||
.filter(|n| n.role() == Role::SpinButton && n.label() == Some(name))
|
||||
.min_by(|a, b| a.bounds().map_or(f64::INFINITY, |r| r.y0).total_cmp(&b.bounds().map_or(f64::INFINITY, |r| r.y0)))
|
||||
.unwrap();
|
||||
let b = n.bounds().unwrap();
|
||||
pos2(b.x0 as f32 - 12.0, ((b.y0 + b.y1) / 2.0) as f32)
|
||||
}
|
||||
|
||||
/// Layer and fill opacity are both named for assistive technology, even without a visible lead.
|
||||
#[test]
|
||||
fn paint_opacity_has_an_accessible_name() {
|
||||
let (mut u, _, _) = setup();
|
||||
let output = u.frame_output(vec![]);
|
||||
let nodes = output.platform_output.accesskit_update.unwrap().nodes;
|
||||
let opacity_fields = nodes.iter().filter(|(_, n)| n.role() == Role::SpinButton && n.label() == Some("Opacity")).count();
|
||||
assert_eq!(opacity_fields, 2, "both layer and fill opacity must have an accessible name");
|
||||
}
|
||||
|
||||
fn geom(u: &Ui, n: NodeId) -> (f64, f64, f64, f64) {
|
||||
let doc = u.app.session.doc().unwrap();
|
||||
let b = doc.world_bounds(n).unwrap();
|
||||
|
||||
@@ -29,6 +29,8 @@ pub use draw::{paint, paint_outlines};
|
||||
|
||||
icons! {
|
||||
Move,
|
||||
/// Select layers using a colour: selection corners around a colour swatch.
|
||||
SelectColor,
|
||||
Scale,
|
||||
FitContents,
|
||||
Hand,
|
||||
|
||||
@@ -285,6 +285,13 @@ fn draw(p: &P, icon: Icon) {
|
||||
use Icon::*;
|
||||
match icon {
|
||||
Move => p.fill(&[(4.0, 2.0), (4.0, 13.6), (6.9, 10.9), (8.8, 14.8), (10.6, 14.0), (8.7, 10.2), (12.6, 10.2)]),
|
||||
SelectColor => {
|
||||
p.poly(&[(2.5, 5.5), (2.5, 2.5), (5.5, 2.5)], false);
|
||||
p.poly(&[(10.5, 2.5), (13.5, 2.5), (13.5, 5.5)], false);
|
||||
p.poly(&[(2.5, 10.5), (2.5, 13.5), (5.5, 13.5)], false);
|
||||
p.poly(&[(10.5, 13.5), (13.5, 13.5), (13.5, 10.5)], false);
|
||||
p.circle(8.0, 8.0, 2.5);
|
||||
}
|
||||
Scale => {
|
||||
p.rect(2.5, 7.5, 8.5, 13.5, 0.0);
|
||||
p.line(6.0, 10.0, 13.0, 3.0);
|
||||
@@ -391,11 +398,20 @@ fn draw(p: &P, icon: Icon) {
|
||||
ChevronUp => p.poly(&[(4.5, 10.0), (8.0, 6.5), (11.5, 10.0)], false),
|
||||
ChevronRight => p.poly(&[(6.0, 4.5), (9.5, 8.0), (6.0, 11.5)], false),
|
||||
ChevronLeft => p.poly(&[(10.0, 4.5), (6.5, 8.0), (10.0, 11.5)], false),
|
||||
Plus => {
|
||||
p.line(7.5, 2.0, 7.5, 13.0);
|
||||
p.line(2.0, 7.5, 13.0, 7.5);
|
||||
Plus | Minus => {
|
||||
// Snap the shared centre once, then give every arm the same pixel length.
|
||||
// Snapping each line's ends separately can offset its midpoint at small sizes.
|
||||
let c = p.sp(8.0, 8.0);
|
||||
let half = p.stroke.width / 2.0;
|
||||
let reach = (5.0 * p.s / p.px).round() * p.px + half;
|
||||
let mut mesh = Mesh::default();
|
||||
mesh.add_colored_rect(Rect::from_min_max(c - vec2(reach, half), c + vec2(reach, half)), p.color);
|
||||
if icon == Plus {
|
||||
mesh.add_colored_rect(Rect::from_min_max(c - vec2(half, reach), c + vec2(half, -half)), p.color);
|
||||
mesh.add_colored_rect(Rect::from_min_max(c + vec2(-half, half), c + vec2(half, reach)), p.color);
|
||||
}
|
||||
p.painter.add(Shape::mesh(mesh));
|
||||
}
|
||||
Minus => p.line(2.0, 7.5, 13.0, 7.5),
|
||||
Eye | EyeOff => {
|
||||
// An almond (two arcs meeting at the corners) with the pupil.
|
||||
let (r, cy, half) = (7.0f32, 7.5f32, 5.5f32);
|
||||
|
||||
@@ -89,12 +89,18 @@ impl FigApp {
|
||||
|
||||
/// Apply a field edit through any command: `params` builds the command's params from the value.
|
||||
pub fn field_run(&mut self, edit: Option<FieldEdit>, cmd: &str, params: impl Fn(f64) -> Value) {
|
||||
self.field_run_named(edit, "Edit", cmd, params);
|
||||
}
|
||||
|
||||
/// Apply a field edit with a specific undo label for scrubs; commit only on release.
|
||||
/// Typed edits use `run`; scrub errors are discarded as in `field_run`.
|
||||
pub(crate) fn field_run_named(&mut self, edit: Option<FieldEdit>, label: &str, cmd: &str, params: impl Fn(f64) -> Value) {
|
||||
match edit {
|
||||
Some(FieldEdit::Set(v)) => {
|
||||
self.run(cmd, params(v));
|
||||
}
|
||||
Some(FieldEdit::Scrub(v, done)) => {
|
||||
let _ = self.session.begin_interaction("Edit");
|
||||
let _ = self.session.begin_interaction(label);
|
||||
let _ = self.session.execute(cmd, ¶ms(v));
|
||||
if done {
|
||||
let _ = self.session.commit_interaction();
|
||||
|
||||
@@ -446,78 +446,62 @@ fn paint_row(app: &mut FigApp, ui: &mut Ui, ids: &[NodeId], i: usize, p: &Paint,
|
||||
let cmd = if fills { "fill.set" } else { "stroke.set" };
|
||||
let r = row_rect(ui, 32.0, |ui| {
|
||||
let w = ui.available_width() - 60.0;
|
||||
let (r, _) = ui.allocate_exact_size(vec2(w, FIELD_H), Sense::hover());
|
||||
ui.painter().rect_filled(r, CornerRadius::same(5), t.field);
|
||||
let sw = Rect::from_min_size(pos2(r.min.x + 4.0, r.center().y - 8.0), vec2(16.0, 16.0));
|
||||
widgets::paint_swatch(ui.painter(), sw, p);
|
||||
let sresp = ui.interact(sw.expand(2.0), Id::unique(("swatch", fills, i)), Sense::click());
|
||||
app.picker_control(crate::colorpicker::PickerTarget::Paint { fills, index: i, ids: ids.clone() }, &sresp);
|
||||
let text_r = Rect::from_min_max(pos2(sw.max.x + 8.0, r.min.y), pos2(r.max.x - 52.0, r.max.y));
|
||||
let mut child = ui.new_child(egui::UiBuilder::new().max_rect(text_r));
|
||||
// The variable bound to this paint's colour (its key on the layers: `fill` or `fills/<i>/color`).
|
||||
let bound = app.session.doc().ok().and_then(|d| {
|
||||
let key = ids.first().and_then(|id| d.node(*id)).and_then(|n| figcraft_engine::cmd::lists::paint_binding_key(n, fills, i))?;
|
||||
Some((key.to_string(), crate::variable_ui::bound_name(d, &ids, key)?))
|
||||
});
|
||||
match &p.kind {
|
||||
PaintKind::Solid { .. } if bound.is_some() => {
|
||||
let (key, name) = bound.clone().unwrap_or_default();
|
||||
let chip = Rect::from_min_max(pos2(text_r.min.x - 2.0, r.min.y + 3.0), pos2(text_r.max.x - 20.0, r.max.y - 3.0));
|
||||
child.painter().rect_filled(chip, CornerRadius::same(4), t.hover);
|
||||
child.painter().rect_stroke(chip, CornerRadius::same(4), Stroke::new(1.0, t.border), egui::StrokeKind::Inside);
|
||||
let short = name.rsplit('/').next().unwrap_or(&name).to_string();
|
||||
child.painter().with_clip_rect(chip.shrink2(vec2(5.0, 0.0))).text(
|
||||
pos2(chip.min.x + 5.0, r.center().y),
|
||||
Align2::LEFT_CENTER,
|
||||
short,
|
||||
regular(11.0),
|
||||
t.text,
|
||||
);
|
||||
let _ = ui.interact(chip, Id::unique(("bound_paint", fills, i)), Sense::hover()).on_hover_text(&name);
|
||||
let dr = Rect::from_center_size(pos2(text_r.max.x - 9.0, r.center().y), vec2(18.0, 18.0));
|
||||
let dresp = ui.interact(dr, Id::unique(("detach_paint", fills, i)), Sense::click()).tip(tr("Detach variable"));
|
||||
icons::paint(ui.painter(), dr.shrink(3.0), Icon::Detach, t.icon_secondary);
|
||||
if dresp.clicked() {
|
||||
app.run("variable.bind", json!({"ids": ids, "field": key, "variable": null}));
|
||||
let (sresp, e) = widgets::paint_field(ui, Id::unique(("swatch", fills, i)), Id::unique(("pop", fills, i)), p, w, |child, text_r| {
|
||||
let r = child.max_rect();
|
||||
// The variable bound to this paint's colour (its key on the layers: `fill` or `fills/<i>/color`).
|
||||
let bound = app.session.doc().ok().and_then(|d| {
|
||||
let key = ids.first().and_then(|id| d.node(*id)).and_then(|n| figcraft_engine::cmd::lists::paint_binding_key(n, fills, i))?;
|
||||
Some((key.to_string(), crate::variable_ui::bound_name(d, &ids, key)?))
|
||||
});
|
||||
match &p.kind {
|
||||
PaintKind::Solid { .. } if bound.is_some() => {
|
||||
let (key, name) = bound.clone().unwrap_or_default();
|
||||
let chip = Rect::from_min_max(pos2(text_r.min.x - 2.0, r.min.y + 3.0), pos2(text_r.max.x - 20.0, r.max.y - 3.0));
|
||||
child.painter().rect_filled(chip, CornerRadius::same(4), t.hover);
|
||||
child.painter().rect_stroke(chip, CornerRadius::same(4), Stroke::new(1.0, t.border), egui::StrokeKind::Inside);
|
||||
let short = name.rsplit('/').next().unwrap_or(&name).to_string();
|
||||
child.painter().with_clip_rect(chip.shrink2(vec2(5.0, 0.0))).text(
|
||||
pos2(chip.min.x + 5.0, r.center().y),
|
||||
Align2::LEFT_CENTER,
|
||||
short,
|
||||
regular(11.0),
|
||||
t.text,
|
||||
);
|
||||
let _ = child.interact(chip, Id::unique(("bound_paint", fills, i)), Sense::hover()).on_hover_text(&name);
|
||||
let dr = Rect::from_center_size(pos2(text_r.max.x - 9.0, r.center().y), vec2(18.0, 18.0));
|
||||
let dresp = child.interact(dr, Id::unique(("detach_paint", fills, i)), Sense::click()).tip(tr("Detach variable"));
|
||||
icons::paint(child.painter(), dr.shrink(3.0), Icon::Detach, t.icon_secondary);
|
||||
if dresp.clicked() {
|
||||
app.run("variable.bind", json!({"ids": ids, "field": key, "variable": null}));
|
||||
}
|
||||
}
|
||||
}
|
||||
PaintKind::Solid { color } => {
|
||||
if let Some(h) = widgets::text_field_inline(
|
||||
&mut child,
|
||||
Id::unique(("hex", fills, i)),
|
||||
&color.to_hex(),
|
||||
text_r.shrink2(vec2(0.0, 4.0)),
|
||||
regular(11.0),
|
||||
) && let Some(c) = figcraft_color::Color::from_hex_or_name(&h)
|
||||
{
|
||||
app.run(cmd, json!({"ids": ids, "index": i, "color": c.to_css_hex()}));
|
||||
PaintKind::Solid { color } => {
|
||||
if let Some(h) = widgets::text_field_inline(
|
||||
child,
|
||||
Id::unique(("hex", fills, i)),
|
||||
&color.to_hex(),
|
||||
text_r.shrink2(vec2(0.0, 4.0)),
|
||||
regular(11.0),
|
||||
) && let Some(c) = figcraft_color::Color::from_hex_or_name(&h)
|
||||
{
|
||||
app.run(cmd, json!({"ids": ids, "index": i, "color": c.to_css_hex()}));
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
child.painter().text(pos2(text_r.min.x, r.center().y), Align2::LEFT_CENTER, paint_label(p), regular(11.0), t.text);
|
||||
// One layer's image fill: crop it on the canvas.
|
||||
if fills && ids.len() == 1 && matches!(p.kind, PaintKind::Image(_)) {
|
||||
let cr = Rect::from_center_size(pos2(text_r.max.x - 9.0, r.center().y), vec2(18.0, 18.0));
|
||||
let cresp = ui.interact(cr, Id::unique(("crop_image", i)), Sense::click()).tip(tr("Crop image"));
|
||||
icons::paint(ui.painter(), cr.shrink(3.0), Icon::Crop, if cresp.hovered() { t.icon } else { t.icon_secondary });
|
||||
if cresp.clicked() {
|
||||
app.run("image.crop", json!({"ids": ids, "index": i}));
|
||||
_ => {
|
||||
child.painter().text(pos2(text_r.min.x, r.center().y), Align2::LEFT_CENTER, paint_label(p), regular(11.0), t.text);
|
||||
// One layer's image fill: crop it on the canvas.
|
||||
if fills && ids.len() == 1 && matches!(p.kind, PaintKind::Image(_)) {
|
||||
let cr = Rect::from_center_size(pos2(text_r.max.x - 9.0, r.center().y), vec2(18.0, 18.0));
|
||||
let cresp = child.interact(cr, Id::unique(("crop_image", i)), Sense::click()).tip(tr("Crop image"));
|
||||
icons::paint(child.painter(), cr.shrink(3.0), Icon::Crop, if cresp.hovered() { t.icon } else { t.icon_secondary });
|
||||
if cresp.clicked() {
|
||||
app.run("image.crop", json!({"ids": ids, "index": i}));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let op_r = Rect::from_min_max(pos2(r.max.x - 48.0, r.min.y), r.max);
|
||||
ui.painter().line_segment([pos2(op_r.min.x, r.min.y + 4.0), pos2(op_r.min.x, r.max.y - 4.0)], Stroke::new(1.0, t.panel));
|
||||
let mut child = ui.new_child(egui::UiBuilder::new().max_rect(op_r));
|
||||
let e = widgets::number_field(
|
||||
&mut child,
|
||||
Id::unique(("pop", fills, i)),
|
||||
Lead::None,
|
||||
Some((f64::from(p.opacity) * 100.0).round()),
|
||||
"%",
|
||||
48.0,
|
||||
1.0,
|
||||
);
|
||||
});
|
||||
app.picker_control(crate::colorpicker::PickerTarget::Paint { fills, index: i, ids: ids.clone() }, &sresp);
|
||||
match e {
|
||||
Some(FieldEdit::Set(v)) => {
|
||||
app.run(cmd, json!({"ids": ids, "index": i, "opacity": (v / 100.0).clamp(0.0, 1.0)}));
|
||||
|
||||
@@ -24,6 +24,12 @@ struct Cache {
|
||||
colors: Arc<Vec<SelectionColor>>,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct OpacityScrub {
|
||||
targets: Vec<PaintTarget>,
|
||||
opacity: f32,
|
||||
}
|
||||
|
||||
/// Return the cached selection colours when the document and selection match. During an
|
||||
/// interaction reuse an existing matching cache, or return an empty list without discovering
|
||||
/// colours; otherwise discover and cache them.
|
||||
@@ -47,6 +53,7 @@ fn colors(ui: &Ui, document: u64, doc: &Arc<Document>, ids: &[NodeId], interacti
|
||||
colors
|
||||
}
|
||||
|
||||
/// Open or close the picker for frozen paint targets, anchored to the invoking control.
|
||||
pub(crate) fn toggle(app: &mut FigApp, targets: Vec<PaintTarget>, response: Option<&egui::Response>) {
|
||||
let Ok(ds) = app.session.ds() else { return };
|
||||
let target = PickerTarget::SelectionColor { targets, selection: ds.selection.clone(), document: ds.uid };
|
||||
@@ -70,97 +77,139 @@ pub fn section(app: &mut FigApp, ui: &mut Ui, doc: &Arc<Document>, ids: &[NodeId
|
||||
let t = Tokens::get(ui.ctx());
|
||||
widgets::section_header(ui, tr("Selection colors"), &[], false);
|
||||
// Bound the panel's height; a document with many distinct colors stays scrollable.
|
||||
ui.add_enabled_ui(!interacting, |ui| {
|
||||
let scrub_key = Id::unique("selection_color_scrub");
|
||||
if !interacting {
|
||||
ui.data_mut(|d| d.remove::<OpacityScrub>(scrub_key));
|
||||
}
|
||||
let scrubbing = ui.data(|d| d.get_temp::<OpacityScrub>(scrub_key));
|
||||
ui.add_enabled_ui(!interacting || scrubbing.is_some(), |ui| {
|
||||
egui::ScrollArea::vertical().id_salt("selection_colors_rows").max_height(240.0).show_rows(ui, 32.0, colors.len(), |ui, range| {
|
||||
for group in &colors[range] {
|
||||
ui.push_id((&group.targets, "selection_color"), |ui| {
|
||||
crate::right::row(ui, 32.0, |ui| {
|
||||
let swatch = widgets::swatch(ui, &group.paint, 24.0).tip(tr("Edit colour"));
|
||||
toggle(app, group.targets.clone(), Some(&swatch));
|
||||
let width = (ui.available_width() - 116.0).max(40.0);
|
||||
let linked_name = group
|
||||
.style
|
||||
.as_ref()
|
||||
.and_then(|id| doc.style(id).map(|s| s.name.as_str()))
|
||||
.or_else(|| group.variable.as_ref().and_then(|id| doc.variables.get_by_id(id).map(|v| v.name.as_str())));
|
||||
if let Some(name) = linked_name {
|
||||
let response = widgets::dropdown(ui, name, width, None);
|
||||
toggle(app, group.targets.clone(), Some(&response));
|
||||
} else if let Some(color) = group.paint.solid_color() {
|
||||
if let Some(hex) = widgets::text_field_named(ui, ui.scope_id().with("hex"), &color.to_hex(), width, tr("Color")) {
|
||||
if let Some(color) = Color::from_hex(&hex) {
|
||||
let mut paint = group.paint.clone();
|
||||
paint.kind = figcraft_color::PaintKind::Solid { color: color.with_alpha(1.0) };
|
||||
if color.a < 1.0 {
|
||||
paint.opacity = color.a;
|
||||
}
|
||||
app.run("selection.setPaint", json!({"targets": group.targets, "paint": paint}));
|
||||
} else {
|
||||
app.toast(tr("Invalid color"));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
let response = widgets::dropdown(ui, &widgets::paint_name(&group.paint), width, None);
|
||||
toggle(app, group.targets.clone(), Some(&response));
|
||||
}
|
||||
let alpha = format!("{}%", figcraft_doc::trim_num(f64::from(group.paint.opacity) * 100.0));
|
||||
if let Some(value) = widgets::text_field_named(ui, ui.scope_id().with("opacity"), &alpha, 44.0, tr("Opacity"))
|
||||
&& let Ok(value) = value.trim().trim_end_matches('%').parse::<f32>()
|
||||
&& value.is_finite()
|
||||
let width = ui.available_width() - 60.0;
|
||||
let mut paint = group.paint.clone();
|
||||
if let Some(scrub) = &scrubbing
|
||||
&& scrub.targets == group.targets
|
||||
{
|
||||
let mut paint = group.paint.clone();
|
||||
paint.opacity = (value / 100.0).clamp(0.0, 1.0);
|
||||
app.run("selection.setPaint", json!({"targets": group.targets, "paint": paint}));
|
||||
paint.opacity = scrub.opacity;
|
||||
}
|
||||
if linked_name.is_some() {
|
||||
let detach = if group.style.is_some() { tr("Detach style") } else { tr("Detach variable") };
|
||||
if icons::button(ui, Icon::Detach, 24.0, false, detach).clicked() {
|
||||
app.run("selection.detachColor", json!({"targets": group.targets}));
|
||||
}
|
||||
} else {
|
||||
let styles = icons::button(ui, Icon::Styles, 24.0, false, tr("Color styles"));
|
||||
crate::right::menu_popup(&styles).show(|ui| {
|
||||
let mut any = false;
|
||||
for style in &doc.styles {
|
||||
if !matches!(style.kind, StyleKind::Paint { .. }) {
|
||||
continue;
|
||||
}
|
||||
any = true;
|
||||
if crate::right::menu_item(ui, &style.name, "") {
|
||||
app.run("selection.applyColorStyle", json!({"targets": group.targets, "style": style.id}));
|
||||
app.ui.picker = None;
|
||||
ui.close();
|
||||
let mut name_response = None;
|
||||
let (swatch, opacity) = widgets::paint_field(
|
||||
ui,
|
||||
ui.scope_id().with("paint_field"),
|
||||
ui.scope_id().with("opacity"),
|
||||
&paint,
|
||||
width,
|
||||
|child, rect| {
|
||||
if linked_name.is_some() || group.paint.solid_color().is_none() {
|
||||
let name = linked_name.map(str::to_owned).unwrap_or_else(|| widgets::paint_name(&group.paint));
|
||||
child.painter().with_clip_rect(rect).text(
|
||||
rect.left_center(),
|
||||
egui::Align2::LEFT_CENTER,
|
||||
&name,
|
||||
crate::theme::regular(11.0),
|
||||
t.text,
|
||||
);
|
||||
name_response = Some(child.interact(rect, child.scope_id().with("paint_name"), egui::Sense::click()).tip(name));
|
||||
} else if let Some(color) = group.paint.solid_color()
|
||||
&& let Some(hex) = widgets::text_field_inline(
|
||||
child,
|
||||
child.scope_id().with("hex"),
|
||||
&color.to_hex(),
|
||||
rect.shrink2(egui::vec2(0.0, 4.0)),
|
||||
crate::theme::regular(11.0),
|
||||
)
|
||||
{
|
||||
if let Some(color) = Color::from_hex_or_name(&hex) {
|
||||
let mut paint = group.paint.clone();
|
||||
paint.kind = figcraft_color::PaintKind::Solid { color: color.with_alpha(1.0) };
|
||||
if color.a < 1.0 {
|
||||
paint.opacity = color.a;
|
||||
}
|
||||
app.run("selection.setPaint", json!({"targets": group.targets, "paint": paint}));
|
||||
} else {
|
||||
app.toast(tr("Invalid color"));
|
||||
}
|
||||
}
|
||||
if !any {
|
||||
widgets::label(ui, tr("No color styles"), t.text_secondary);
|
||||
}
|
||||
let variables: Vec<_> = doc
|
||||
.variables
|
||||
.variables
|
||||
.iter()
|
||||
.filter(|v| {
|
||||
v.kind == VariableType::Color
|
||||
&& bind_refusal(doc, &group.targets, &v.id).is_none()
|
||||
&& in_scope(doc, &group.targets, &v.id)
|
||||
})
|
||||
.collect();
|
||||
if !variables.is_empty() {
|
||||
ui.separator();
|
||||
widgets::label(ui, tr("Color variables"), t.text_secondary);
|
||||
}
|
||||
for v in variables {
|
||||
if crate::right::menu_item(ui, &v.name, "") {
|
||||
app.run("selection.bindColorVariable", json!({"targets": group.targets, "variable": v.id}));
|
||||
app.ui.picker = None;
|
||||
ui.close();
|
||||
}
|
||||
},
|
||||
);
|
||||
toggle(app, group.targets.clone(), Some(&swatch));
|
||||
if let Some(response) = name_response {
|
||||
toggle(app, group.targets.clone(), Some(&response));
|
||||
}
|
||||
if let Some(edit) = opacity {
|
||||
let (value, scrub, done) = match edit {
|
||||
widgets::FieldEdit::Set(value) => (value, false, false),
|
||||
widgets::FieldEdit::Scrub(value, done) => (value, true, done),
|
||||
};
|
||||
let mut paint = group.paint.clone();
|
||||
paint.opacity = (value / 100.0).clamp(0.0, 1.0) as f32;
|
||||
ui.data_mut(|d| {
|
||||
if scrub && !done {
|
||||
d.insert_temp(scrub_key, OpacityScrub { targets: group.targets.clone(), opacity: paint.opacity });
|
||||
} else {
|
||||
d.remove::<OpacityScrub>(scrub_key);
|
||||
}
|
||||
});
|
||||
app.field_run_named(Some(edit), "Opacity", "selection.setPaint", |_| json!({"targets": group.targets, "paint": paint}));
|
||||
}
|
||||
if icons::button(ui, Icon::Move, 24.0, false, tr("Select layers with this color")).clicked() {
|
||||
app.run("selection.selectColor", json!({"targets": group.targets}));
|
||||
}
|
||||
widgets::tight_end(ui, |ui| {
|
||||
if linked_name.is_some() {
|
||||
let detach = if group.style.is_some() { tr("Detach style") } else { tr("Detach variable") };
|
||||
if icons::button(ui, Icon::Detach, 24.0, false, detach).clicked() {
|
||||
app.run("selection.detachColor", json!({"targets": group.targets}));
|
||||
}
|
||||
} else {
|
||||
let styles = icons::button(ui, Icon::Styles, 24.0, false, tr("Color styles"));
|
||||
crate::right::menu_popup(&styles).show(|ui| {
|
||||
let mut any = false;
|
||||
for style in &doc.styles {
|
||||
if !matches!(style.kind, StyleKind::Paint { .. }) {
|
||||
continue;
|
||||
}
|
||||
any = true;
|
||||
if crate::right::menu_item(ui, &style.name, "") {
|
||||
app.run("selection.applyColorStyle", json!({"targets": group.targets, "style": style.id}));
|
||||
app.ui.picker = None;
|
||||
ui.close();
|
||||
}
|
||||
}
|
||||
if !any {
|
||||
widgets::label(ui, tr("No color styles"), t.text_secondary);
|
||||
}
|
||||
let variables: Vec<_> = doc
|
||||
.variables
|
||||
.variables
|
||||
.iter()
|
||||
.filter(|v| {
|
||||
v.kind == VariableType::Color
|
||||
&& bind_refusal(doc, &group.targets, &v.id).is_none()
|
||||
&& in_scope(doc, &group.targets, &v.id)
|
||||
})
|
||||
.collect();
|
||||
if !variables.is_empty() {
|
||||
ui.separator();
|
||||
widgets::label(ui, tr("Color variables"), t.text_secondary);
|
||||
}
|
||||
for v in variables {
|
||||
if crate::right::menu_item(ui, &v.name, "") {
|
||||
app.run("selection.bindColorVariable", json!({"targets": group.targets, "variable": v.id}));
|
||||
app.ui.picker = None;
|
||||
ui.close();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
if icons::button(ui, Icon::SelectColor, 24.0, false, tr("Select layers with this color")).clicked() {
|
||||
app.run("selection.selectColor", json!({"targets": group.targets}));
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -181,6 +230,7 @@ mod tests {
|
||||
ctx: egui::Context,
|
||||
app: FigApp,
|
||||
time: f64,
|
||||
modifiers: egui::Modifiers,
|
||||
}
|
||||
|
||||
impl Panel {
|
||||
@@ -192,7 +242,7 @@ mod tests {
|
||||
ids.push(NodeId(value["id"].as_u64().unwrap()));
|
||||
}
|
||||
s.execute("select.set", &json!({"ids":ids})).unwrap();
|
||||
let mut p = Self { ctx: egui::Context::default(), app: FigApp::new(s, Box::new(NoServices)), time: 0.0 };
|
||||
let mut p = Self { ctx: egui::Context::default(), app: FigApp::new(s, Box::new(NoServices)), time: 0.0, modifiers: Default::default() };
|
||||
crate::theme::install_fonts(&p.ctx, false, 0);
|
||||
crate::theme::apply(&p.ctx, crate::theme::Tokens::light());
|
||||
for _ in 0..3 {
|
||||
@@ -200,7 +250,9 @@ mod tests {
|
||||
}
|
||||
(p, ids[0], ids[1])
|
||||
}
|
||||
fn frame(&mut self, events: Vec<Event>) -> Vec<(String, Pos2)> {
|
||||
/// Run one panel frame, retaining its shapes and accessibility output for assertions.
|
||||
fn output(&mut self, mut events: Vec<Event>) -> egui::FullOutput {
|
||||
events.insert(0, Event::ModifiersChanged(self.modifiers));
|
||||
self.time += 1.0 / 60.0;
|
||||
let input = RawInput {
|
||||
screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(280.0, 600.0))),
|
||||
@@ -215,6 +267,10 @@ mod tests {
|
||||
section(&mut self.app, ui, &doc, &ids);
|
||||
});
|
||||
output.textures_delta.clear();
|
||||
output
|
||||
}
|
||||
fn frame(&mut self, events: Vec<Event>) -> Vec<(String, Pos2)> {
|
||||
let output = self.output(events);
|
||||
fn texts(shape: &Shape, out: &mut Vec<(String, Pos2)>) {
|
||||
match shape {
|
||||
Shape::Text(t) => out.push((t.galley.text().to_string(), t.pos + t.galley.size() / 2.0)),
|
||||
@@ -300,6 +356,127 @@ mod tests {
|
||||
assert!(p.app.ui.last_error.is_none());
|
||||
}
|
||||
|
||||
/// Stored variable ids must never resolve to another variable with that name.
|
||||
#[test]
|
||||
fn linked_variable_name_uses_its_stored_id_when_another_name_matches() {
|
||||
let (mut p, a, _) = Panel::new();
|
||||
p.app.run("variable.createCollection", json!({"name":"Theme"}));
|
||||
let shadow = p.app.run("variable.create", json!({"collection":"Theme","name":"Shadow","type":"color","value":"#ff0000"})).unwrap();
|
||||
let accent = p.app.run("variable.create", json!({"collection":"Theme","name":"Accent","type":"color","value":"#00ff00"})).unwrap();
|
||||
p.app.run("variable.bind", json!({"id":a,"field":"fill","variable":accent["id"]}));
|
||||
p.app.run("variable.update", json!({"variable":shadow["id"],"name":accent["id"]}));
|
||||
assert!(p.app.ui.last_error.is_none());
|
||||
let texts = p.frame(vec![]);
|
||||
assert!(texts.iter().any(|(text, _)| text == "Accent"));
|
||||
assert!(!texts.iter().any(|(text, _)| text == accent["id"].as_str().unwrap()));
|
||||
}
|
||||
|
||||
/// Shared swatches stay distinguishable by their paint values to assistive technology.
|
||||
#[test]
|
||||
fn shared_swatch_announces_its_colour_and_keeps_the_edit_label() {
|
||||
let (mut p, _, _) = Panel::new();
|
||||
p.ctx.enable_accesskit();
|
||||
let output = p.output(vec![]);
|
||||
let nodes = output.platform_output.accesskit_update.unwrap().nodes;
|
||||
let mut values: Vec<_> = nodes
|
||||
.iter()
|
||||
.filter_map(|(_, node)| {
|
||||
if node.role() == egui::accesskit::Role::ColorWell {
|
||||
assert_eq!(node.label(), Some("Edit colour"));
|
||||
Some(node.value().unwrap().to_string())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
values.sort();
|
||||
assert_eq!(values, ["0000FF", "FF0000"]);
|
||||
}
|
||||
|
||||
/// Consecutive fine scrubs retain fractional baselines and each get one undo step.
|
||||
#[test]
|
||||
fn fractional_opacity_is_displayed_and_accumulates_across_fine_scrubs() {
|
||||
let (mut p, a, _) = Panel::new();
|
||||
p.app.run("fill.set", json!({"id":a, "opacity":0.999}));
|
||||
let texts = p.frame(vec![]);
|
||||
assert!(texts.iter().any(|(text, _)| text == "99.9%"));
|
||||
let red = texts.into_iter().find(|(text, _)| text == "FF0000").unwrap().1;
|
||||
let start = Pos2::new(167.0, red.y);
|
||||
p.modifiers.alt = true;
|
||||
for expected in [0.989, 0.979] {
|
||||
p.frame(vec![
|
||||
Event::PointerMoved(start),
|
||||
Event::PointerButton { pos: start, button: egui::PointerButton::Primary, pressed: true, modifiers: p.modifiers },
|
||||
]);
|
||||
for dx in [-4.0, -8.0, -10.0] {
|
||||
p.frame(vec![Event::PointerMoved(start + vec2(dx, 0.0))]);
|
||||
}
|
||||
p.frame(vec![Event::PointerButton {
|
||||
pos: start - vec2(10.0, 0.0),
|
||||
button: egui::PointerButton::Primary,
|
||||
pressed: false,
|
||||
modifiers: p.modifiers,
|
||||
}]);
|
||||
assert!(p.app.session.ds().unwrap().interaction.is_none());
|
||||
let opacity = p.app.session.doc().unwrap().node(a).unwrap().fills[0].opacity;
|
||||
assert!((opacity - expected).abs() < 1e-6, "fine scrub kept fractional baseline: {opacity}");
|
||||
}
|
||||
assert!(p.frame(vec![]).iter().any(|(text, _)| text == "97.9%"));
|
||||
for expected in [0.989, 0.999] {
|
||||
p.app.run("edit.undo", json!({}));
|
||||
let opacity = p.app.session.doc().unwrap().node(a).unwrap().fills[0].opacity;
|
||||
assert!((opacity - expected).abs() < 1e-6, "each fine scrub is one undo step: {opacity}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shared_color_field_edits_hex_and_opacity_and_undoes_each_edit() {
|
||||
let (mut p, a, _) = Panel::new();
|
||||
let red = p.frame(vec![]).into_iter().find(|(s, _)| s == "FF0000").unwrap().1;
|
||||
p.click(red);
|
||||
p.frame(vec![Event::Text("00FF00".into())]);
|
||||
let enter = Event::Key { key: egui::Key::Enter, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() };
|
||||
p.frame(vec![enter.clone()]);
|
||||
assert_eq!(p.app.session.doc().unwrap().node(a).unwrap().fills[0].solid_color().unwrap().to_hex(), "00FF00");
|
||||
p.frame(vec![]);
|
||||
p.click(Pos2::new(176.0, red.y));
|
||||
p.frame(vec![Event::Text("45".into())]);
|
||||
p.frame(vec![enter]);
|
||||
assert_eq!(p.app.session.doc().unwrap().node(a).unwrap().fills[0].opacity, 0.45);
|
||||
p.app.run("edit.undo", json!({}));
|
||||
assert_eq!(p.app.session.doc().unwrap().node(a).unwrap().fills[0].opacity, 1.0);
|
||||
p.app.run("edit.undo", json!({}));
|
||||
assert_eq!(p.app.session.doc().unwrap().node(a).unwrap().fills[0].solid_color().unwrap().to_hex(), "FF0000");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shared_opacity_field_keeps_dragging_until_release_as_one_undo_step() {
|
||||
let (mut p, a, _) = Panel::new();
|
||||
let red = p.frame(vec![]).into_iter().find(|(s, _)| s == "FF0000").unwrap().1;
|
||||
let start = Pos2::new(167.0, red.y);
|
||||
p.frame(vec![
|
||||
Event::PointerMoved(start),
|
||||
Event::PointerButton { pos: start, button: egui::PointerButton::Primary, pressed: true, modifiers: Default::default() },
|
||||
]);
|
||||
for dx in [-10.0, -20.0, -30.0] {
|
||||
p.frame(vec![Event::PointerMoved(start + vec2(dx, 0.0))]);
|
||||
}
|
||||
assert!(p.app.session.ds().unwrap().interaction.is_some(), "the scrub commits only on release");
|
||||
assert!(p.frame(vec![]).iter().any(|(text, _)| text == "70%"), "the live opacity stays visible while scrubbing");
|
||||
p.frame(vec![Event::PointerButton {
|
||||
pos: start - vec2(30.0, 0.0),
|
||||
button: egui::PointerButton::Primary,
|
||||
pressed: false,
|
||||
modifiers: Default::default(),
|
||||
}]);
|
||||
assert!(p.app.session.ds().unwrap().interaction.is_none());
|
||||
assert_eq!(p.app.session.doc().unwrap().node(a).unwrap().fills[0].opacity, 0.7);
|
||||
assert_eq!(p.app.session.undo_labels(1), ["Opacity"], "the shared helper preserves the scrub's undo label");
|
||||
p.app.run("edit.undo", json!({}));
|
||||
assert_eq!(p.app.session.doc().unwrap().node(a).unwrap().fills[0].opacity, 1.0);
|
||||
assert_eq!(p.app.session.selection().len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn panel_displays_the_linked_style_name_and_the_other_color() {
|
||||
let (mut p, a, b) = Panel::new();
|
||||
|
||||
@@ -1041,6 +1041,35 @@ pub fn checker(painter: &egui::Painter, rect: Rect, cell: f32) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Shared Fill/Stroke/Selection colors control: one background, a 16 pt swatch,
|
||||
/// caller-provided colour content, and a separated, scrubbable opacity field.
|
||||
/// The caller owns picker routing and commands; this widget only draws and reports edits.
|
||||
pub fn paint_field(
|
||||
ui: &mut Ui,
|
||||
id: Id,
|
||||
opacity_id: Id,
|
||||
paint: &figcraft_color::Paint,
|
||||
width: f32,
|
||||
content: impl FnOnce(&mut Ui, Rect),
|
||||
) -> (Response, Option<FieldEdit>) {
|
||||
let t = Tokens::get(ui.ctx());
|
||||
let (r, _) = ui.allocate_exact_size(vec2(width, FIELD_H), Sense::hover());
|
||||
ui.painter().rect_filled(r, CornerRadius::same(5), t.field);
|
||||
let sw = Rect::from_min_size(pos2(r.min.x + 4.0, r.center().y - 8.0), vec2(16.0, 16.0));
|
||||
paint_swatch(ui.painter(), sw, paint);
|
||||
let swatch = ui.interact(sw.expand(2.0), id, Sense::click()).tip(tr("Edit colour"));
|
||||
let value = if a11y::active(&swatch.ctx) { paint_name(paint) } else { String::new() };
|
||||
a11y::color(&swatch, tr("Edit colour"), &value);
|
||||
let text_r = Rect::from_min_max(pos2(sw.max.x + 8.0, r.min.y), pos2(r.max.x - 52.0, r.max.y));
|
||||
let mut child = ui.new_child(egui::UiBuilder::new().max_rect(text_r));
|
||||
content(&mut child, text_r);
|
||||
let op_r = Rect::from_min_max(pos2(r.max.x - 48.0, r.min.y), r.max);
|
||||
ui.painter().line_segment([pos2(op_r.min.x, r.min.y + 4.0), pos2(op_r.min.x, r.max.y - 4.0)], Stroke::new(1.0, t.panel));
|
||||
let mut child = ui.new_child(egui::UiBuilder::new().max_rect(op_r));
|
||||
let opacity = number_field(&mut child, opacity_id, Lead::Named(tr("Opacity")), Some(f64::from(paint.opacity) * 100.0), "%", 48.0, 1.0);
|
||||
(swatch, opacity)
|
||||
}
|
||||
|
||||
/// A paint swatch (with checkerboard under transparent colours).
|
||||
pub fn swatch(ui: &mut Ui, paint: &figcraft_color::Paint, size: f32) -> Response {
|
||||
swatch_named(ui, paint, size, tr("Color"))
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Boards parity
|
||||
|
||||
> **Last reviewed:** 2026-10-24 · **Last updated:** 2026-10-31 · **Change:** minor (a connector end moved with Cmd/Ctrl held goes on any part of an object, and stays there as the object moves or resizes; a connector end dropped along a side of a shape attaches to that side (#1708); a board connector's path can be reshaped by dragging its path handles (#1710); boards have 16 more shapes (arrows, polygons, star, plus and flowchart symbols), in pickers that lay them out in a grid; a board keeps earlier votes' results, listed newest first in Results and deleted one at a time; a connector's bar sets its start and end points, dashes, weight and any colour (#1596); cells copied from a spreadsheet paste onto a board as a table; Shift+Cmd/Ctrl+Enter on a selected board shape adds the next shape already joined to it, and goes on typing (#1597); "+" handles beside a selected sticky or shape make the next one, joined by a connector (#1597); a FigJam `.jam` file opens as a board (#1342); board grid settings: dots, lines, graph paper or none, spacing, size and contrast; the connector tool shows the connector it will make while dragging, ends snapping to attach points (#1387); templates and tables; facilitation: a shared timer and voting sessions; the dot grid, dragging a connector's end to re-attach it, curved connectors, elbows that go around what they join) · **Target:** the incumbent's whiteboard product (behaviour from its public help centre)
|
||||
> **Last reviewed:** 2026-10-24 · **Last updated:** 2026-11-04 · **Change:** minor (a connector attached to a side starts 4 pt outside the border, so its stroke never lies on the fill (#1916); a connector end moved with Cmd/Ctrl held goes on any part of an object, and stays there as the object moves or resizes; a connector end dropped along a side of a shape attaches to that side (#1708); a board connector's path can be reshaped by dragging its path handles (#1710); boards have 16 more shapes (arrows, polygons, star, plus and flowchart symbols), in pickers that lay them out in a grid; a board keeps earlier votes' results, listed newest first in Results and deleted one at a time; a connector's bar sets its start and end points, dashes, weight and any colour (#1596); cells copied from a spreadsheet paste onto a board as a table; Shift+Cmd/Ctrl+Enter on a selected board shape adds the next shape already joined to it, and goes on typing (#1597); "+" handles beside a selected sticky or shape make the next one, joined by a connector (#1597); a FigJam `.jam` file opens as a board (#1342); board grid settings: dots, lines, graph paper or none, spacing, size and contrast; the connector tool shows the connector it will make while dragging, ends snapping to attach points (#1387); templates and tables; facilitation: a shared timer and voting sessions; the dot grid, dragging a connector's end to re-attach it, curved connectors, elbows that go around what they join) · **Target:** the incumbent's whiteboard product (behaviour from its public help centre)
|
||||
|
||||
**Breadth ~47%, ready ~29% (estimated, erring low).** A board is a FigCraft file of its own kind
|
||||
(`file.newBoard`) with a dot grid on the page, sticky notes, shapes with text, connectors that
|
||||
@@ -34,10 +34,10 @@ all end with the same geometry.
|
||||
| Sticky options: hide the author, change size presets, sticky stacks | partial | `board.sticky {author: false}`; no size presets or stacks |
|
||||
| Shapes with text | done | rectangle, rounded rectangle, ellipse, diamond, triangle, speech bubble, chevron; text centred and wrapping inside the outline; shape type and text size from the contextual bar |
|
||||
| Shape auto-fit to its text, more shapes (cylinder, cross, star…), shape libraries | missing | |
|
||||
| Connectors | done | from a layer's side (the facing one, or one named) to another layer or a free point, straight, elbow or curved, arrowheads (the stroke's caps), a label in the middle of the route by length (double-click to add); while one is dragged out it shows as it will be made (route, line and arrowhead), the object under the pointer outlined with its four attach points (side middles), the one the end goes to ringed; an end dropped on the outer half of an object takes the side it is towards (a drop along a whole edge chooses that edge), one in the middle takes the facing side; re-routed when either end moves or resizes; a deleted end stays where it was |
|
||||
| Connectors | done | from a layer's side (the facing one, or one named) to another layer or a free point, straight, elbow or curved, arrowheads (the stroke's caps), a label in the middle of the route by length (double-click to add); while one is dragged out it shows as it will be made (route, line and arrowhead), the object under the pointer outlined with its four attach points (side middles), the one the end goes to ringed; an end dropped on the outer half of an object takes the side it is towards (a drop along a whole edge chooses that edge), one in the middle takes the facing side; re-routed when either end moves or resizes; a deleted end stays where it was; an end attached to a side starts 4 pt outside the border (`board_route::END_GAP`), so the stroke never lies on the fill; elbows leaving one side share their first run along its normal and curves leave tangent to it (#1916) |
|
||||
| Shapes with text | done | 23 outlines: rectangle, rounded rectangle, ellipse, diamond, triangle up and down, parallelogram right and left, trapezoid, pentagon, hexagon, octagon, star, plus, arrow left and right, chevron, speech bubble, and the flowchart symbols database, document, predefined process, manual input and internal storage; text centred and wrapping inside the outline; shape type and text size from the contextual bar |
|
||||
| Shape auto-fit to its text, the advanced shape libraries (engineering and other icon shapes) | missing | |
|
||||
| Connectors | done | from a layer's side (the facing one, or one named) to another layer or a free point, straight, elbow or curved, arrowheads (the stroke's caps), a label in the middle of the route by length (double-click to add); while one is dragged out it shows as it will be made (route, line and arrowhead), the object under the pointer outlined with its four attach points (side middles), the one the end goes to ringed, and within 10 px of one the end keeps that side; re-routed when either end moves or resizes; a deleted end stays where it was |
|
||||
| Connectors | done | from a layer's side (the facing one, or one named) to another layer or a free point, straight, elbow or curved, arrowheads (the stroke's caps), a label in the middle of the route by length (double-click to add); while one is dragged out it shows as it will be made (route, line and arrowhead), the object under the pointer outlined with its four attach points (side middles), the one the end goes to ringed, and within 10 px of one the end keeps that side; re-routed when either end moves or resizes; a deleted end stays where it was; an end attached to a side starts 4 pt outside the border (`board_route::END_GAP`), so the stroke never lies on the fill; elbows leaving one side share their first run along its normal and curves leave tangent to it (#1916) |
|
||||
| Create the next shape already connected | done | a selected sticky or shape shows a "+" beside each side; hovering one shows where the next goes, clicking makes one of the same kind, size and colour there, joined by a connector as the Connector tool makes one, and starts typing in it; one undo step (`board.addConnected {id?, side?, edit?}`, #1597). Shift+Cmd/Ctrl+Enter on a selected (or edited) shape adds the next shape on its right, joined the same way, and goes on typing; on a sticky it adds a sticky beside it without a connector, as before |
|
||||
| Curved connectors, elbows around objects, dragging an end to re-attach | done | `board.setStyle {style: curved}` (and the contextual bar): one curve leaving and arriving along the sides; an elbow whose short way would cross what it joins goes around their boxes, 24 units clear; a selected connector shows its two ends as handles, and dragging one onto an object attaches it there (the object is outlined while dragging), onto empty canvas leaves it free (`board.reattach {id, end, target, side?}`, one undo step) |
|
||||
| A connector end on any part of an object | done | holding Cmd/Ctrl while moving an end places it where the pointer is on the object, as a share of its box, so it follows moves and resizes; the line leaves by the side facing the other end. Without the key an end snaps to a side |
|
||||
@@ -70,6 +70,7 @@ all end with the same geometry.
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-11-04 | minor | M12, #1916: a connector end attached to a side starts 4 pt outside the border (`board_route::END_GAP`), as FigJam's do (the issue's screenshots: the line starts a few pixels outside, with a round cap), so the stroke never lies on the fill; elbows leaving one side share their first run along its normal, curves leave tangent to it and straight ones fan out from the same point; the `.jam` importer's routes, re-attached ends, path handles and labels follow the route's points; an end placed by hand with Cmd/Ctrl held keeps its exact point. Tests: `board_route_tests` (three). Numbers unchanged. |
|
||||
| 2026-10-31 | minor | M12: as the help describes, holding Cmd/Ctrl while moving a connector's end places it on any part of an object instead of snapping to a side. It keeps that spot as a fraction of the object's box, so it follows the object when it moves or resizes, and without the key an end snaps as before. `board.connector {fromAt, toAt}` and `board.reattach {at}` take it; saved only when set. Numbers unchanged |
|
||||
| 2026-10-31 | patch | M12, #1708: a connector end dropped on the outer half of a shape takes the side it is towards, instead of only within 10 px of a side's middle, so a drop anywhere along an edge chooses that edge (dragging a selected connector's end and with the connector tool, ring included); a drop in the middle of a shape still takes the facing side. |
|
||||
| 2026-10-31 | minor | M12, #1710: a selected elbow or curved connector shows path handles. Dragging a run moves it and a first or last run gains an extra run to stay on its end; a curve's middle goes where it is dragged (`board.reshape`, one undo step). The shape travels with what the connector joins, is saved with the file, and goes back to routing itself when the style changes or an end moves to something else. |
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Collaboration parity
|
||||
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-06 · **Change:** minor (a file shared on the local network can be shared to look at only: a view-only code next to the edit code, picked in the Share popover before or while sharing)
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-06 · **Change:** minor (; a file shared on the local network can be shared to look at only: a view-only code next to the edit code, picked in the Share popover before or while sharing)
|
||||
|
||||
Figma is multiplayer first; FigCraft is local first. **Ready ~13% (estimated):** comments, version
|
||||
history and branches (review and merge) work inside one file; the real-time collaboration core landed in #103 (sync model,
|
||||
@@ -18,7 +18,7 @@ cursors, selections, text carets, cursor chat and spotlights shown live ([`colla
|
||||
| Share links, permissions (view / edit), teams and projects | yes | **partial**: sharing with a join code from the Share popover (online: the file goes to the server in Preferences and the server names its edit, comment and view links with short codes; local network: the app hosts and the code carries its address, with an edit code and a view-only code, picked before or while sharing, whose holders see every change and can't make one; one field joins with a code or a link, in the popover and on the home screen, and the Join dialog then shows the join until its file is ready (Cancel), or why it failed (Try again, #1381); the browser build also joins from a link in its URL's fragment, `#join=…`, which never reaches the web host's logs, capped at 6 KiB and checked like a `figcraft://` link (#712; unit-tested, not run in a browser), and shares online and publishes to a server as the desktop app does, though not on the local network (#917; the owner token of a file it puts on an open server lasts as long as the page)); `figcraft-server` share links per file with edit, comment or view access (a viewer sees changes and presence, a "View only" badge and only the moving tools; a commenter also adds, replies to, reacts to and resolves comment threads, with a "Can comment" badge and the comment tool, #1525; the server refuses their other edits), revocable at once, tokens stored as hashes; managed from the app's Share popover (first links), the server's command line or a managing connection. On a server open to the public, whoever published a file manages it with its owner token (links, name, removal: `collab.manageFile`), which the app remembers: Home ▸ Online lists your online files (open again as owner, start and stop sharing, copy the code, rename, remove, forget), with one request per server for what became of them; anyone in a file can report it, and the operator blocks addresses. The person hosting a session, or a file's owner, removes someone from it (right-click their avatar, `collab.removePerson`): they are disconnected and their address can't join that file again while it runs. The list is per computer; a server only a team reaches can also list the files shared from it now for everyone (`team_files`): Home ▸ Online shows that team list for the server in Preferences, a row joins its file, and its links (`figcraft://join?server=…&file=…&team=1`, or the browser build's) carry no secret and stop working with the share. No accounts, teams or projects | 8–17 |
|
||||
| Comments: pins on frames and layers, threads, reactions, @mentions, resolve, unread, search and filters, links, in the presenter | yes (shared) | **done, local**: stored in the file, your name from Preferences (an AI agent attached over MCP comments as its own name, marked Agent); a behaviour suite from the documentation (pinning and following layers, threads, own edits and deletes, mentions, reactions, C and Shift+C, stepping, filters, saving, copy and paste); restoring a version keeps them. `comment.list` (CLI, MCP) gives each message its `mentions` (`{name, known, you}`, by the highlighting rule). In a live session threads sync and anyone in it can reply, react and resolve (no accounts: a name is who you are) | (shared once multiplayer lands) |
|
||||
| Version history: named versions, autosave checkpoints, view before restore, restore, duplicate | yes (cloud) | **done**, saved in the `.figcraft` file: restoring keeps the replaced design as an autosave first, a titled autosave becomes a named version, merging a branch records the file before and after. Versions are per person in a live session (a shared history needs accounts); no comparing two versions (Dev Mode compares a ready-for-dev layer with its state when marked) | — |
|
||||
| Branching and merging | yes (paid plans) | **done, also in live sessions**: branches saved in the `.figcraft` file, each opened in its own tab; Review and merge shows both sides' changes since the branch was made and the conflicts (the same property on both sides, or a layer deleted on one side and edited on the other), each resolved for the branch or main; merge as one undo step (the branch is archived, the main file's history gets a version for the merge), update from main, archive. Each branch keeps its own version history (saved, viewed and restored on the branch tab, kept when it is merged or archived; entries for its creation and updates from main); fills, strokes, effects, layout grids, export settings, guides, interactions, annotations and Dev Mode resources merge item by item. In a live session a branch stays with its author (its ids in their own client space, far above the main file's) and merging it is one edit everyone gets; peers' edits merge against the branch's own base and conflicts resolve as offline; a view link refuses merging. Left: others in the session can't see or open your branches (the server would have to keep them); text runs conflict as a whole; a branch made offline that adds layers merges only outside a session | 1–2 |
|
||||
| Branching and merging | yes (paid plans) | **done, also in live sessions**: branches saved in the `.figcraft` file, each opened in its own tab; Review and merge shows both sides' changes since the branch was made and the conflicts (the same property on both sides, or a layer deleted on one side and edited on the other), each resolved for the branch or main; merge as one undo step (the branch is archived, the main file's history gets a version for the merge), update from main, archive. Each branch keeps its own version history (saved, viewed and restored on the branch tab, kept when it is merged or archived; entries for its creation and updates from main); fills, strokes, effects, layout grids, export settings, guides, interactions, annotations and Dev Mode resources merge item by item. Auto layout settings (a frame's and a child's) merge field by field, each field changed both ways a conflict of its own (`<id>/layout.padding`), and sizes and places auto layout works out (hugging, filling, a child's place) or that an instance takes from its main are no conflict: the merged file lays them out again. In a live session a branch stays with its author (its ids in their own client space, far above the main file's) and merging it is one edit everyone gets; peers' edits merge against the branch's own base and conflicts resolve as offline; a view link refuses merging. Left: others in the session can't see or open your branches (the server would have to keep them); text runs conflict as a whole; a branch made offline that adds layers merges only outside a session | 1–2 |
|
||||
| Team / organization libraries | yes | **partial**: a file's library is published to `figcraft-server` under the file and enabled in other files by a share link (per-asset versions, background update checks, overrides kept), usage counts per component and file, swapping a library by names ([components-parity](components-parity.md), [server.md](server.md#team-libraries)). No team-wide library list, accounts or analytics over time | 4–8 |
|
||||
| Notifications, activity | yes | no | with sharing |
|
||||
|
||||
@@ -26,6 +26,7 @@ cursors, selections, text carets, cursor chat and spotlights shown live ([`colla
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-11-06 | patch | M9, #2026: one conflicting auto layout edit added a conflict for every size and place it moved (a padding changed on both sides of a file with one instance gave 10, with 15 instances 138), and a `layout` conflict took all auto layout fields together, so a gap changed only on the branch was lost if main won the padding. `merge::plan` now leaves out values both sides work out for themselves: a hugging frame's or a filling child's size, text sizing to its characters, an auto layout child's place (when both sides turn it the same way) and a value a layer in an instance takes from its main; merging keeps the file merged into's own value and normalising lays it out from the merged inputs. `layout` and `childLayout` merge field by field: a field changed on one side merges, each field changed both ways is its own conflict (`<id>/layout.padding`, shown as auto layout padding with both sides' values). Tests: `branch_tests::one_conflicting_auto_layout_edit_is_one_conflict`, `branch_tests::auto_layout_fields_changed_one_way_survive_a_conflict`, `branch_tests::sizes_auto_layout_works_out_never_conflict`; the merge fuzz test leaves worked-out values out of what each side must show |
|
||||
| 2026-11-06 | minor | M9: a file shared on the local network can be shared read-only. The session the app hosts has a second secret, so a view-only code next to the edit code (same address and port, a 44-bit secret of its own); whoever joins with it is welcomed as a viewer, sees every change and presence, gets the "View only" badge and only the moving tools, and the session refuses their edits. The Share popover offers Can edit / Can view under Local network before sharing starts (the edit code then never shows) and while sharing; `collab.share {via: "local", access: "view"}` does the same (its `link` and `url`, like its `code`, are the view-only way in), and `share` in `collab.peers` lists both codes and links. No comment code on the local network. Numbers unchanged. |
|
||||
| 2026-10-31 | patch | M9, #1665: the document in a live session's welcome goes compressed (deflate) to clients whose hello announces `packed`, about seven times smaller on the wire (a synthetic file of 4,040 layers: 397 KB to 53 KB); older clients keep getting it uncompressed, and the client reads a packed document only up to the size an uncompressed welcome could have had. |
|
||||
| 2026-10-30 | minor | M9, part of #742: a team list on `figcraft-server`. With `team_files = "edit"` (or `comment`, `view`) everyone who reaches the server sees the files shared from it now (a link of theirs has a join code: Share ▸ Start sharing) and joins them by a team list link, `figcraft://join?server=…&file=…&team=1`, which carries no secret: the server hands out the file's team link while it stays shared (`ResolveTeam`, answered like a join code), and Stop sharing revokes it with the others, disconnecting whoever joined with it. Turning the list off or changing its access refuses the old team links at once. `collab.files {refresh}` asks the server in Preferences for its list (`Admin::Team`; not the public server FigCraft ships with), and Home ▸ Online shows it below your own files: a row joins its file, its menu copies the link for the app or, with the server's `web_url`, for the browser build (`<web_url>#join=…`). A browser build served beside its server names it with `<meta name="figcraft-server">`, the page's default for sharing, codes and the team list. No accounts: the list is for a server only your team reaches. Tests: `team_tests` (the server and apps over loopback), `code_tests` (links and the browser's driver), `online_tests` (the Online section), `query_tests` (the page's server). Percentages and hours unchanged |
|
||||
|
||||
+4
-1
@@ -1353,7 +1353,10 @@ branches). Driven with `run_command`:
|
||||
export settings, guides, prototype interactions, annotations and Dev Mode resources compare item
|
||||
by item, so changing different items of one list on each side, or adding items at its end on one
|
||||
side, merges without a conflict; other lists, such as code links, compare whole; a layer's parent
|
||||
and position are one property, `parent`), a layer deleted on one side while the other edited it or what's inside it
|
||||
and position are one property, `parent`; auto layout settings, `layout` and `childLayout`, compare
|
||||
field by field, each field changed both ways its own conflict, `<layer id>/layout.padding`; sizes and
|
||||
places auto layout works out, and values a layer in an instance takes from its main, are never
|
||||
conflicts: the merged file works them out again), a layer deleted on one side while the other edited it or what's inside it
|
||||
(`<layer id>/layer`, with `deletedBy`), or a document-level entry or setting changed on both sides
|
||||
(`style/<id>`, `variable/<id>`, `comment/<id>`, `doc/<property>`…).
|
||||
- `branch.merge {id?, resolutions?}` merges the branch into the main file as one undo step,
|
||||
|
||||
+5
-2
@@ -121,8 +121,11 @@ a missing required face, style or asset fails the required web build. Excluded A
|
||||
are skipped before resolving their asset paths.
|
||||
Native builds retain the permitted Latin presentation faces. Source Sans 3 and Source Serif 4
|
||||
are filtered on every target under FigCraft's asset policy. The web build keeps its smaller
|
||||
allowlist: Inter, Noto Sans Georgian and Archivo SemiBold when supplied. Packages carry each
|
||||
embedded font's licence as `OFL-<family>.txt`
|
||||
allowlist: Inter, Noto Sans Georgian and Archivo SemiBold when supplied. A distribution whose
|
||||
users write another script adds the manifest families it needs, comma-separated, with
|
||||
`FIGCRAFT_WEB_FONTS` (`FIGCRAFT_WEB_FONTS="Noto Sans Thai" trunk build --release`); a named family
|
||||
the build doesn't embed gets a warning, and each one adds its size to the wasm, which must stay
|
||||
under the size gate in `packaging/web/package.sh`. Packages carry each embedded font's licence as `OFL-<family>.txt`
|
||||
(`copy_font_licences` in `packaging/env.sh`; `Contents/Resources/Licenses` in the macOS app).
|
||||
|
||||
### macOS
|
||||
|
||||
@@ -75,6 +75,7 @@ blockers.
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-11-03 | patch | M4, #1747: a text layer still carrying the name its characters gave it is renamed as they are typed, so the Layers panel no longer shows the word a layer started with while the canvas shows another (`hello` typed into `hello there` read as `hello` in the panel). A name the author typed is kept, and only the editor follows the characters: commands leave the name alone, so the layer names `data.fill`, component property bindings and templates use as field keys stay put. Tests: `text_behaviour_tests::typing_renames_a_text_layer_that_still_carries_the_name_its_characters_gave_it`, `setting_characters_as_a_command_never_renames_the_layer`. Grade unchanged |
|
||||
| 2026-10-31 | minor | M12: as the help describes, holding Cmd/Ctrl while moving a connector's end places it on any part of an object instead of snapping to a side. It keeps that spot as a fraction of the object's box, so it follows the object when it moves or resizes, and without the key an end snaps as before. `board.connector {fromAt, toAt}` and `board.reattach {at}` take it; saved only when set. Numbers unchanged |
|
||||
| 2026-10-31 | patch | M11: a trackpad or touch tap sends its press and release in one frame, so a plugin panel's field committed in the frame its button was clicked and the value was lost: the Counter's Set count… kept the old count. The plugin now gets both, the field's value first. The `window.figcraft` docs name `screenshot`'s `data`. Numbers unchanged |
|
||||
| 2026-10-31 | patch | M4: Dash and Custom strokes have a Dash cap (None, Round, Square) in the advanced stroke settings and `node.set {dashCap}`, on both ends of every dash on the canvas and in PNG, PDF and SVG. Unset, dashes keep taking the end point caps, so older files look the same; the saved file writes it only when set. Numbers unchanged |
|
||||
|
||||
@@ -654,6 +654,7 @@ Carried over from the ROADMAP's "Shipped so far" (2026-10-10). The test count th
|
||||
| 2026-11-02 | minor | M3, #1885: glass bends towards its core, the shape shrunk by `depth` and the bevel, as the reference tool's: round a sharp corner the bend turns smoothly, and a thin part (a capsule, a letter's stroke) bends across itself, checked side by side on a capsule 44 units tall. Rounded rectangles work it out in closed form. A shape too big to keep whole at the zoom bends along its edge normals instead, so no render works out a core over more pixels than a kept shape holds. Tests: `glass::tests::a_sharp_corner_bends_round_towards_the_core`, `glass::tests::a_thin_part_bends_across_itself`, `glass::tests::a_shape_too_big_to_keep_bends_along_its_normals`, `glass_cut_tests::a_cut_through_the_pane_matches_the_whole_render`. Grade unchanged. |
|
||||
| 2026-11-02 | minor | M3, #1885: glass's light is a line on its 1-unit bevel added to the backdrop, as the reference tool's: fully where the edge faces the light, none below 0.35 of facing it, 0.6 as much on the opposite side, with a faint gradient across the curve. `splay` turns the bend from along the edge's normal towards the way away from the layer's centre and no longer widens the light, as in the reference tool. Checked side by side on synthetic files: a splay of 1 bends the backdrop towards the centre in both. Tests: `glass::tests::the_light_lies_on_the_bevel_and_the_gradient_across_the_curve`, `backdrop_tests::splay_turns_the_bend_towards_the_centre`, `glass_cut_tests::the_light_is_a_line_on_the_bevel`. Grade unchanged. |
|
||||
| 2026-11-02 | minor | M3, #1885: glass bends the backdrop with the reference tool's thick-lens profile (most a 1-unit bevel in from the edge, falling off as the 3.5th power of the way out of the curve to nothing `depth` further in) and splits its colours over 8 steps, red and blue 0.16 of the bend apart at 100% dispersion. Measured against the reference tool on synthetic files at 2×: the black band a pane pulls to its edge ends within 3 px of the reference tool's, and red and blue part 2.27 px at 50% dispersion and 4.66 px at 100% (2.38 and 4.69 there). Tests: `glass::tests::the_bend_follows_the_thick_lens_profile`, `glass::tests::dispersion_splits_the_channels_along_the_bend`. Grade unchanged. |
|
||||
| 2026-11-03 | patch | M4, #1747: a text layer still carrying the name its characters gave it is renamed as they are typed, so the Layers panel no longer shows the word a layer started with while the canvas shows another (`hello` typed into `hello there` read as `hello` in the panel). A name the author typed is kept, and only the editor follows the characters: commands leave the name alone, so the layer names `data.fill`, component property bindings and templates use as field keys stay put. Tests: `text_behaviour_tests::typing_renames_a_text_layer_that_still_carries_the_name_its_characters_gave_it`, `setting_characters_as_a_command_never_renames_the_layer`. Grade unchanged |
|
||||
| 2026-11-01 | patch | M4: bulleted lists draw the same bullet at every level of indentation ("Figma bullets will keep the same styling at all levels of indentation", Create bulleted and numbered lists); the deeper levels drew a white bullet and a small square, pinned as silent before. Numbered levels (1., a., i.) are unchanged. Found by a documentation audit of the text rules. Test: `tail_tests::list_numbering_by_level` (the bullets row). Numbers unchanged |
|
||||
| 2026-11-01 | patch | M4: typing `1)` followed by a space at the start of a plain paragraph starts a numbered list, as `1.` already did ("Enter one of the creation characters below followed by a Space: 1. 1)", Create bulleted and numbered lists). Found by a documentation audit of the text rules. Test: `text_tail_tests::typing_a_creation_character_and_a_space_starts_a_list`. Numbers unchanged |
|
||||
| 2026-11-01 | patch | M4: a link made with `text.link` (Cmd/Ctrl+K, Shift+Cmd/Ctrl+U) underlines the linked text unless it has a decoration of its own ("Links are styled with an underline by default. Use the keyboard shortcut to remove the underline", Add links to text); Underline (Cmd/Ctrl+U) takes the underline off and the link stays. Found by a documentation audit of the text rules. Test: `text_behaviour_tests::a_link_is_underlined_by_default_and_underline_takes_it_off`. Numbers unchanged |
|
||||
|
||||
Reference in new issue
Block a user